1use 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#[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
37fn 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
47fn is_bidi_control(c: char) -> bool {
49 matches!(
50 c,
51 '\u{200C}'..='\u{200F}'
53 | '\u{202A}'..='\u{202E}'
55 | '\u{2066}'..='\u{2069}'
57 )
58}
59
60fn 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#[derive(Clone, Debug, PartialEq)]
73pub struct BiDiRun {
74 pub text: Vec<char>,
75 pub rtl: bool,
76}
77
78struct Analysis<'text> {
83 info: BidiInfo<'text>,
84 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 fn byte(&self, index: usize) -> usize {
109 if self.offsets.is_empty() { index } else { self.offsets[index] }
110 }
111
112 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 fn paragraphs(&self) -> impl Iterator<Item = Range<usize>> {
124 self.info.paragraphs.iter().map(|paragraph| self.chars(paragraph.range.clone()))
125 }
126
127 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 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 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 = ¶graphs[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
159pub(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
176pub(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
183pub(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 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 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 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#[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#[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 #[test]
309 fn reverse_arabic() {
310 assert_eq!(reorder_lines(&shape_arabic(&u("سلام۳۹")), set(&[])), vec![u("۳۹ﻡﻼﺳ")]);
311 }
312
313 #[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 #[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 #[test]
337 fn styled_text() {
338 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 #[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 #[test]
374 fn visual_runs_right_to_left_paragraph() {
375 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 #[test]
386 fn blocks_keep_their_order_in_right_to_left_runs() {
387 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 #[test]
399 fn block_at_the_start_of_a_run_takes_only_its_own_text() {
400 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 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 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}