diff --git a/Cargo.lock b/Cargo.lock index 311a6103e6..f96f6cc14c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4587,6 +4587,7 @@ dependencies = [ "serde_json", "sys-locale", "toml", + "unicode-bidi", ] [[package]] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 479de86891..652a883ede 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -36,6 +36,8 @@ log = { workspace = true } base64 = "0.22" # Inflating the translation catalogs, stored deflated (build.rs); already linked through photocraft-io. flate2 = { workspace = true } +# Visual order for right-to-left labels (`bidi_label.rs`); already in the tree through usvg/resvg. +unicode-bidi = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } diff --git a/crates/ui-egui/src/bidi_label.rs b/crates/ui-egui/src/bidi_label.rs new file mode 100644 index 0000000000..3fde458a9a --- /dev/null +++ b/crates/ui-egui/src/bidi_label.rs @@ -0,0 +1,86 @@ +//! Visual order for single-line labels that contain right-to-left text (Arabic, Persian, Urdu, +//! Hebrew, Kurdish …), such as layer names. +//! +//! egui 0.36 shapes each font run with HarfRust, so an Arabic or Hebrew word is drawn right to +//! left with its letters joined. What it lacks is paragraph bidi: it places a line's runs left to +//! right in logical order, so `سلام عليكم` draws as `عليكم سلام`. [`for_egui`] puts the runs in +//! visual order with the Unicode bidi algorithm, but leaves the letters of every stretch egui +//! reverses by itself in logical order. Reversing those too (`reorder_line`) mirrors each word, +//! picks joining forms from the wrong neighbours and loses the لا ligature. +//! +//! Only for painted, single-line text: wrapping and eliding happen on the logical string first +//! (see [`crate::layer_row_ui::truncated`]), and editable text and accessibility labels keep the +//! logical string. Known gap: Arabic-Indic digits written against Arabic letters with no space +//! (`طبقة١`) share one egui run with them and land on the wrong side. Remove this once egui +//! orders runs by bidi level itself (emilk/egui#8577). + +use std::borrow::Cow; + +use unicode_bidi::BidiInfo; + +/// Does `text` contain a character from a right-to-left script? +pub fn has_rtl(text: &str) -> bool { + text.chars().any(rtl_script) +} + +/// Characters egui shapes right to left: those of the right-to-left scripts (HarfRust guesses a +/// run's direction from its script), including their marks and digits. The joiners count too, +/// so a Persian word with a ZWNJ stays one stretch. +fn rtl_script(c: char) -> bool { + matches!( + c as u32, + 0x0590..=0x05FF // Hebrew + | 0x0600..=0x06FF // Arabic (letters, marks, Arabic-Indic and Persian digits) + | 0x0700..=0x074F // Syriac + | 0x0750..=0x077F // Arabic Supplement + | 0x0780..=0x07BF // Thaana + | 0x07C0..=0x07FF // NKo + | 0x0860..=0x08FF // Syriac Supplement, Arabic Extended-A/B + | 0xFB1D..=0xFB4F // Hebrew presentation forms + | 0xFB50..=0xFDFF // Arabic Presentation Forms-A + | 0xFE70..=0xFEFF // Arabic Presentation Forms-B + | 0x10800..=0x10FFF // Historic RTL scripts + | 0x1E800..=0x1EFFF // Mende Kikakui, Adlam, Arabic mathematical symbols + ) || matches!(c, '\u{200C}' | '\u{200D}') +} + +/// `text` arranged so that egui draws it in visual order. Text without right-to-left characters +/// is returned unchanged. +pub fn for_egui(text: &str) -> Cow<'_, str> { + if !has_rtl(text) { + return Cow::Borrowed(text); + } + let info = BidiInfo::new(text, None); + let mut out = String::with_capacity(text.len()); + for para in &info.paragraphs { + let (levels, runs) = info.visual_runs(para, para.range.clone()); + for run in runs { + let Some(s) = text.get(run.clone()) else { continue }; + let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); + // A right-to-left run must read backwards on screen: reverse it, then turn back each + // stretch egui reverses again. A left-to-right run (Latin, digits) reads as written, + // so only egui's stretches inside it (Arabic-Indic digits) are pre-reversed. + let shown: String = if rtl { s.chars().rev().collect() } else { s.to_owned() }; + push_unreversing_rtl_stretches(&mut out, &shown); + } + } + Cow::Owned(out) +} + +/// Append `s`, reversing each maximal stretch of right-to-left-script characters. +fn push_unreversing_rtl_stretches(out: &mut String, s: &str) { + let mut stretch: Vec = Vec::new(); + for c in s.chars() { + if rtl_script(c) { + stretch.push(c); + } else { + out.extend(stretch.drain(..).rev()); + out.push(c); + } + } + out.extend(stretch.into_iter().rev()); +} + +#[cfg(test)] +#[path = "bidi_label_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/bidi_label_tests.rs b/crates/ui-egui/src/bidi_label_tests.rs new file mode 100644 index 0000000000..29ee2945f2 --- /dev/null +++ b/crates/ui-egui/src/bidi_label_tests.rs @@ -0,0 +1,147 @@ +//! The bidi pre-pass: string rules everywhere, and what egui actually draws when an Arabic or +//! Hebrew system font is installed. + +use super::*; +use egui::epaint::text::{FontData, FontDefinitions, FontFamily, Fonts, LayoutJob, TextFormat, TextOptions}; +use std::sync::Arc; + +#[test] +fn text_without_right_to_left_characters_is_untouched() { + for s in ["Layer 1", "", "Background copy 2", "图层 1", "Ебать"] { + assert!(matches!(for_egui(s), Cow::Borrowed(t) if t == s), "{s}"); + } +} + +#[test] +fn right_to_left_words_swap_places_but_keep_their_letters() { + // egui reverses each word's letters itself; only the word order changes here. + assert_eq!(for_egui("سلام عليكم"), "عليكم سلام"); + assert_eq!(for_egui("שלום עולם"), "עולם שלום"); + assert_eq!(for_egui("ئەمە تێستە بۆ ئیش"), "ئیش بۆ تێستە ئەمە"); + // One word: nothing to reorder. + assert_eq!(for_egui("طبقة"), "طبقة"); +} + +#[test] +fn numbers_and_latin_keep_reading_left_to_right() { + // European digits and Latin are runs of their own, in the right visual place. + assert_eq!(for_egui("عدد 123 مرحبا"), "مرحبا 123 عدد"); + assert_eq!(for_egui("طبقة 1 Layer"), "Layer 1 طبقة"); + // Arabic-Indic digits are Arabic-script, which egui reverses: pre-reversed so they read ١٢٣. + assert_eq!(for_egui("شلام ١٢٣ x"), "x ٣٢١ شلام"); + // A left-to-right label keeps its order; a number right after an Arabic word belongs to it + // (UAX #9 W2), as in browsers. + assert_eq!(for_egui("Layer طبقة"), "Layer طبقة"); + assert_eq!(for_egui("Layer طبقة 2"), "Layer 2 طبقة"); +} + +#[test] +fn persian_joiners_stay_inside_their_word() { + // "می‌خواهم" has a ZWNJ: still one word, letters untouched. + assert_eq!(for_egui("می\u{200C}خواهم سلام"), "سلام می\u{200C}خواهم"); +} + +/// An installed font covering `sample`, if any of the usual ones is present. +fn system_font(candidates: &[&str]) -> Option> { + candidates.iter().find_map(|p| std::fs::read(p).ok()) +} + +const ARABIC_FONTS: [&str; 6] = [ + "/System/Library/Fonts/GeezaPro.ttc", + "/System/Library/Fonts/SFArabic.ttf", + "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf", + "/usr/share/fonts/noto/NotoSansArabic-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "C:\\Windows\\Fonts\\arial.ttf", +]; + +fn fonts_with(bytes: Vec) -> Fonts { + let mut defs = FontDefinitions::default(); + defs.font_data.insert("rtl-test".into(), Arc::new(FontData::from_owned(bytes))); + if let Some(family) = defs.families.get_mut(&FontFamily::Proportional) { + family.push("rtl-test".into()); + } + Fonts::new(TextOptions::default(), defs) +} + +/// x of each drawn (non-continuation) glyph, with the character it was attributed to. +fn drawn(fonts: &mut Fonts, text: &str) -> Vec<(char, f32)> { + let mut job = LayoutJob::default(); + job.append(text, 0.0, TextFormat { font_id: egui::FontId::proportional(20.0), ..Default::default() }); + let galley = fonts.with_pixels_per_point(1.0).layout_job(job); + galley.rows.iter().flat_map(|r| r.glyphs.iter()).filter(|g| !g.uv_rect.is_nothing()).map(|g| (g.chr, g.pos.x)).collect() +} + +fn x_of(glyphs: &[(char, f32)], c: char) -> f32 { + glyphs.iter().find(|(g, _)| *g == c).map(|(_, x)| *x).unwrap_or_else(|| panic!("{c} drawn: {glyphs:?}")) +} + +#[test] +fn arabic_draws_first_word_rightmost_with_letters_joined() { + let Some(bytes) = system_font(&ARABIC_FONTS) else { + eprintln!("skipped: no Arabic system font"); + return; + }; + let mut fonts = fonts_with(bytes); + let shown = drawn(&mut fonts, &for_egui("سلام عليكم")); + // The first word (سلام) is on the right: its first letter right of the second word's. + assert!(x_of(&shown, 'س') > x_of(&shown, 'ع'), "{shown:?}"); + // سلام draws as three glyphs (س, the لا ligature, م): the letters kept their logical order. + // Reversed letters (مالس) can't form the ligature and draw four. + let word = drawn(&mut fonts, &for_egui("سلام")); + let mirrored = drawn(&mut fonts, "مالس"); + assert!(word.len() < mirrored.len(), "ligature: {word:?} vs {mirrored:?}"); +} + +#[test] +fn hebrew_draws_first_word_rightmost() { + let Some(bytes) = system_font(&[ + "/System/Library/Fonts/SFHebrew.ttf", + "/System/Library/Fonts/ArialHB.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "C:\\Windows\\Fonts\\arial.ttf", + ]) else { + eprintln!("skipped: no Hebrew system font"); + return; + }; + let mut fonts = fonts_with(bytes); + let shown = drawn(&mut fonts, &for_egui("שלום עולם")); + // ש starts the first word, ע the second: ש is further right. + assert!(x_of(&shown, 'ש') > x_of(&shown, 'ע'), "{shown:?}"); +} + +#[test] +fn a_long_right_to_left_layer_name_keeps_its_beginning() { + let Some(bytes) = system_font(&ARABIC_FONTS) else { + eprintln!("skipped: no Arabic system font"); + return; + }; + let name = "سلام عليكم يا أصدقاء الطبقات"; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 100.0)).build_ui_state( + |ui, out: &mut Option>| { + *out = crate::layer_row_ui::truncated(ui.painter(), name, egui::FontId::proportional(20.0), egui::Color32::WHITE, false, 90.0); + }, + None, + ); + let mut defs = FontDefinitions::default(); + defs.font_data.insert("rtl-test".into(), Arc::new(FontData::from_owned(bytes))); + if let Some(family) = defs.families.get_mut(&FontFamily::Proportional) { + family.push("rtl-test".into()); + } + h.ctx.set_fonts(defs); + h.run_steps(3); + let g = h.state().clone().expect("room for a cut name"); + let shown = g.job.text.clone(); + assert!(g.size().x <= 90.0, "{} wide", g.size().x); + // Cut in logical order: the first word survives, and "…" sits at the reading end (left). + assert!(shown.starts_with('…') && shown.contains("سلام") && !shown.contains("الطبقات"), "{shown}"); + // Short enough to fit: drawn whole. + let mut short = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 100.0)).build_ui_state( + |ui, out: &mut Option>| { + *out = crate::layer_row_ui::truncated(ui.painter(), "سلام عليكم", egui::FontId::proportional(20.0), egui::Color32::WHITE, false, 300.0); + }, + None, + ); + short.run_steps(1); + assert_eq!(short.state().as_ref().map(|g| g.job.text.clone()).as_deref(), Some("عليكم سلام")); +} diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs index d265690597..84a38179b0 100644 --- a/crates/ui-egui/src/layer_row_ui.rs +++ b/crates/ui-egui/src/layer_row_ui.rs @@ -89,17 +89,56 @@ pub fn indent(depth: usize, row_width: f32, fixed: f32) -> f32 { (depth as f32 * 14.0).min((row_width - fixed - MIN_NAME_W).max(0.0)) } -/// A single-line galley cut with "…" to `max_width` (nothing when there's no room). +/// A single-line galley cut with "…" to `max_width` (nothing when there's no room). Right-to-left +/// text (an Arabic or Hebrew layer name) is drawn in visual order, see [`crate::bidi_label`]. pub fn truncated(painter: &Painter, text: &str, font: FontId, color: egui::Color32, italics: bool, max_width: f32) -> Option> { if max_width < 8.0 { return None; } + if crate::bidi_label::has_rtl(text) { + return truncated_bidi(painter, text, font, color, italics, max_width); + } let mut job = egui::text::LayoutJob::default(); job.append(text, 0.0, egui::TextFormat { font_id: font, color, italics, ..Default::default() }); job.wrap = egui::text::TextWrapping { max_width, max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; Some(painter.layout_job(job)) } +/// [`truncated`] for text with right-to-left characters. egui elides the end of the string it is +/// given, which after reordering would be the start of a right-to-left name, so the name is cut in +/// logical order (keeping its beginning) and then reordered; the "…" lands at its reading end. +fn truncated_bidi(painter: &Painter, text: &str, font: FontId, color: egui::Color32, italics: bool, max_width: f32) -> Option> { + let lay = |s: &str| { + let mut job = egui::text::LayoutJob::single_section( + crate::bidi_label::for_egui(s).into_owned(), + egui::TextFormat { font_id: font.clone(), color, italics, ..Default::default() }, + ); + job.wrap.max_rows = 1; + painter.layout_job(job) + }; + let whole = lay(text); + if whole.size().x <= max_width { + return Some(whole); + } + // The longest prefix (in characters) that fits with "…" after it. Galleys are cached by + // content, so an unchanged row costs no layout on later frames. + let ends: Vec = text.char_indices().map(|(i, _)| i).collect(); + let (mut lo, mut hi) = (0usize, ends.len()); + let mut best = None; + while lo < hi { + let mid = (lo + hi).div_ceil(2); + let cut = ends.get(mid).copied().unwrap_or(text.len()); + let g = lay(&format!("{}…", text.get(..cut).unwrap_or(text).trim_end())); + if g.size().x <= max_width { + best = Some(g); + lo = mid; + } else { + hi = mid - 1; + } + } + best.or_else(|| Some(lay("…")).filter(|g| g.size().x <= max_width)) +} + /// Paint `l`'s right-hand indicators in `row` and handle the effects triangle. Returns the /// name's right limit, the indicator rects, and whether the triangle was clicked this frame (so /// the row doesn't also treat the click as a selection). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0adf31b0f2..69676905e7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -22,6 +22,7 @@ pub mod adjust_ui; mod alt_grab; pub mod analysis_ui; pub mod artboard_ui; +pub mod bidi_label; pub(crate) mod blend_preview; mod brand; pub mod brush_panel;