1use 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#[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
71fn 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
79fn 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
87fn 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 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#[derive(Clone, Debug, PartialEq)]
112pub struct BiDiRun {
113 pub(crate) text: Vec<char>,
114 pub(crate) rtl: bool,
115}
116
117struct Analysis<'text> {
122 info: BidiInfo<'text>,
123 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 fn byte(&self, index: usize) -> usize {
148 if self.offsets.is_empty() { index } else { self.offsets[index] }
149 }
150
151 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 fn paragraphs(&self) -> impl Iterator<Item = Range<usize>> {
163 self.info.paragraphs.iter().map(|paragraph| self.chars(paragraph.range.clone()))
164 }
165
166 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 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 = ¶graphs[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
184pub(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
210pub(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
217pub(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 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 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 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#[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 let cases: [(&str, &[usize], &[&str]); 5] = [
361 ("سلام۳۹", &[], &["۳۹ﻡﻼﺳ"]),
362 (LIBRARY, &[], &[" Maktabat al-Iskandarīyahﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ"]),
363 (LIBRARY, &[18, 30], &[" ﺔﻳﺭﺪﻨﻜﺳﻹﺍ ﺔﺒﺘﻜﻣ", "Maktabat al-", "Iskandarīyah"]),
364 ("é😀ab\nש😀", &[2], &["é😀", "ab\n", "😀ש"]),
366 ("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 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 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 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 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 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 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 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}