diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs index a14d032153..698768edc5 100644 --- a/crates/data/src/display_marks.rs +++ b/crates/data/src/display_marks.rs @@ -1,11 +1,14 @@ -//! The marks right-to-left display text carries. An interface that lays a line out back to -//! front rewrites it for painting (`ui-egui`'s `i18n::rtl`) and marks what it rewrote, so that +//! Right-to-left display text and the marks it carries. An interface that lays a line out back +//! to front rewrites it for painting ([`visual`]) and marks what it rewrote, so that //! text leaving the screen (a notice, a file name, the clipboard) can be put back in logical //! order ([`logical`]), and text kept to be painted as it is (a command's parameters) can lose //! the marks alone ([`unmarked`]). +use std::collections::HashMap; + // Invisible, of no width and no direction. A start and an end differ, so that a mark with no -// partner, cut from its pair or part of the data, is told apart and left where it is. +// partner, cut from its pair or part of the data, is told apart and left where it is. Data can +// hold a pair too, so one is read only around exactly what `visual` makes of its text. /// Before a rewritten line. pub const LINE_START: char = '\u{2063}'; @@ -37,15 +40,15 @@ pub fn mirror(c: char) -> char { } /// `shown` with what was rewritten for display put back in logical order, and the marks -/// around it gone; `None` when no line holds a start mark and its end. Only what stands between -/// the two is reordered; text around it, and a mark with no partner, stay as they are. +/// around it gone; `None` when no line holds a display form. Only a form [`visual`] makes is +/// reordered; text around it, and any other mark, stay as they are. #[must_use] pub fn logical(shown: &str) -> Option { unmark(shown, true) } /// `shown` without the marks [`logical`] would read, its characters left where they are: a -/// display form kept as data that is painted as it is. `None` when no line holds a pair. +/// display form kept as data that is painted as it is. `None` when no line holds one. #[must_use] pub fn unmarked(shown: &str) -> Option { unmark(shown, false) @@ -60,56 +63,301 @@ fn unmark(shown: &str, reorder: bool) -> Option { (text != shown).then_some(text) } -/// One line of [`unmark`]. +/// One line of [`unmark`]: each pair of line marks around what [`shaped_line`] makes is +/// undone; everything else, a pair that data holds included, stays as it is. fn unmark_line(line: &str, reorder: bool) -> String { + if !line.contains(MARKS) { + return line.to_owned(); + } let chars: Vec = line.chars().collect(); - let lines = Pairs::of(&chars, LINE_START, LINE_END); - let runs = Pairs::of(&chars, RUN_START, RUN_END); let mut out = String::with_capacity(line.len()); - let mut run: Vec = Vec::new(); - let marks = lines.mark.into_iter().zip(runs.mark).map(|(a, b)| a || b); - for (((c, mark), in_line), in_run) in chars.into_iter().zip(marks).zip(lines.inside).zip(runs.inside) { - if reorder && in_run && !mark { - run.push(mirror(c)); + let mut done = 0; + for (from, to) in pairs(&chars, LINE_START, LINE_END) { + let (Some(before), Some(form), Some(inside)) = (chars.get(done..from), chars.get(from..=to), chars.get(from + 1..to)) else { + continue; + }; + let logical = undone(inside, true); + if !shaped_line(&logical).chars().eq(form.iter().copied()) { continue; } - out.extend(run.drain(..).rev()); - if !mark { - out.push(if reorder && in_line { mirror(c) } else { c }); + out.extend(before); + out.push_str(&if reorder { logical } else { undone(inside, false) }); + done = to + 1; + } + out.extend(chars.iter().skip(done)); + out +} + +/// What stands between a line's marks, without its runs' marks: put back in logical order +/// when `reorder` (each run reversed, every bracket mirrored), else left where it is. +fn undone(inside: &[char], reorder: bool) -> String { + let flow = |c: &char| if reorder { mirror(*c) } else { *c }; + let mut out = String::new(); + let mut done = 0; + for (from, to) in pairs(inside, RUN_START, RUN_END) { + let (Some(before), Some(run)) = (inside.get(done..from), inside.get(from + 1..to)) else { + continue; + }; + out.extend(before.iter().map(flow)); + if reorder { + out.extend(run.iter().rev().map(flow)); + } else { + out.extend(run); } + done = to + 1; } - out.extend(run.drain(..).rev()); + out.extend(inside.iter().skip(done).map(flow)); out } -/// Where the complete pairs of one start and end mark are in a line, character by character. -struct Pairs { - /// Whether it stands between a start and the end that closes it, both included. - inside: Vec, - /// Whether it is one of those two marks. - mark: Vec, -} - -impl Pairs { - fn of(chars: &[char], start: char, end: char) -> Self { - let mut pairs = Self { inside: vec![false; chars.len()], mark: vec![false; chars.len()] }; - let mut open = None; - for (i, c) in chars.iter().enumerate() { - if *c == start { - open = Some(i); - } else if *c == end - && let Some(from) = open.take() - { - if let Some(span) = pairs.inside.get_mut(from..=i) { - span.fill(true); +/// Where the complete pairs of one start and end mark are in a line: the latest start, and the +/// end that closes it. +fn pairs(chars: &[char], start: char, end: char) -> Vec<(usize, usize)> { + let mut found = Vec::new(); + let mut open = None; + for (i, c) in chars.iter().enumerate() { + if *c == start { + open = Some(i); + } else if *c == end + && let Some(from) = open.take() + { + found.push((from, i)); + } + } + found +} + +/// A character of a script written right to left (Arabic, Persian, Hebrew). Digits +/// read left to right, and the comma, semicolon and question mark take the line's +/// direction, so none of them are script letters here. +fn rtl_script(c: char) -> bool { + if matches!(c as u32, 0x0660..=0x066C | 0x06F0..=0x06F9 | 0x060C | 0x061B | 0x061F) { + return false; + } + matches!(c as u32, + 0x0590..=0x05FF // Hebrew + | 0x0600..=0x06FF // Arabic + | 0x0750..=0x077F + | 0x08A0..=0x08FF + | 0xFB1D..=0xFDFF // presentation forms + | 0xFE70..=0xFEFF) +} + +/// A character of a left-to-right run: a letter or number of any script but a +/// right-to-left one (Latin, Cyrillic, Greek, CJK, accented letters, superscripts), +/// or a Persian or Arabic digit. +fn ltr(c: char) -> bool { + c.is_alphanumeric() && !rtl_script(c) +} + +/// A digit of either script: what the degree sign attaches to. +fn digit(c: char) -> bool { + c.is_ascii_digit() || matches!(c as u32, 0x0660..=0x0669 | 0x06F0..=0x06F9) +} + +/// A left-to-right letter: what brackets pair onto (they close around letters, not +/// numbers). +fn letter(c: char) -> bool { + c.is_alphabetic() && !rtl_script(c) +} + +/// What the toolkit's direction guess makes of a character: `Some(true)` — of a +/// right-to-left script, the line start that is laid out back to front (the digits +/// of the Arabic block included, for their script is Arabic); `Some(false)` — of a +/// left-to-right script (Latin, Cyrillic, Greek, CJK…); `None` — of no script of +/// its own (digits, punctuation, marks, controls), which the guess skips. +#[must_use] +pub fn strong(c: char) -> Option { + if rtl_script(c) || matches!(c as u32, 0x0660..=0x0669 | 0x06F0..=0x06F9) { + Some(true) + } else if c.is_alphabetic() { + Some(false) + } else { + None + } +} + +fn opening(c: char) -> bool { + matches!(c, '(' | '[' | '{' | '«' | '‹') +} + +fn closing(c: char) -> bool { + matches!(c, ')' | ']' | '}' | '»' | '›') +} + +/// Whether any right-to-left text is in `s`: a cheap check before any work. +#[must_use] +pub fn has_rtl(s: &str) -> bool { + s.chars().any(rtl_script) +} + +/// Whether `s` starts, past characters of no script of their own, with one of a +/// right-to-left script: the lines the toolkit lays out back to front. A string +/// of no strong character at all is laid out front to back. +#[must_use] +pub fn back_to_front(s: &str) -> bool { + s.chars().find_map(strong) == Some(true) +} + +/// `s` in the form that reads correctly when laid out back to front: each +/// left-to-right run reversed (the line's own reversal puts it back), and every bracket +/// mirrored (the shaper mirrors them all back). Everything else is untouched, so the shaper still +/// joins the right-to-left text as written. Every line is rewritten on its own +/// strength; a line that starts left-to-right, a string with no right-to-left +/// text, and a line holding a mark of its data's own come back unchanged. A display +/// form put into a line is shaped as part of it. +#[must_use] +pub fn visual(s: &str) -> String { + if !has_rtl(s) { + return s.to_owned(); + } + s.split('\n').map(visual_line).collect::>().join("\n") +} + +/// One line of [`visual`]. Display forms put into it (a translated part of a message) are put +/// back in logical order first, so the line is shaped as a whole. A line that starts +/// left-to-right, or still holds a mark (its data's), comes back as it is. A line of Persian or +/// Arabic digits alone is back to front too, though [`has_rtl`] finds no letter in it. +#[must_use] +pub fn visual_line(line: &str) -> String { + let logical = unmark_line(line, true); + if !back_to_front(&logical) || logical.contains(MARKS) { + return line.to_owned(); + } + shaped_line(&logical) +} + +/// A line in logical order rewritten for display and marked: only when it starts back to front +/// and holds no mark, for one that does would come back from [`logical`] as something else. +fn shaped_line(line: &str) -> String { + if !back_to_front(line) || line.contains(MARKS) { + return line.to_owned(); + } + let chars: Vec = line.chars().collect(); + // The nearest run character before and after each position (1 left-to-right, + // 2 right-to-left): a neutral between two runs takes the side of both. + let mut before = vec![0u8; chars.len()]; + let mut seen = 0u8; + for (i, c) in chars.iter().enumerate() { + before[i] = seen; + if ltr(*c) { + seen = 1; + } else if rtl_script(*c) { + seen = 2; + } + } + let mut after = vec![0u8; chars.len()]; + let mut next = 0u8; + for i in (0..chars.len()).rev() { + after[i] = next; + if ltr(chars[i]) { + next = 1; + } else if rtl_script(chars[i]) { + next = 2; + } + } + // The nearest Latin letter before and after: a bracket joins a run when it opens + // or closes onto a letter, not onto a number (Unicode 'paired brackets'). + let mut letter_before = vec![0u8; chars.len()]; + let mut word_seen = 0u8; + for (i, c) in chars.iter().enumerate() { + letter_before[i] = word_seen; + if letter(*c) { + word_seen = 1; + } else if rtl_script(*c) { + word_seen = 2; + } + } + let mut letter_after = vec![0u8; chars.len()]; + let mut word_next = 0u8; + for i in (0..chars.len()).rev() { + letter_after[i] = word_next; + if letter(chars[i]) { + word_next = 1; + } else if rtl_script(chars[i]) { + word_next = 2; + } + } + // Paired brackets are resolved as one (Unicode BD16, N0): a pair joins the run + // only when both of its brackets would, and nothing right-to-left is inside, so + // its two brackets never land in different runs. + let mut partner: Vec> = vec![None; chars.len()]; + let mut open: Vec<(usize, char)> = Vec::new(); + // How many of each closing bracket are awaited: one that none awaits doesn't search + // `open`, and a search that finds one drops all it passed, so the line is walked once. + let mut awaited: HashMap = HashMap::new(); + for (i, c) in chars.iter().enumerate() { + if opening(*c) { + open.push((i, mirror(*c))); + *awaited.entry(mirror(*c)).or_default() += 1; + } else if awaited.get(c).is_some_and(|n| *n > 0) + && let Some(at) = open.iter().rposition(|(_, close)| close == c) + { + let o = open[at].0; + for (_, close) in open.drain(at..) { + if let Some(n) = awaited.get_mut(&close) { + *n = n.saturating_sub(1); } - for at in [from, i] { - if let Some(mark) = pairs.mark.get_mut(at) { - *mark = true; - } + } + partner[o] = Some(i); + partner[i] = Some(o); + } + } + // The right-to-left letters before each position, so that a pair's inside is not read again. + let rtl_count: Vec = std::iter::once(0) + .chain(chars.iter().scan(0, |n, c| { + *n += usize::from(rtl_script(*c)); + Some(*n) + })) + .collect(); + let alone = |i: usize| { + if opening(chars[i]) { letter_after[i] == 1 } else { letter_before[i] == 1 } + }; + let in_run = |i: usize| { + let c = chars[i]; + if ltr(c) { + return true; + } + if rtl_script(c) { + return false; + } + if c == '°' { + // A European terminator: of the run when a digit is next to it, of + // the line's flow otherwise. + return (0 < i && digit(chars[i - 1])) || (i + 1 < chars.len() && digit(chars[i + 1])); + } + if opening(c) || closing(c) { + match partner[i] { + Some(j) => { + let (o, e) = (i.min(j), i.max(j)); + alone(o) && alone(e) && rtl_count[o] == rtl_count[e] } + None => alone(i), } + } else { + before[i] == 1 && after[i] == 1 } - pairs + }; + let mut out = String::with_capacity(line.len()); + let mut run: Vec = Vec::new(); + // A run of one character reads the same either way: it takes no marks. + let flush = |out: &mut String, run: &mut Vec| { + let marked = run.len() > 1; + out.extend(marked.then_some(RUN_START)); + out.extend(run.drain(..).rev().map(mirror)); + out.extend(marked.then_some(RUN_END)); + }; + for (i, c) in chars.iter().enumerate() { + if in_run(i) { + run.push(*c); + } else { + flush(&mut out, &mut run); + out.push(mirror(*c)); + } + } + flush(&mut out, &mut run); + if out == line { + return out; } + format!("{LINE_START}{out}{LINE_END}") } diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs index 3d8ae6b18d..25a11b64b6 100644 --- a/crates/ui-egui/src/i18n/boundary_tests.rs +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -1,7 +1,7 @@ //! Right-to-left display text paints rewritten, and leaves the screen in logical order. use egui::OutputCommand; -use rustgis_engine::data::display_marks::{MARKS, RUN_END, logical}; +use rustgis_engine::data::display_marks::{MARKS, RUN_END, logical, unmarked}; use serde_json::json; use super::*; @@ -231,3 +231,92 @@ fn a_dialog_error_is_painted_in_display_form() { assert_eq!(service.as_deref(), Some(shown.as_str())); assert_eq!(plugin, shown); } + +/// Pairs of marks that data holds, none of them around what the display code makes. +const FAKES: [&str; 3] = [ + // A line pair around text that starts left-to-right. + "\u{2063}abc (d)\u{2062}", + // A run with no line around it. + "x \u{2064}ab\u{2061} y", + // A line pair around a run of one character, which is never marked. + "\u{2063}سلام \u{2064}a\u{2061}\u{2062}", +]; + +#[test] +fn a_pair_of_marks_in_data_is_left_as_it_is() { + for data in FAKES { + assert_eq!(logical(data), None, "{data:?}"); + assert_eq!(unmarked(data), None, "{data:?}"); + } +} + +#[test] +fn only_a_real_display_form_is_put_back_beside_pairs_in_data() { + set_current(fa()); + let (shown, text) = message(); + set_current(Lang::EN); + for fake in FAKES { + assert_eq!(logical(&format!("{fake} {shown}")), Some(format!("{fake} {text}"))); + assert_eq!(logical(&format!("{shown}\n{fake}\nplain")), Some(format!("{text}\n{fake}\nplain"))); + let painted = shown.replace(MARKS, ""); + assert_eq!(unmarked(&format!("{shown} {fake}")), Some(format!("{painted} {fake}"))); + } +} + +/// A line that already holds a mark isn't rewritten, so it leaves the screen as it was made. +#[test] +fn a_message_around_data_with_marks_keeps_them() { + set_current(fa()); + let args = &[("names", "a\u{2064}bc\u{2061}")]; + let (shown, text) = (fmt(TEMPLATE, args), fmt_raw(TEMPLATE, args)); + set_current(Lang::EN); + assert_eq!(shown, text); + assert_eq!(outgoing(&shown), text); +} + +#[test] +fn a_command_and_a_notice_keep_a_pair_that_data_holds() { + let mut app = persian(); + for (i, fake) in FAKES.into_iter().enumerate() { + let name = format!("{i} {fake}"); + app.run("gp.bufferPoint", json!({"lon": 8.5, "lat": 47.4, "distance": 500.0, "units": "Meters", "name": name})).unwrap(); + assert!(app.session.map().layers.iter().any(|l| l.name == name), "no layer named {name:?}"); + app.session.notify(fake, false); + assert_eq!(app.session.notices.last().unwrap().text, fake); + app.session.notify_redacted(rustgis_engine::Session::redacted(fake), true); + assert_eq!(app.session.notices.last().unwrap().text, fake); + } + set_current(Lang::EN); +} + +/// The limit: data that is exactly a display form this code makes can't be told from one. +#[test] +fn data_identical_to_a_display_form_is_read_as_one() { + let text = "سلام abc"; + assert_eq!(logical(&rtl::visual(text)).as_deref(), Some(text)); +} + +/// A message put around a display form (a `tl!` or `fmt` result as an argument) is shaped as +/// one made of the logical parts; beside data with marks, the line stays as it was made. +#[test] +fn a_message_around_a_display_form_is_shaped_as_one() { + set_current(fa()); + let (shown, text) = message(); + let around = |names: &str| fmt(TEMPLATE, &[("names", names)]); + let (nested, whole) = (around(&shown), around(&text)); + let logical_whole = fmt_raw(TEMPLATE, &[("names", &text)]); + let data = format!("{shown} {}", FAKES[0]); + let (kept, raw) = (around(&data), fmt_raw(TEMPLATE, &[("names", &data)])); + set_current(Lang::EN); + assert_eq!(nested, whole); + assert_eq!(logical(&nested), Some(logical_whole)); + assert_eq!(kept, raw); +} + +/// A long line of brackets, as data may hold, comes back whole. A smoke test for a quadratic +/// walk, which would take minutes here: it has no time bound. +#[test] +fn a_long_line_of_brackets_is_read_in_one_walk() { + let text = format!("سلام {}{}{}", "(".repeat(100_000), "]".repeat(100_000), "a)".repeat(100_000)); + assert_eq!(logical(&rtl::visual(&text)), Some(text)); +} diff --git a/crates/ui-egui/src/i18n/rtl.rs b/crates/ui-egui/src/i18n/rtl.rs index ee92b0e748..c808e132c7 100644 --- a/crates/ui-egui/src/i18n/rtl.rs +++ b/crates/ui-egui/src/i18n/rtl.rs @@ -10,14 +10,13 @@ //! and the right-to-left text in it reads backwards, so the catalogs of such //! languages start their lines with right-to-left text (see `fa.tsv`). //! -//! [`visual`] rewrites a back-to-front line into the form that reads correctly -//! once laid out: each left-to-right run is reversed ahead of time, and every -//! bracket is mirrored, for the shaper mirrors every bracket of a back-to-front -//! line, those inside a left-to-right run too. Joining, which the shaper does on -//! the text as given, is untouched: right-to-left text keeps its written -//! order. Each line is rewritten on its own strength, and a line that starts -//! left-to-right, or a string with no right-to-left text at all, comes back -//! unchanged. +//! [`visual`] (in `rustgis-data`, beside the marks it writes) rewrites a back-to-front +//! line into the form that reads correctly once laid out: each left-to-right run is reversed +//! ahead of time, and every bracket is mirrored, for the shaper mirrors every bracket of a +//! back-to-front line, those inside a left-to-right run too. Joining, which the shaper does on +//! the text as given, is untouched: right-to-left text keeps its written order. Each line is +//! rewritten on its own strength, and a line that starts left-to-right, or a string with no +//! right-to-left text at all, comes back unchanged. //! //! [`fit`] breaks a long line into lines whose display form fits a width, so //! the toolkit's own wrapping never has to: it fills rows from the start of a @@ -34,210 +33,8 @@ //! What is rewritten is marked ([`rustgis_engine::data::display_marks`]), so text that leaves //! the screen can be put back in logical order. -use rustgis_engine::data::display_marks::{LINE_END, LINE_START, RUN_END, RUN_START, mirror}; - -/// A character of a script written right to left (Arabic, Persian, Hebrew). Digits -/// read left to right, and the comma, semicolon and question mark take the line's -/// direction, so none of them are script letters here. -fn rtl_script(c: char) -> bool { - if matches!(c as u32, 0x0660..=0x066C | 0x06F0..=0x06F9 | 0x060C | 0x061B | 0x061F) { - return false; - } - matches!(c as u32, - 0x0590..=0x05FF // Hebrew - | 0x0600..=0x06FF // Arabic - | 0x0750..=0x077F - | 0x08A0..=0x08FF - | 0xFB1D..=0xFDFF // presentation forms - | 0xFE70..=0xFEFF) -} - -/// A character of a left-to-right run: a letter or number of any script but a -/// right-to-left one (Latin, Cyrillic, Greek, CJK, accented letters, superscripts), -/// or a Persian or Arabic digit. -fn ltr(c: char) -> bool { - c.is_alphanumeric() && !rtl_script(c) -} - -/// A digit of either script: what the degree sign attaches to. -fn digit(c: char) -> bool { - c.is_ascii_digit() || matches!(c as u32, 0x0660..=0x0669 | 0x06F0..=0x06F9) -} - -/// A left-to-right letter: what brackets pair onto (they close around letters, not -/// numbers). -fn letter(c: char) -> bool { - c.is_alphabetic() && !rtl_script(c) -} - -/// What the toolkit's direction guess makes of a character: `Some(true)` — of a -/// right-to-left script, the line start that is laid out back to front (the digits -/// of the Arabic block included, for their script is Arabic); `Some(false)` — of a -/// left-to-right script (Latin, Cyrillic, Greek, CJK…); `None` — of no script of -/// its own (digits, punctuation, marks, controls), which the guess skips. -fn strong(c: char) -> Option { - if rtl_script(c) || matches!(c as u32, 0x0660..=0x0669 | 0x06F0..=0x06F9) { - Some(true) - } else if c.is_alphabetic() { - Some(false) - } else { - None - } -} - -fn opening(c: char) -> bool { - matches!(c, '(' | '[' | '{' | '«' | '‹') -} - -fn closing(c: char) -> bool { - matches!(c, ')' | ']' | '}' | '»' | '›') -} - -/// Whether any right-to-left text is in `s`: a cheap check before any work. -#[must_use] -pub fn has_rtl(s: &str) -> bool { - s.chars().any(rtl_script) -} - -/// Whether `s` starts, past characters of no script of their own, with one of a -/// right-to-left script: the lines the toolkit lays out back to front. A string -/// of no strong character at all is laid out front to back. -fn back_to_front(s: &str) -> bool { - s.chars().find_map(strong) == Some(true) -} - -/// `s` in the form that reads correctly when laid out back to front: each -/// left-to-right run reversed (the line's own reversal puts it back), and every bracket -/// mirrored (the shaper mirrors them all back). Everything else is untouched, so the shaper still -/// joins the right-to-left text as written. Every line is rewritten on its own -/// strength; a line that starts left-to-right, and a string with no right-to-left -/// text, come back unchanged. -#[must_use] -pub fn visual(s: &str) -> String { - if !has_rtl(s) { - return s.to_owned(); - } - s.split('\n').map(visual_line).collect::>().join("\n") -} - -/// One line of [`visual`]: rewritten only when it starts back to front. -fn visual_line(line: &str) -> String { - if !back_to_front(line) { - return line.to_owned(); - } - let chars: Vec = line.chars().collect(); - // The nearest run character before and after each position (1 left-to-right, - // 2 right-to-left): a neutral between two runs takes the side of both. - let mut before = vec![0u8; chars.len()]; - let mut seen = 0u8; - for (i, c) in chars.iter().enumerate() { - before[i] = seen; - if ltr(*c) { - seen = 1; - } else if rtl_script(*c) { - seen = 2; - } - } - let mut after = vec![0u8; chars.len()]; - let mut next = 0u8; - for i in (0..chars.len()).rev() { - after[i] = next; - if ltr(chars[i]) { - next = 1; - } else if rtl_script(chars[i]) { - next = 2; - } - } - // The nearest Latin letter before and after: a bracket joins a run when it opens - // or closes onto a letter, not onto a number (Unicode 'paired brackets'). - let mut letter_before = vec![0u8; chars.len()]; - let mut word_seen = 0u8; - for (i, c) in chars.iter().enumerate() { - letter_before[i] = word_seen; - if letter(*c) { - word_seen = 1; - } else if rtl_script(*c) { - word_seen = 2; - } - } - let mut letter_after = vec![0u8; chars.len()]; - let mut word_next = 0u8; - for i in (0..chars.len()).rev() { - letter_after[i] = word_next; - if letter(chars[i]) { - word_next = 1; - } else if rtl_script(chars[i]) { - word_next = 2; - } - } - // Paired brackets are resolved as one (Unicode BD16, N0): a pair joins the run - // only when both of its brackets would, and nothing right-to-left is inside, so - // its two brackets never land in different runs. - let mut partner: Vec> = vec![None; chars.len()]; - let mut open: Vec = Vec::new(); - for (i, c) in chars.iter().enumerate() { - if opening(*c) { - open.push(i); - } else if closing(*c) - && let Some(at) = open.iter().rposition(|o| chars.get(*o).copied().map(mirror) == Some(*c)) - { - let o = open[at]; - open.truncate(at); - partner[o] = Some(i); - partner[i] = Some(o); - } - } - let alone = |i: usize| { - if opening(chars[i]) { letter_after[i] == 1 } else { letter_before[i] == 1 } - }; - let in_run = |i: usize| { - let c = chars[i]; - if ltr(c) { - return true; - } - if rtl_script(c) { - return false; - } - if c == '°' { - // A European terminator: of the run when a digit is next to it, of - // the line's flow otherwise. - return (0 < i && digit(chars[i - 1])) || (i + 1 < chars.len() && digit(chars[i + 1])); - } - if opening(c) || closing(c) { - match partner[i] { - Some(j) => { - let (o, e) = (i.min(j), i.max(j)); - alone(o) && alone(e) && !chars[o..e].iter().copied().any(rtl_script) - } - None => alone(i), - } - } else { - before[i] == 1 && after[i] == 1 - } - }; - let mut out = String::with_capacity(line.len()); - let mut run: Vec = Vec::new(); - // A run of one character reads the same either way: it takes no marks. - let flush = |out: &mut String, run: &mut Vec| { - let marked = run.len() > 1; - out.extend(marked.then_some(RUN_START)); - out.extend(run.drain(..).rev().map(mirror)); - out.extend(marked.then_some(RUN_END)); - }; - for (i, c) in chars.iter().enumerate() { - if in_run(i) { - run.push(*c); - } else { - flush(&mut out, &mut run); - out.push(mirror(*c)); - } - } - flush(&mut out, &mut run); - if out == line { - return out; - } - format!("{LINE_START}{out}{LINE_END}") -} +use rustgis_engine::data::display_marks::{back_to_front, strong, visual_line}; +pub use rustgis_engine::data::display_marks::{has_rtl, visual}; /// `s` broken into lines whose display form is no wider than `max_width`, so the /// toolkit's own wrapping never has to: it fills rows from the start of a @@ -246,8 +43,8 @@ fn visual_line(line: &str) -> String { /// is laid out front to back, and the right-to-left words in it would read /// backwards, so it ends before the first word with right-to-left text; a row with /// no right-to-left text at all reads correctly front to back on its own. `width` -/// measures a line's display form, marks included (they have no width). Strings with no right-to-left text come back -/// unchanged. +/// measures a line's display form, marks included (they have no width). Strings with no +/// right-to-left text come back unchanged. #[must_use] pub fn fit(s: &str, max_width: f32, width: &dyn Fn(&str) -> f32) -> String { if !has_rtl(s) || !max_width.is_finite() || max_width <= 0.0 { @@ -384,6 +181,14 @@ mod tests { assert_eq!(fit("hello world", 2.0, &chars), "hello world"); } + #[test] + fn a_row_of_digits_alone_is_put_in_display_form() { + let chars = |s: &str| s.chars().count() as f32; + // Persian and Arabic digits are laid out back to front, with no letter beside them. + assert_eq!(fit("سلام ۱۲۳", 4.0, &chars), "سلام\n۳۲۱"); + assert_eq!(fit("سلام ١٢٣", 4.0, &chars), "سلام\n٣٢١"); + } + #[test] fn a_row_that_starts_with_a_latin_word_holds_no_rtl_words() { let chars = |s: &str| s.chars().count() as f32; diff --git a/crates/ui-egui/src/pluginstart.rs b/crates/ui-egui/src/pluginstart.rs index efc0a43ceb..a5cfe5b0e7 100644 --- a/crates/ui-egui/src/pluginstart.rs +++ b/crates/ui-egui/src/pluginstart.rs @@ -277,12 +277,16 @@ mod tests { /// A queued plugin command's parameters lose the display marks, as any command's do. #[test] fn a_queued_command_keeps_no_display_mark() { - use rustgis_engine::data::display_marks::{LINE_END, LINE_START}; let mut h = launch("ui-pinned-marks"); - let shown = format!("{LINE_START}Streams{LINE_END}"); + // No Persian font is needed to read the layer's name. + h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu); + let shown = crate::i18n::display("رود Streams"); h.state_mut().run_by_user("plugin:ui-pinned-marks/f", rename("Rivers", &shown)).unwrap(); h.run(); - assert!(h.state().session.map().layer_by_name("Streams").is_some()); + // Kept as painted, without the marks: storing names in logical order is #3329. + let kept = shown.replace(rustgis_engine::data::display_marks::MARKS, ""); + assert_ne!(kept, shown); + assert!(h.state().session.map().layer_by_name(&kept).is_some()); plugins::unload("ui-pinned-marks"); } diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index c52348ddb4..bd4ccfe392 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -1032,8 +1032,8 @@ mod tests { assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); } - /// In a right-to-left language the words of a tool call are put in display form once, with the - /// line they go into: twice would turn the Latin in them back round. + /// In a right-to-left language the words of a tool call stay logical, to be put in display + /// form with the line they go into; words already in display form come out the same there. #[test] fn the_words_of_a_tool_call_are_put_in_display_form_once() { let mut held = Held::new(); @@ -1047,7 +1047,8 @@ mod tests { i18n::set_current(before); assert_eq!(words, logical); assert!(!words.is_ascii() && words.contains("PostGIS"), "{words}"); - assert_ne!(once, twice, "the test can tell"); + assert_ne!(i18n::display(&words), words, "the words are rewritten for display"); + assert_eq!(once, twice); } /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers.