Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
334 changes: 291 additions & 43 deletions crates/data/src/display_marks.rs
Original file line number Diff line number Diff line change
@@ -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}';
Expand Down Expand Up @@ -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<String> {
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<String> {
unmark(shown, false)
Expand All @@ -60,56 +63,301 @@ fn unmark(shown: &str, reorder: bool) -> Option<String> {
(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<char> = 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<char> = 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<bool>,
/// Whether it is one of those two marks.
mark: Vec<bool>,
}

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<bool> {
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)
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}

/// 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::<Vec<_>>().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<char> = 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<Option<usize>> = 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<char, usize> = 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<usize> = 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<char> = Vec::new();
// A run of one character reads the same either way: it takes no marks.
let flush = |out: &mut String, run: &mut Vec<char>| {
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}")
}
Loading
Loading