Skip to main content

mln_engine/text/
bidi.rs

1//! Lines and runs of text in visual order.
2//!
3//! The `unicode-bidi` crate resolves levels and visual runs (UAX #9), and
4//! this module writes them: runs in visual order, RTL runs reversed by
5//! character with each character replaced by its `Bidi_Mirroring_Glyph`
6//! (rule L4, which unicode-bidi leaves to the renderer; `crate::text::bidi_mirroring`,
7//! from the same Unicode version as unicode-bidi's tables), and BiDi controls
8//! removed.
9//!
10//! The line splitters take line break points as offsets into the text, in
11//! characters. Each must end a nonempty line within the text (`0 < point <=
12//! len`); the end of each paragraph is a line break point whether or not the
13//! caller passes it.
14
15use std::ops::Range;
16
17use mln_style::collections::VecSet;
18use unicode_bidi::{BidiClass, BidiInfo};
19
20use crate::text::bidi_mirroring::BIDI_MIRRORING_GLYPH;
21use crate::text::tagged_string::{SectionIndex, StyledText};
22
23/// Whether the first character in `text` with a strong direction runs right
24/// to left.
25#[must_use]
26pub fn starts_right_to_left(text: &[char]) -> bool {
27    for &ch in text {
28        match unicode_bidi::bidi_class(ch) {
29            BidiClass::L => return false,
30            BidiClass::R | BidiClass::AL => return true,
31            _ => {}
32        }
33    }
34    false
35}
36
37/// The character's `Bidi_Mirroring_Glyph`, or the character itself if it has
38/// none.
39fn mirror(c: char) -> char {
40    u16::try_from(u32::from(c))
41        .ok()
42        .and_then(|c| BIDI_MIRRORING_GLYPH.binary_search_by_key(&c, |&(from, _)| from).ok())
43        .and_then(|i| char::from_u32(u32::from(BIDI_MIRRORING_GLYPH[i].1)))
44        .unwrap_or(c)
45}
46
47/// Whether `c` is a BiDi control that visual-order text leaves out.
48fn is_bidi_control(c: char) -> bool {
49    matches!(
50        c,
51        // ZWNJ, ZWJ, LRM and RLM
52        '\u{200C}'..='\u{200F}'
53        // LRE, RLE, PDF, LRO and RLO
54        | '\u{202A}'..='\u{202E}'
55        // LRI, RLI, FSI and PDI
56        | '\u{2066}'..='\u{2069}'
57    )
58}
59
60/// Appends the run `src` to `out` in visual order without BiDi controls: an
61/// RTL run reversed, each character mirrored, and an LTR run as it is.
62fn write_run(src: &[char], rtl: bool, out: &mut Vec<char>) {
63    let kept = |&&c: &&char| !is_bidi_control(c);
64    if rtl {
65        out.extend(src.iter().rev().filter(kept).map(|&c| mirror(c)));
66    } else {
67        out.extend(src.iter().filter(kept));
68    }
69}
70
71/// Whether the bidi analysis leaves all of `text` at level 0, left to right
72/// in logical order: no character in it runs right to left, is an Arabic
73/// number, or opens an embedding, override or isolate.
74fn is_pure_ltr(text: &[char]) -> bool {
75    use BidiClass::{AL, AN, FSI, LRE, LRI, LRO, R, RLE, RLI, RLO};
76    !text.iter().any(|&c| matches!(unicode_bidi::bidi_class(c), R | AL | AN | LRE | RLE | LRO | RLO | LRI | RLI | FSI))
77}
78
79/// The ends of the paragraphs of `text`: after each paragraph separator,
80/// and at the end of the text, which may also end the last separator's
81/// paragraph.
82fn paragraph_ends(text: &[char]) -> impl Iterator<Item = usize> {
83    let separators = text.iter().enumerate().filter(|&(_, &c)| unicode_bidi::bidi_class(c) == BidiClass::B);
84    separators.map(|(i, _)| i + 1).chain([text.len()])
85}
86
87/// The lines of text `len` characters long that end at `line_breaks` and at
88/// `paragraph_ends`, so that no line crosses a paragraph boundary.
89fn lines(
90    len: usize,
91    mut line_breaks: VecSet<usize>,
92    paragraph_ends: impl IntoIterator<Item = usize>,
93) -> impl Iterator<Item = Range<usize>> {
94    debug_assert!(
95        line_breaks.iter().all(|&point| 0 < point && point <= len),
96        "line breaks {line_breaks:?} outside 1..={len}"
97    );
98    for end in paragraph_ends {
99        line_breaks.insert(end);
100    }
101    let mut start = 0;
102    // A release build drops points outside the text rather than panic.
103    line_breaks.into_iter().filter(move |&end| 0 < end && end <= len).map(move |end| {
104        let line = start..end;
105        start = end;
106        line
107    })
108}
109
110/// A run of text in one direction, in logical order.
111#[derive(Clone, Debug, PartialEq)]
112pub struct BiDiRun {
113    pub(crate) text: Vec<char>,
114    pub(crate) rtl: bool,
115}
116
117/// The bidi analysis of text given as characters. unicode-bidi reads text
118/// as UTF-8 or UTF-16 and indexes it by code unit, so the text goes through
119/// UTF-8, and this maps between its byte offsets and the characters'
120/// indices.
121struct Analysis<'text> {
122    info: BidiInfo<'text>,
123    /// The byte offset of each character and of the end of the text; empty
124    /// when the text is ASCII, where the two are the same.
125    offsets: Vec<usize>,
126}
127
128impl<'text> Analysis<'text> {
129    fn new(text: &[char], utf8: &'text mut String) -> Self {
130        utf8.reserve(text.iter().map(|c| c.len_utf8()).sum());
131        utf8.extend(text);
132        let offsets = if utf8.len() == text.len() {
133            Vec::new()
134        } else {
135            let mut offsets = Vec::with_capacity(text.len() + 1);
136            offsets.push(0);
137            offsets.extend(text.iter().scan(0, |offset, c| {
138                *offset += c.len_utf8();
139                Some(*offset)
140            }));
141            offsets
142        };
143        Analysis { info: BidiInfo::new(utf8, None), offsets }
144    }
145
146    /// The byte offset of the character at `index`, or of the text's end.
147    fn byte(&self, index: usize) -> usize {
148        if self.offsets.is_empty() { index } else { self.offsets[index] }
149    }
150
151    /// The index of the character that starts at byte `offset`, or of the
152    /// text's end.
153    fn char(&self, offset: usize) -> usize {
154        if self.offsets.is_empty() { offset } else { self.offsets.partition_point(|&o| o < offset) }
155    }
156
157    fn chars(&self, bytes: Range<usize>) -> Range<usize> {
158        self.char(bytes.start)..self.char(bytes.end)
159    }
160
161    /// The text's paragraphs, as ranges of characters.
162    fn paragraphs(&self) -> impl Iterator<Item = Range<usize>> {
163        self.info.paragraphs.iter().map(|paragraph| self.chars(paragraph.range.clone()))
164    }
165
166    /// The lines of the text that end at `line_breaks` and at the ends of its
167    /// paragraphs.
168    fn lines(&self, line_breaks: VecSet<usize>) -> impl Iterator<Item = Range<usize>> {
169        lines(self.char(self.info.text.len()), line_breaks, self.paragraphs().map(|paragraph| paragraph.end))
170    }
171
172    /// The visual runs of `line`, a nonempty line of the text within one
173    /// paragraph: whether each runs right to left, and its logical range, in
174    /// visual order.
175    fn line_runs(&self, line: Range<usize>) -> Vec<(bool, Range<usize>)> {
176        let line = self.byte(line.start)..self.byte(line.end);
177        let paragraphs = &self.info.paragraphs;
178        let paragraph = &paragraphs[paragraphs.partition_point(|p| p.range.end <= line.start)];
179        let (levels, runs) = self.info.visual_runs(paragraph, line);
180        runs.into_iter().map(|run| (levels[run.start].is_rtl(), self.chars(run))).collect()
181    }
182}
183
184/// Splits `text`, in logical order, into lines at `line_breaks`, and writes
185/// each line in visual order.
186pub(crate) fn reorder_lines(text: &[char], line_breaks: VecSet<usize>) -> Vec<Vec<char>> {
187    if is_pure_ltr(text) {
188        return lines(text.len(), line_breaks, paragraph_ends(text))
189            .map(|line| {
190                let mut out = Vec::with_capacity(line.len());
191                write_run(&text[line], false, &mut out);
192                out
193            })
194            .collect();
195    }
196    let mut utf8 = String::new();
197    let analysis = Analysis::new(text, &mut utf8);
198    analysis
199        .lines(line_breaks)
200        .map(|line| {
201            let mut out = Vec::with_capacity(line.len());
202            for (rtl, run) in analysis.line_runs(line) {
203                write_run(&text[run], rtl, &mut out);
204            }
205            out
206        })
207        .collect()
208}
209
210/// Like [`reorder_lines`], with each character's style, except that LTR runs
211/// keep their BiDi controls, and an RTL run's first character takes the
212/// style of the chunk after it unless either style is a block.
213pub(crate) fn reorder_styled_lines(input: &StyledText, line_breaks: VecSet<usize>) -> Vec<StyledText> {
214    reorder_styled_lines_with_blocks(input, line_breaks, &input.text, &[])
215}
216
217/// Like [`reorder_styled_lines`], but the bidi analysis reads `bidi_text`,
218/// which is as long as the input's text, and a right-to-left run keeps the
219/// order of the text in the styles that `block_styles` marks, which a shaper
220/// already laid out in visual order.
221pub(crate) fn reorder_styled_lines_with_blocks(
222    input: &StyledText,
223    line_breaks: VecSet<usize>,
224    bidi_text: &[char],
225    block_styles: &[bool],
226) -> Vec<StyledText> {
227    debug_assert_eq!(bidi_text.len(), input.text.len());
228    let input_text = &input.text;
229    let style_indices = &input.styles;
230    let is_block = |style: SectionIndex| block_styles.get(style as usize).copied().unwrap_or(false);
231
232    if is_pure_ltr(bidi_text) {
233        return lines(bidi_text.len(), line_breaks, paragraph_ends(bidi_text))
234            .map(|line| StyledText { text: input_text[line.clone()].to_vec(), styles: style_indices[line].to_vec() })
235            .collect();
236    }
237    let mut utf8 = String::new();
238    let analysis = Analysis::new(bidi_text, &mut utf8);
239    let mut out = Vec::new();
240    for line_range in analysis.lines(line_breaks) {
241        let mut line = StyledText { text: Vec::new(), styles: Vec::with_capacity(line_range.len()) };
242
243        for (is_reversed, run) in analysis.line_runs(line_range) {
244            let logical_start = run.start;
245            let logical_end = run.end;
246            if is_reversed {
247                // Within this reversed section, iterate logically
248                // backwards. Each time we see a change in style, render
249                // a reversed chunk of everything since the last change.
250                //
251                let mut style_run_start = logical_end;
252                let mut current_style_index = style_indices[style_run_start - 1];
253                let mut add_chunk = |start: usize, end: usize, style: SectionIndex| {
254                    // A block's text is already in visual order.
255                    let mut reversed = Vec::new();
256                    if is_block(style) {
257                        reversed.extend_from_slice(&input_text[start..end]);
258                    } else {
259                        write_run(&input_text[start..end], true, &mut reversed);
260                    }
261                    line.text.extend_from_slice(&reversed);
262                    line.styles.extend(std::iter::repeat_n(style, reversed.len()));
263                };
264                let mut i = logical_end - 1;
265                while i >= logical_start {
266                    if current_style_index != style_indices[i] || i == logical_start {
267                        // The run's first character joins the chunk
268                        // after it even when its style differs, except
269                        // next to a block, which
270                        // holds only its own text.
271                        let split_first = i == logical_start
272                            && current_style_index != style_indices[i]
273                            && (is_block(current_style_index) || is_block(style_indices[i]));
274                        let style_run_end = if i == logical_start && !split_first { i } else { i + 1 };
275                        add_chunk(style_run_end, style_run_start, current_style_index);
276                        current_style_index = style_indices[i];
277                        style_run_start = style_run_end;
278                        if split_first {
279                            add_chunk(i, i + 1, current_style_index);
280                            style_run_start = i;
281                        }
282                    }
283                    if i == 0 {
284                        break;
285                    }
286                    i -= 1;
287                }
288            } else {
289                line.text.extend_from_slice(&input_text[logical_start..logical_end]);
290                line.styles.extend_from_slice(&style_indices[logical_start..logical_end]);
291            }
292        }
293
294        out.push(line);
295    }
296    out
297}
298
299/// Splits text in logical order into runs of one direction each, and
300/// returns the runs in visual order: each paragraph's runs in visual order,
301/// the paragraphs in logical order. Each run keeps its logical order, so a
302/// shaper such as HarfBuzz can lay it out in its direction. Text with no runs
303/// is one LTR run.
304#[must_use]
305pub fn visual_runs(text: &[char]) -> Vec<BiDiRun> {
306    let mut runs = Vec::new();
307    if text.is_empty() {
308        return runs;
309    }
310    if is_pure_ltr(text) {
311        let mut start = 0;
312        for end in paragraph_ends(text) {
313            if start < end {
314                runs.push(BiDiRun { text: text[start..end].to_vec(), rtl: false });
315            }
316            start = end;
317        }
318        return runs;
319    }
320
321    let mut utf8 = String::new();
322    let analysis = Analysis::new(text, &mut utf8);
323    for paragraph in analysis.paragraphs() {
324        for (rtl, run) in analysis.line_runs(paragraph) {
325            if run.is_empty() {
326                continue;
327            }
328            runs.push(BiDiRun { text: text[run].to_vec(), rtl });
329        }
330    }
331
332    if runs.is_empty() {
333        runs.push(BiDiRun { text: text.to_vec(), rtl: false });
334    }
335    runs
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use crate::text::arabic::shape_arabic;
342
343    fn u(s: &str) -> Vec<char> {
344        s.chars().collect()
345    }
346
347    fn set(v: &[usize]) -> VecSet<usize> {
348        v.iter().copied().collect()
349    }
350
351    fn styled(text: Vec<char>, styles: Vec<SectionIndex>) -> StyledText {
352        StyledText { text, styles }
353    }
354
355    const LIBRARY: &str = "مكتبة الإسكندرية\u{200E}\u{200E} Maktabat al-Iskandarīyah";
356
357    #[test]
358    fn lines_come_out_in_visual_order() {
359        // (text, line breaks, lines)
360        let cases: [(&str, &[usize], &[&str]); 5] = [
361            ("سلام۳۹", &[], &["۳۹ﻡﻼﺳ"]),
362            (LIBRARY, &[], &[" Maktabat al-Iskandarīyahﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ"]),
363            (LIBRARY, &[18, 30], &[" ﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ", "Maktabat al-", "Iskandarīyah"]),
364            // Line breaks count characters, whatever their length in UTF-8.
365            ("é😀ab\nש😀", &[2], &["é😀", "ab\n", "😀ש"]),
366            // Left-to-right text stays in logical order, without its controls,
367            // and CR and LF each end a paragraph.
368            ("a\u{200D}b\u{200E}\u{202C}\u{2069}c\r\nd", &[2], &["a", "bc\r", "\n", "d"]),
369        ];
370        for (text, breaks, lines) in cases {
371            let lines: Vec<Vec<char>> = lines.iter().map(|line| u(line)).collect();
372            assert_eq!(reorder_lines(&shape_arabic(&u(text)), set(breaks)), lines, "{text:?} at {breaks:?}");
373        }
374    }
375
376    #[test]
377    fn styled_lines_keep_each_character_s_style() {
378        // The line breaks split and interleave sections that are contiguous
379        // in the input.
380        let input = styled(
381            shape_arabic(&u(LIBRARY)).into_owned(),
382            vec![
383                0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6,
384                6, 6, 6, 6, 6, 7, 7, 7,
385            ],
386        );
387        let expected: Vec<StyledText> = vec![
388            styled(u("ﺔﺒﺘﻜﻣ"), vec![0, 0, 0, 0, 0]),
389            styled(u(" \u{200E}\u{200E}ﺔﻳﺭﺪﻨﻜﺳﻹﺍ "), vec![2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1]),
390            styled(u("Maktabat al-"), vec![2, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6]),
391            styled(u("Iskandarīyah"), vec![6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7]),
392        ];
393        assert_eq!(reorder_styled_lines(&input, set(&[5, 18, 30])), expected);
394
395        // Left-to-right lines keep their controls.
396        let input = styled(u("a\u{200D}b\u{202C}c\nd"), vec![0, 0, 1, 1, 1, 1, 2]);
397        let expected =
398            [styled(u("a\u{200D}"), vec![0, 0]), styled(u("b\u{202C}c\n"), vec![1, 1, 1, 1]), styled(u("d"), vec![2])];
399        assert_eq!(reorder_styled_lines(&input, set(&[2])), expected);
400    }
401
402    #[test]
403    fn visual_runs_come_left_to_right_each_in_logical_order() {
404        // (text, runs as (text, right to left))
405        let cases = [
406            ("Erbil هەولێر", vec![("Erbil ", false), ("هەولێر", true)]),
407            ("هەولێر Erbil", vec![("Erbil", false), ("هەولێر ", true)]),
408            ("a😀 שלום x", vec![("a😀 ", false), ("שלום", true), (" x", false)]),
409            ("a\u{200E}\u{2069}b\r\nc", vec![("a\u{200E}\u{2069}b\r", false), ("\n", false), ("c", false)]),
410        ];
411        for (text, expected) in cases {
412            let runs: Vec<(Vec<char>, bool)> =
413                visual_runs(&u(text)).into_iter().map(|run| (run.text, run.rtl)).collect();
414            let expected: Vec<(Vec<char>, bool)> = expected.into_iter().map(|(text, rtl)| (u(text), rtl)).collect();
415            assert_eq!(runs, expected, "{text:?}");
416        }
417    }
418
419    #[test]
420    fn blocks_keep_their_order_in_right_to_left_runs() {
421        // "XY" stands for glyphs that a shaper already laid out right to
422        // left. Bidi sees them as Hebrew letters, and moves them without
423        // reversing them.
424        let input = styled(u("XY Erbil"), vec![0, 0, 1, 1, 1, 1, 1, 1]);
425        let lines = reorder_styled_lines_with_blocks(&input, set(&[]), &u("אא Erbil"), &[true, false]);
426        assert_eq!(lines, [styled(u("Erbil XY"), vec![1, 1, 1, 1, 1, 1, 0, 0])]);
427    }
428
429    #[test]
430    fn block_at_the_start_of_a_run_takes_only_its_own_text() {
431        // The run "-XY" reads right to left, and its first character, "-",
432        // is not part of the block.
433        let input = styled(u("-XY"), vec![0, 1, 1]);
434        let lines = reorder_styled_lines_with_blocks(&input, set(&[]), &u("-אא"), &[false, true]);
435        assert_eq!(lines, [styled(u("XY-"), vec![1, 1, 0])]);
436    }
437
438    #[test]
439    fn starts_right_to_left_at_the_first_strong_character() {
440        assert!(!starts_right_to_left(&u("1 abc שלום")));
441        assert!(starts_right_to_left(&u("1 שלום abc")));
442        assert!(starts_right_to_left(&u("(سلام)")));
443        // A supplementary letter (Adlam).
444        assert!(starts_right_to_left(&u("\u{1E900}")));
445        assert!(!starts_right_to_left(&u("123 !?")));
446    }
447
448    #[test]
449    fn runs_are_written_without_controls_and_rtl_runs_reversed_and_mirrored() {
450        // (run, right to left, written)
451        let cases = [
452            ("א<ב(ג", true, "ג)ב>א"),
453            ("א\u{1E900}ב", true, "ב\u{1E900}א"),
454            ("«≤a»", true, "«a≥»"),
455            ("a\u{200D}b\u{202A}c\u{2069}(\u{200F}", false, "abc("),
456        ];
457        for (run, rtl, expected) in cases {
458            let mut out = Vec::new();
459            write_run(&u(run), rtl, &mut out);
460            assert_eq!(out, u(expected), "{run:?}");
461        }
462    }
463
464    #[test]
465    fn mirroring_table_is_sorted_and_symmetric() {
466        assert!(BIDI_MIRRORING_GLYPH.windows(2).all(|w| w[0].0 < w[1].0));
467        for &(from, to) in &BIDI_MIRRORING_GLYPH {
468            let (from, to) = (char::from_u32(from.into()).unwrap(), char::from_u32(to.into()).unwrap());
469            assert_eq!(mirror(to), from, "U+{:04X}", u32::from(from));
470        }
471    }
472}