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_vec_map::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/// A run of text in one direction, in logical order.
72#[derive(Clone, Debug, PartialEq)]
73pub struct BiDiRun {
74    pub text: Vec<char>,
75    pub rtl: bool,
76}
77
78/// The bidi analysis of text given as characters. unicode-bidi reads text
79/// as UTF-8 or UTF-16 and indexes it by code unit, so the text goes through
80/// UTF-8, and this maps between its byte offsets and the characters'
81/// indices.
82struct Analysis<'text> {
83    info: BidiInfo<'text>,
84    /// The byte offset of each character and of the end of the text; empty
85    /// when the text is ASCII, where the two are the same.
86    offsets: Vec<usize>,
87}
88
89impl<'text> Analysis<'text> {
90    fn new(text: &[char], utf8: &'text mut String) -> Self {
91        utf8.reserve(text.iter().map(|c| c.len_utf8()).sum());
92        utf8.extend(text);
93        let offsets = if utf8.len() == text.len() {
94            Vec::new()
95        } else {
96            let mut offsets = Vec::with_capacity(text.len() + 1);
97            offsets.push(0);
98            offsets.extend(text.iter().scan(0, |offset, c| {
99                *offset += c.len_utf8();
100                Some(*offset)
101            }));
102            offsets
103        };
104        Analysis { info: BidiInfo::new(utf8, None), offsets }
105    }
106
107    /// The byte offset of the character at `index`, or of the text's end.
108    fn byte(&self, index: usize) -> usize {
109        if self.offsets.is_empty() { index } else { self.offsets[index] }
110    }
111
112    /// The index of the character that starts at byte `offset`, or of the
113    /// text's end.
114    fn char(&self, offset: usize) -> usize {
115        if self.offsets.is_empty() { offset } else { self.offsets.partition_point(|&o| o < offset) }
116    }
117
118    fn chars(&self, bytes: Range<usize>) -> Range<usize> {
119        self.char(bytes.start)..self.char(bytes.end)
120    }
121
122    /// The text's paragraphs, as ranges of characters.
123    fn paragraphs(&self) -> impl Iterator<Item = Range<usize>> {
124        self.info.paragraphs.iter().map(|paragraph| self.chars(paragraph.range.clone()))
125    }
126
127    /// The lines of the text that end at `line_breaks` and at the ends of its
128    /// paragraphs, so that no line crosses a paragraph boundary.
129    fn lines(&self, mut line_breaks: VecSet<usize>) -> impl Iterator<Item = Range<usize>> {
130        let len = self.char(self.info.text.len());
131        debug_assert!(
132            line_breaks.iter().all(|&point| 0 < point && point <= len),
133            "line breaks {line_breaks:?} outside 1..={len}"
134        );
135        for paragraph in self.paragraphs() {
136            line_breaks.insert(paragraph.end);
137        }
138        let mut start = 0;
139        // A release build drops points outside the text rather than panic.
140        line_breaks.into_iter().filter(move |&end| 0 < end && end <= len).map(move |end| {
141            let line = start..end;
142            start = end;
143            line
144        })
145    }
146
147    /// The visual runs of `line`, a nonempty line of the text within one
148    /// paragraph: whether each runs right to left, and its logical range, in
149    /// visual order.
150    fn line_runs(&self, line: Range<usize>) -> Vec<(bool, Range<usize>)> {
151        let line = self.byte(line.start)..self.byte(line.end);
152        let paragraphs = &self.info.paragraphs;
153        let paragraph = &paragraphs[paragraphs.partition_point(|p| p.range.end <= line.start)];
154        let (levels, runs) = self.info.visual_runs(paragraph, line);
155        runs.into_iter().map(|run| (levels[run.start].is_rtl(), self.chars(run))).collect()
156    }
157}
158
159/// Splits `text`, in logical order, into lines at `line_breaks`, and writes
160/// each line in visual order.
161pub(crate) fn reorder_lines(text: &[char], line_breaks: VecSet<usize>) -> Vec<Vec<char>> {
162    let mut utf8 = String::new();
163    let analysis = Analysis::new(text, &mut utf8);
164    analysis
165        .lines(line_breaks)
166        .map(|line| {
167            let mut out = Vec::with_capacity(line.len());
168            for (rtl, run) in analysis.line_runs(line) {
169                write_run(&text[run], rtl, &mut out);
170            }
171            out
172        })
173        .collect()
174}
175
176/// Like [`reorder_lines`], with each character's style, except that LTR runs
177/// keep their BiDi controls, and an RTL run's first character takes the
178/// style of the chunk after it unless either style is a block.
179pub(crate) fn reorder_styled_lines(input: &StyledText, line_breaks: VecSet<usize>) -> Vec<StyledText> {
180    reorder_styled_lines_with_blocks(input, line_breaks, &input.text, &[])
181}
182
183/// Like [`reorder_styled_lines`], but the bidi analysis reads `bidi_text`,
184/// which is as long as the input's text, and a right-to-left run keeps the
185/// order of the text in the styles that `block_styles` marks, which a shaper
186/// already laid out in visual order.
187pub(crate) fn reorder_styled_lines_with_blocks(
188    input: &StyledText,
189    line_breaks: VecSet<usize>,
190    bidi_text: &[char],
191    block_styles: &[bool],
192) -> Vec<StyledText> {
193    debug_assert_eq!(bidi_text.len(), input.text.len());
194    let input_text = &input.text;
195    let style_indices = &input.styles;
196    let is_block = |style: SectionIndex| block_styles.get(style as usize).copied().unwrap_or(false);
197
198    let mut utf8 = String::new();
199    let analysis = Analysis::new(bidi_text, &mut utf8);
200    let mut out = Vec::new();
201    for line_range in analysis.lines(line_breaks) {
202        let mut line = StyledText { text: Vec::new(), styles: Vec::with_capacity(line_range.len()) };
203
204        for (is_reversed, run) in analysis.line_runs(line_range) {
205            let logical_start = run.start;
206            let logical_end = run.end;
207            if is_reversed {
208                // Within this reversed section, iterate logically
209                // backwards. Each time we see a change in style, render
210                // a reversed chunk of everything since the last change.
211                //
212                let mut style_run_start = logical_end;
213                let mut current_style_index = style_indices[style_run_start - 1];
214                let mut add_chunk = |start: usize, end: usize, style: SectionIndex| {
215                    // A block's text is already in visual order.
216                    let mut reversed = Vec::new();
217                    if is_block(style) {
218                        reversed.extend_from_slice(&input_text[start..end]);
219                    } else {
220                        write_run(&input_text[start..end], true, &mut reversed);
221                    }
222                    line.text.extend_from_slice(&reversed);
223                    line.styles.extend(std::iter::repeat_n(style, reversed.len()));
224                };
225                let mut i = logical_end - 1;
226                while i >= logical_start {
227                    if current_style_index != style_indices[i] || i == logical_start {
228                        // The run's first character joins the chunk
229                        // after it even when its style differs, as GL JS
230                        // lays it out, except next to a block, which
231                        // holds only its own text.
232                        let split_first = i == logical_start
233                            && current_style_index != style_indices[i]
234                            && (is_block(current_style_index) || is_block(style_indices[i]));
235                        let style_run_end = if i == logical_start && !split_first { i } else { i + 1 };
236                        add_chunk(style_run_end, style_run_start, current_style_index);
237                        current_style_index = style_indices[i];
238                        style_run_start = style_run_end;
239                        if split_first {
240                            add_chunk(i, i + 1, current_style_index);
241                            style_run_start = i;
242                        }
243                    }
244                    if i == 0 {
245                        break;
246                    }
247                    i -= 1;
248                }
249            } else {
250                line.text.extend_from_slice(&input_text[logical_start..logical_end]);
251                line.styles.extend_from_slice(&style_indices[logical_start..logical_end]);
252            }
253        }
254
255        out.push(line);
256    }
257    out
258}
259
260/// Splits text in logical order into runs of one direction each, and
261/// returns the runs in visual order: each paragraph's runs in visual order,
262/// the paragraphs in logical order. Each run keeps its logical order, so a
263/// shaper such as HarfBuzz can lay it out in its direction. Text with no runs
264/// is one LTR run.
265#[must_use]
266pub fn visual_runs(text: &[char]) -> Vec<BiDiRun> {
267    let mut runs = Vec::new();
268    if text.is_empty() {
269        return runs;
270    }
271
272    let mut utf8 = String::new();
273    let analysis = Analysis::new(text, &mut utf8);
274    for paragraph in analysis.paragraphs() {
275        for (rtl, run) in analysis.line_runs(paragraph) {
276            if run.is_empty() {
277                continue;
278            }
279            runs.push(BiDiRun { text: text[run].to_vec(), rtl });
280        }
281    }
282
283    if runs.is_empty() {
284        runs.push(BiDiRun { text: text.to_vec(), rtl: false });
285    }
286    runs
287}
288
289/// These tests mirror the unit tests in mapbox-gl-rtl-text's arabic.test.js.
290#[cfg(test)]
291mod bidi_test {
292    use super::*;
293    use crate::text::arabic::shape_arabic;
294
295    fn u(s: &str) -> Vec<char> {
296        s.chars().collect()
297    }
298
299    fn set(v: &[usize]) -> VecSet<usize> {
300        v.iter().copied().collect()
301    }
302
303    fn styled(text: Vec<char>, styles: Vec<SectionIndex>) -> StyledText {
304        StyledText { text, styles }
305    }
306
307    // gtest: BiDi.ReverseArabic
308    #[test]
309    fn reverse_arabic() {
310        assert_eq!(reorder_lines(&shape_arabic(&u("سلام۳۹")), set(&[])), vec![u("۳۹ﻡﻼﺳ")]);
311    }
312
313    // gtest: BiDi.ReverseMixed
314    #[test]
315    fn reverse_mixed() {
316        assert_eq!(
317            reorder_lines(&shape_arabic(&u("مكتبة الإسكندرية\u{200E}\u{200E} Maktabat al-Iskandarīyah")), set(&[])),
318            vec![u(" Maktabat al-Iskandarīyahﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ")]
319        );
320    }
321
322    // gtest: BiDi.WithLineBreaks
323    #[test]
324    fn with_line_breaks() {
325        let expected = vec![u(" ﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ"), u("Maktabat al-"), u("Iskandarīyah")];
326        assert_eq!(
327            reorder_lines(
328                &shape_arabic(&u("مكتبة الإسكندرية\u{200E}\u{200E} Maktabat al-Iskandarīyah")),
329                set(&[18, 30])
330            ),
331            expected
332        );
333    }
334
335    // gtest: BiDi.StyledText
336    #[test]
337    fn styled_text() {
338        // This test uses line breaks that intentionally split/reorder/
339        // interleave styled blocks that are contiguous in the input
340        let input = styled(
341            shape_arabic(&u("مكتبة الإسكندرية\u{200E}\u{200E} Maktabat al-Iskandarīyah")).into_owned(),
342            vec![
343                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,
344                6, 6, 6, 6, 6, 7, 7, 7,
345            ],
346        );
347
348        let expected: Vec<StyledText> = vec![
349            styled(u("ﺔﺒﺘﻜﻣ"), vec![0, 0, 0, 0, 0]),
350            styled(u(" \u{200E}\u{200E}ﺔﻳﺭﺪﻨﻜﺳﻹﺍ "), vec![2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1]),
351            styled(u("Maktabat al-"), vec![2, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6]),
352            styled(u("Iskandarīyah"), vec![6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7]),
353        ];
354        for line in &expected {
355            assert_eq!(line.text.len(), line.styles.len());
356        }
357
358        assert_eq!(reorder_styled_lines(&input, set(&[5, 18, 30])), expected);
359    }
360
361    // gtest: BiDi.VisualRuns
362    #[test]
363    fn visual_runs_split_by_direction() {
364        let runs = visual_runs(&u("Erbil هەولێر"));
365        assert_eq!(runs.len(), 2);
366        assert_eq!(runs[0].text, u("Erbil "));
367        assert!(!runs[0].rtl);
368        assert_eq!(runs[1].text, u("هەولێر"));
369        assert!(runs[1].rtl);
370    }
371
372    // gtest: BiDi.VisualRunsRightToLeftParagraph
373    #[test]
374    fn visual_runs_right_to_left_paragraph() {
375        // The runs come in visual order, left to right, each in logical order.
376        let runs = visual_runs(&u("هەولێر Erbil"));
377        assert_eq!(runs.len(), 2);
378        assert_eq!(runs[0].text, u("Erbil"));
379        assert!(!runs[0].rtl);
380        assert_eq!(runs[1].text, u("هەولێر "));
381        assert!(runs[1].rtl);
382    }
383
384    // gtest: BiDi.BlocksKeepTheirOrderInRightToLeftRuns
385    #[test]
386    fn blocks_keep_their_order_in_right_to_left_runs() {
387        // "XY" stands for glyphs that a shaper already laid out right to
388        // left. Bidi sees them as Hebrew letters, and moves them without
389        // reversing them.
390        let input = styled(u("XY Erbil"), vec![0, 0, 1, 1, 1, 1, 1, 1]);
391        let lines = reorder_styled_lines_with_blocks(&input, set(&[]), &u("אא Erbil"), &[true, false]);
392        assert_eq!(lines.len(), 1);
393        assert_eq!(lines[0].text, u("Erbil XY"));
394        assert_eq!(lines[0].styles, vec![1, 1, 1, 1, 1, 1, 0, 0]);
395    }
396
397    // gtest: BiDi.BlockAtTheStartOfARunTakesOnlyItsOwnText
398    #[test]
399    fn block_at_the_start_of_a_run_takes_only_its_own_text() {
400        // The run "-XY" reads right to left, and its first character, "-",
401        // is not part of the block.
402        let input = styled(u("-XY"), vec![0, 1, 1]);
403        let lines = reorder_styled_lines_with_blocks(&input, set(&[]), &u("-אא"), &[false, true]);
404        assert_eq!(lines.len(), 1);
405        assert_eq!(lines[0].text, u("XY-"));
406        assert_eq!(lines[0].styles, vec![1, 1, 0]);
407    }
408
409    #[test]
410    fn starts_right_to_left_at_the_first_strong_character() {
411        assert!(!starts_right_to_left(&u("1 abc שלום")));
412        assert!(starts_right_to_left(&u("1 שלום abc")));
413        assert!(starts_right_to_left(&u("(سلام)")));
414        // A supplementary letter (Adlam).
415        assert!(starts_right_to_left(&u("\u{1E900}")));
416        assert!(!starts_right_to_left(&u("123 !?")));
417    }
418
419    #[test]
420    fn mirrors_the_characters_unicode_mirrors() {
421        assert_eq!(mirror('('), ')');
422        assert_eq!(mirror('<'), '>');
423        assert_eq!(mirror('«'), '»');
424        assert_eq!(mirror('≤'), '≥');
425        assert_eq!(mirror('a'), 'a');
426        assert_eq!(mirror('\u{1E900}'), '\u{1E900}');
427    }
428
429    #[test]
430    fn writes_rtl_runs_mirrored() {
431        let mut out = Vec::new();
432        write_run(&u("א<ב(ג"), true, &mut out);
433        assert_eq!(out, u("ג)ב>א"));
434    }
435
436    #[test]
437    fn writes_runs_without_bidi_controls() {
438        let mut out = Vec::new();
439        write_run(&u("a\u{200D}b\u{202A}c\u{2069}(\u{200F}"), false, &mut out);
440        assert_eq!(out, u("abc("));
441    }
442
443    #[test]
444    fn reverses_rtl_runs_by_character() {
445        let mut out = Vec::new();
446        write_run(&u("א\u{1E900}ב"), true, &mut out);
447        assert_eq!(out, u("ב\u{1E900}א"));
448    }
449
450    #[test]
451    fn breaks_lines_by_character_beyond_ascii() {
452        // Line breaks and runs count characters, whatever their length in
453        // UTF-8.
454        assert_eq!(reorder_lines(&u("é😀ab\nש😀"), set(&[2])), vec![u("é😀"), u("ab\n"), u("😀ש")]);
455        let runs = visual_runs(&u("a😀 שלום x"));
456        assert_eq!(
457            runs.iter().map(|run| (run.text.clone(), run.rtl)).collect::<Vec<_>>(),
458            [(u("a😀 "), false), (u("שלום"), true), (u(" x"), false)]
459        );
460    }
461
462    #[test]
463    fn mirroring_table_is_sorted_and_symmetric() {
464        assert!(BIDI_MIRRORING_GLYPH.windows(2).all(|w| w[0].0 < w[1].0));
465        for &(from, to) in &BIDI_MIRRORING_GLYPH {
466            let (from, to) = (char::from_u32(from.into()).unwrap(), char::from_u32(to.into()).unwrap());
467            assert_eq!(mirror(to), from, "U+{:04X}", u32::from(from));
468        }
469    }
470}