use std::borrow::Cow;
use f_office_units::Length;
use unicode_bidi::{BidiClass, BidiDataSource, BidiInfo, HardcodedBidiData, Level, bidi_class};
use crate::lines::{Line, Piece, is_space, right_to_left, run_glyph, run_rtl};
use crate::params::BRACKET_PAIR_DEPTH;
use crate::props::BidiLanguageClass;
fn char_of(piece: &Piece) -> char {
match piece {
Piece::Glyph(glyph) => glyph.ch,
Piece::Tab(_) | Piece::PositionTab(..) => '\t',
_ => '\u{FFFC}',
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stand {
Own,
Left,
Right,
}
impl Stand {
fn char_of(self, piece: &Piece, arabic: bool) -> char {
match self {
Self::Own => char_of(piece),
Self::Left => '\u{200E}',
Self::Right => right_mark(arabic),
}
}
}
fn right_mark(arabic: bool) -> char {
if arabic {
ARABIC_LETTER_MARK
} else {
'\u{200F}'
}
}
const ARABIC_LETTER_MARK: char = '\u{061C}';
fn arabic_after(arabic: bool, ch: char) -> bool {
match bidi_class(ch) {
BidiClass::AL => true,
BidiClass::L | BidiClass::R => false,
_ => arabic,
}
}
fn run_class(piece: &Piece) -> Option<BidiLanguageClass> {
run_glyph(piece).and_then(|glyph| glyph.direction.class())
}
fn sequence_char(piece: &Piece) -> char {
let ch = char_of(piece);
let neutral = run_class(piece).is_some_and(BidiLanguageClass::has_neutral_slash);
if ch == '/' && neutral { '\u{FFFC}' } else { ch }
}
fn starts_arabic(run: &[crate::lines::Placed]) -> bool {
run.iter()
.take_while(|placed| run_rtl(&placed.piece) == Some(true))
.find_map(|placed| match class_of(&placed.piece) {
BidiClass::L | BidiClass::R | BidiClass::AL => Some(false),
BidiClass::EN => Some(
run_class(&placed.piece).is_some_and(BidiLanguageClass::starts_with_arabic_number),
),
_ => None,
})
.unwrap_or(false)
}
fn class_of(piece: &Piece) -> BidiClass {
bidi_class(char_of(piece))
}
fn numeric(class: BidiClass) -> bool {
matches!(
class,
BidiClass::EN | BidiClass::AN | BidiClass::ES | BidiClass::ET | BidiClass::CS
)
}
fn stands(placed: &[crate::lines::Placed], units: &[bool]) -> Vec<Stand> {
let mut stands = vec![Stand::Own; placed.len()];
let mut start = 0;
while start < placed.len() {
let end = run_end(placed, start);
let run = placed.get(start..end).unwrap_or_default();
let marks = stands.get_mut(start..end).unwrap_or_default();
let in_unit = units.get(start).copied().unwrap_or(false);
match run.first().and_then(|first| run_rtl(&first.piece)) {
Some(false) if !in_unit => left_run(run, marks),
Some(true) => right_run(run, marks),
_ => {}
}
start = end;
}
numeric_tokens(placed, &mut stands, units);
bracketed_numbers(placed, &mut stands, units);
stands
}
fn left_units(placed: &[crate::lines::Placed]) -> Vec<bool> {
let mut units = vec![false; placed.len()];
let mut start = 0;
while start < placed.len() {
let count = placed
.iter()
.skip(start)
.take_while(|p| run_rtl(&p.piece) == Some(false))
.count();
let end = start + count;
if placed
.get(start..end)
.is_some_and(holds_right_to_left_letter)
{
units.get_mut(start..end).unwrap_or_default().fill(true);
}
start = end.max(start + 1);
}
units
}
fn holds_right_to_left_letter(pieces: &[crate::lines::Placed]) -> bool {
pieces
.iter()
.any(|p| matches!(class_of(&p.piece), BidiClass::R | BidiClass::AL))
}
fn bracketed_numbers(placed: &[crate::lines::Placed], stands: &mut [Stand], units: &[bool]) {
let mut start = 0;
while start < placed.len() {
let count = units.iter().skip(start).take_while(|&&unit| unit).count();
let end = start + count;
let unit = placed.get(start..end).unwrap_or_default();
let mut inside = vec![false; unit.len()];
for (open, close) in bracket_pairs(unit) {
inside
.get_mut(open + 1..close)
.unwrap_or_default()
.fill(true);
}
let mut arabic = false;
for (index, (placed, &bracketed)) in unit.iter().zip(&inside).enumerate() {
let class = class_of(&placed.piece);
arabic = arabic_after(arabic, char_of(&placed.piece));
if bracketed
&& class == BidiClass::EN
&& !arabic
&& let Some(stand) = stands.get_mut(start + index)
{
*stand = Stand::Left;
}
}
start = end.max(start + 1);
}
}
fn bracket_pairs(pieces: &[crate::lines::Placed]) -> Vec<(usize, usize)> {
let mut open: Vec<(char, usize)> = Vec::new();
let mut pairs = Vec::new();
for (index, placed) in pieces.iter().enumerate() {
let ch = char_of(&placed.piece);
let Some(bracket) = HardcodedBidiData.bidi_matched_opening_bracket(ch) else {
continue;
};
if bidi_class(ch) != BidiClass::ON {
continue;
}
if bracket.is_open {
if open.len() == BRACKET_PAIR_DEPTH {
break;
}
open.push((bracket.opening, index));
} else if let Some(depth) = open.iter().rposition(|&(ch, _)| ch == bracket.opening) {
if let Some(&(_, first)) = open.get(depth) {
pairs.push((first, index));
}
open.truncate(depth);
}
}
pairs
}
fn run_end(placed: &[crate::lines::Placed], start: usize) -> usize {
let rtl = placed.get(start).and_then(|first| run_rtl(&first.piece));
let more = placed
.iter()
.skip(start + 1)
.take_while(|next| {
rtl.is_some()
&& run_rtl(&next.piece) == rtl
&& (rtl == Some(true)
|| !run_glyph(&next.piece).is_some_and(|glyph| glyph.starts_run))
})
.count();
start + 1 + more
}
fn left_run(run: &[crate::lines::Placed], stands: &mut [Stand]) {
let foreign = |class| matches!(class, BidiClass::R | BidiClass::AL | BidiClass::AN);
if run.iter().any(|p| foreign(class_of(&p.piece))) {
return;
}
for (placed, stand) in run.iter().zip(stands) {
let own = matches!(class_of(&placed.piece), BidiClass::L | BidiClass::NSM);
if !own {
*stand = Stand::Left;
}
}
}
fn right_run(run: &[crate::lines::Placed], stands: &mut [Stand]) {
let lead = starts_arabic(run).then_some(ARABIC_LETTER_MARK);
let text: String = lead
.into_iter()
.chain(run.iter().map(|p| sequence_char(&p.piece)))
.collect();
let info = BidiInfo::new(&text, Some(Level::rtl()));
let levels = text
.char_indices()
.skip(usize::from(lead.is_some()))
.map(|(at, _)| info.levels.get(at));
for ((placed, stand), level) in run.iter().zip(stands).zip(levels) {
let weak = matches!(
class_of(&placed.piece),
BidiClass::WS | BidiClass::ON | BidiClass::ES | BidiClass::ET | BidiClass::CS
);
if weak && level.is_some_and(Level::is_rtl) {
*stand = Stand::Right;
}
}
}
fn numeric_tokens(placed: &[crate::lines::Placed], stands: &mut [Stand], units: &[bool]) {
let eligible = |index: usize, piece: &Piece| {
!units.get(index).copied().unwrap_or(false)
&& run_rtl(piece) == Some(false)
&& matches!(
class_of(piece),
BidiClass::EN | BidiClass::ES | BidiClass::ET | BidiClass::CS | BidiClass::ON
)
};
let mut start = 0;
while start < placed.len() {
let count = placed
.iter()
.enumerate()
.skip(start)
.take_while(|&(index, p)| eligible(index, &p.piece))
.count();
let token = placed.get(start..start + count).unwrap_or_default();
if token.iter().any(|p| class_of(&p.piece) == BidiClass::EN) {
for stand in stands.get_mut(start..start + count).unwrap_or_default() {
*stand = Stand::Left;
}
}
start += count.max(1);
}
}
fn parted(before: (&Piece, Stand), after: (&Piece, Stand)) -> bool {
let number = |(piece, stand): (&Piece, Stand)| {
let class = class_of(piece);
run_rtl(piece) == Some(true)
&& stand == Stand::Own
&& (numeric(class) || class == BidiClass::L)
};
let left = |(piece, _): (&Piece, Stand)| run_rtl(piece) == Some(false);
(number(before) && left(after)) || (left(before) && number(after))
}
fn embedding(before: Option<&Piece>, here: &Piece) -> Option<char> {
let inside = before.and_then(run_rtl) == Some(true);
match (inside, run_rtl(here) == Some(true)) {
(false, true) => Some('\u{202B}'),
(true, false) => Some('\u{202C}'),
_ => None,
}
}
fn ordering(
all: &[crate::lines::Placed],
rtl: bool,
units: &[bool],
) -> (String, Vec<Option<usize>>) {
let stands = stands(all, units);
let mut text = String::new();
let mut pieces = Vec::with_capacity(all.len());
let mut before: Option<(&Piece, Stand)> = None;
let mut arabic = false;
for (index, (placed, &stand)) in all.iter().zip(&stands).enumerate() {
let here = (&placed.piece, stand);
if before.is_some_and(|before| parted(before, here)) {
text.push(right_mark(arabic));
pieces.push(None);
}
let mark = embedding(before.map(|(piece, _)| piece), &placed.piece);
if let Some(mark) = mark.filter(|_| !rtl) {
text.push(mark);
pieces.push(None);
}
let unit = units.get(index).copied().unwrap_or(false);
let after_unit = index > 0 && units.get(index - 1).copied().unwrap_or(false);
if rtl && unit != after_unit {
text.push(if unit { '\u{202A}' } else { '\u{202C}' });
pieces.push(None);
}
let first = before.and_then(|(piece, _)| run_rtl(piece)) != Some(true);
if first && starts_arabic(all.get(index..).unwrap_or_default()) {
text.push(ARABIC_LETTER_MARK);
pieces.push(None);
arabic = true;
}
let ch = stand.char_of(&placed.piece, arabic);
arabic = arabic_after(arabic, ch);
text.push(ch);
pieces.push(Some(index));
before = Some(here);
}
(text, pieces)
}
pub(super) struct Visual<'a> {
pub line: Cow<'a, Line>,
pub right_to_left: Vec<bool>,
pub written: usize,
pub order: Vec<usize>,
}
pub(super) fn visual(line: &Line, rtl: bool, units: bool) -> Visual<'_> {
let own = line.written();
let (line, right_to_left, order) = reorder(line, rtl, units);
let written = if rtl { own } else { line.written() };
Visual {
line,
right_to_left,
written,
order,
}
}
fn end_spaces(line: &Line) -> usize {
line.placed
.iter()
.rev()
.take_while(|p| is_space(&p.piece))
.count()
}
pub(in crate::layout) fn end_space_runs(
line: &Line,
want: bool,
) -> impl Iterator<Item = bool> + '_ {
let spaces = end_spaces(line);
let first = match line.placed.len() - spaces {
0 => line.placed.len(),
first => first,
};
line.placed
.get(first..)
.unwrap_or_default()
.iter()
.map(move |p| run_rtl(&p.piece) == Some(want))
}
fn unit_mirrors(
pieces: &[crate::lines::Placed],
units: &[bool],
visual: &[(usize, bool)],
) -> Vec<bool> {
if !units.contains(&true) {
return Vec::new();
}
let mut mirrors = vec![false; pieces.len()];
for &(index, rtl) in visual {
let bracket = pieces
.get(index)
.and_then(|placed| run_glyph(&placed.piece))
.is_some_and(|glyph| glyph.unit_mirror.is_some());
if let Some(mirror) = mirrors.get_mut(index) {
*mirror = rtl && bracket && units.get(index) == Some(&true);
}
}
mirrors
}
fn mirror_bracket(piece: &mut Piece) {
if let Piece::Glyph(glyph) = piece
&& let Some(mirrored) = glyph.unit_mirror
{
glyph.id = mirrored.id;
glyph.ch = mirrored.ch;
}
}
fn reorder(line: &Line, rtl: bool, units: bool) -> (Cow<'_, Line>, Vec<bool>, Vec<usize>) {
let turns = |piece: &Piece| right_to_left(char_of(piece)) || run_rtl(piece) == Some(true);
if !rtl && !line.placed.iter().any(|p| turns(&p.piece)) {
return (Cow::Borrowed(line), Vec::new(), Vec::new());
}
let spaces = end_spaces(line);
let trailing = spaces - line.written_end_spaces.min(spaces);
let content = line.placed.len() - trailing;
let pieces = line.placed.get(..content).unwrap_or_default();
let units = if units {
left_units(pieces)
} else {
vec![false; pieces.len()]
};
let (text, stood) = ordering(pieces, rtl, &units);
let base = if rtl { Level::rtl() } else { Level::ltr() };
let info = BidiInfo::new(&text, Some(base));
let Some(paragraph) = info.paragraphs.first() else {
return (Cow::Borrowed(line), Vec::new(), Vec::new());
};
let levels = info.reordered_levels_per_char(paragraph, 0..text.len());
let visual: Vec<(usize, bool)> = BidiInfo::reorder_visual(&levels)
.into_iter()
.filter_map(|at| {
let piece = stood.get(at).copied().flatten()?;
Some((piece, levels.get(at).is_some_and(Level::is_rtl)))
})
.collect();
let order: Vec<usize> = visual.iter().map(|&(piece, _)| piece).collect();
let directions = visual
.iter()
.map(|&(_, rtl)| rtl)
.chain((content..line.placed.len()).map(|_| false))
.collect();
let mirrors = unit_mirrors(pieces, &units, &visual);
if order.iter().enumerate().all(|(i, &j)| i == j) {
if !mirrors.contains(&true) {
return (Cow::Borrowed(line), directions, Vec::new());
}
let mut placed = line.placed.clone();
for (piece, _) in placed
.iter_mut()
.zip(&mirrors)
.filter(|(_, mirror)| **mirror)
{
mirror_bracket(&mut piece.piece);
}
return (
Cow::Owned(Line {
placed,
..line.clone()
}),
directions,
Vec::new(),
);
}
let order: Vec<usize> = order
.into_iter()
.chain(content..line.placed.len())
.collect();
let mut x = line.placed.first().map_or(Length::ZERO, |p| p.x);
let mut placed = Vec::with_capacity(line.placed.len());
for &index in &order {
let Some(mut piece) = line.placed.get(index).copied() else {
continue;
};
if mirrors.get(index) == Some(&true) {
mirror_bracket(&mut piece.piece);
}
piece.x = x;
x += piece.advance;
placed.push(piece);
}
(
Cow::Owned(Line {
placed,
written_end_spaces: 0,
..line.clone()
}),
directions,
order,
)
}
#[cfg(test)]
mod tests {
use super::visual;
use crate::lines::{Line, NoteNumber, Piece, Placed};
use crate::props::BidiLanguageClass;
use crate::text::{FaceIndex, Glyph, MirroredGlyph};
use f_office_units::Length;
fn ordering_text(placed: &[Placed]) -> String {
super::ordering(placed, true, &vec![false; placed.len()]).0
}
fn line(text: &str) -> Line {
Line {
placed: text
.chars()
.enumerate()
.map(|(i, ch)| Placed {
piece: Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)),
x: Length::from_units(i64::try_from(i).unwrap() * 10),
advance: Length::from_units(10),
leader: None,
tab: None,
})
.collect(),
..Line::default()
}
}
fn shown(line: &Line) -> String {
let mut placed = line.placed.clone();
placed.sort_by_key(|p| p.x);
placed
.iter()
.map(|p| match p.piece {
Piece::Glyph(g) => g.ch,
_ => '?',
})
.collect()
}
#[test]
fn leaves_left_to_right_lines_alone() {
let plain = line("abc def");
let shown = visual(&plain, false, false);
assert!(matches!(shown.line, std::borrow::Cow::Borrowed(_)));
assert_eq!(shown.right_to_left, [] as [bool; 0]);
}
#[test]
fn turns_hebrew_around_inside_left_to_right_text() {
let mixed = line("ab \u{5d0}\u{5d1}\u{5d2} cd");
let reordered = visual(&mixed, false, false);
assert_eq!(shown(&reordered.line), "ab \u{5d2}\u{5d1}\u{5d0} cd");
let directions: String = reordered
.right_to_left
.iter()
.map(|&rtl| if rtl { 'r' } else { 'l' })
.collect();
assert_eq!(directions, "lllrrrlll");
}
#[test]
fn orders_the_runs_of_a_right_to_left_paragraph_from_the_right() {
let mixed = line("\u{5d0}\u{5d1} copy ");
let reordered = visual(&mixed, true, false);
assert_eq!(shown(&reordered.line), "copy \u{5d1}\u{5d0} ");
assert_eq!(
reordered.right_to_left,
[false, false, false, false, true, true, true, false]
);
}
#[test]
fn keeps_non_rtl_numbers_and_punctuation_together_after_arabic() {
for token in ["(83.6%)", "[%83.6]", "[83/6%]", "(83-6%)"] {
let mixed = line(&format!("\u{062A}\u{062A} {token}"));
let reordered = visual(&mixed, true, false);
assert_eq!(shown(&reordered.line), format!("{token} \u{062A}\u{062A}"));
assert!(
reordered.right_to_left[..token.chars().count()]
.iter()
.all(|rtl| !rtl)
);
}
}
#[test]
fn orders_a_left_to_right_unit_with_arabic_letters_by_its_own_classes() {
let mixed = line("\u{062A}\u{062A} \u{062B}\u{062B} (2010).,");
let unit = ")2010( \u{062B}\u{062B} \u{062A}\u{062A}.,";
assert_eq!(shown(&visual(&mixed, false, true).line), unit);
assert_eq!(shown(&visual(&mixed, true, true).line), unit);
assert_eq!(
shown(&visual(&mixed, false, false).line),
"\u{062B}\u{062B} \u{062A}\u{062A} (2010).,"
);
let token = line("\u{062A}\u{062A} (83.6%)");
assert_eq!(
shown(&visual(&token, true, true).line),
")%83.6( \u{062A}\u{062A}"
);
}
#[test]
fn mirrors_the_brackets_of_a_unit_that_resolve_right_to_left_where_their_run_gives_a_glyph() {
let marked = |text: &str| {
let mut mixed = line(text);
for placed in &mut mixed.placed {
if let Piece::Glyph(glyph) = &mut placed.piece
&& matches!(glyph.ch, '(' | ')')
{
glyph.unit_mirror = Some(MirroredGlyph {
id: 7,
ch: glyph.ch,
});
}
}
mixed
};
let ids = |shown: &Line| -> Vec<(char, u32)> {
let mut placed = shown.placed.clone();
placed.sort_by_key(|p| p.x);
placed
.iter()
.filter_map(|p| match p.piece {
Piece::Glyph(g) if matches!(g.ch, '(' | ')') => Some((g.ch, g.id)),
_ => None,
})
.collect()
};
let mixed = marked("\u{062A}\u{062A} (2010)");
for rtl in [false, true] {
let unit = visual(&mixed, rtl, true);
assert_eq!(shown(&unit.line), ")2010( \u{062A}\u{062A}");
assert_eq!(ids(&unit.line), [(')', 7), ('(', 7)]);
}
assert_eq!(
ids(&visual(&mixed, false, false).line),
[('(', 1), (')', 1)]
);
let before = marked("(2010) \u{062A}\u{062A}");
assert_eq!(
ids(&visual(&before, false, true).line),
[('(', 1), (')', 1)]
);
let plain = line("\u{062A}\u{062A} (2010)");
assert_eq!(ids(&visual(&plain, false, true).line), [(')', 1), ('(', 1)]);
}
#[test]
fn keeps_a_bracketed_number_after_hebrew_left_to_right_in_a_unit() {
for rtl in [false, true] {
let bracketed = line("\u{05D0}\u{05D1} (2010)");
assert_eq!(
shown(&visual(&bracketed, rtl, true).line),
"\u{05D1}\u{05D0} (2010)"
);
let bare = line("\u{05D0}\u{05D1} 12/5");
assert_eq!(
shown(&visual(&bare, rtl, true).line),
"12/5 \u{05D1}\u{05D0}"
);
}
}
#[test]
fn joins_a_run_without_letters_to_the_unit_of_the_run_before() {
let mut mixed = line("\u{062A}\u{062A} (2010)");
if let Some(Piece::Glyph(glyph)) = mixed.placed.get_mut(3).map(|p| &mut p.piece) {
glyph.starts_run = true;
}
assert_eq!(
shown(&visual(&mixed, false, true).line),
")2010( \u{062A}\u{062A}"
);
assert_eq!(
shown(&visual(&mixed, false, false).line),
"\u{062A}\u{062A} (2010)"
);
}
#[test]
fn ends_the_rtl_sequence_at_a_number_of_a_left_to_right_paragraph() {
let mixed = line("\u{05D0}\u{05D1} 2 \u{05D2}\u{05D3} 3");
assert_eq!(
shown(&visual(&mixed, false, false).line),
"\u{05D1}\u{05D0} 2 \u{05D3}\u{05D2} 3"
);
}
#[test]
fn keeps_a_number_of_an_rtl_run_in_the_sequence_of_a_left_to_right_paragraph() {
let mut mixed = line("\u{05D0}\u{05D1} 2 \u{05D2}\u{05D3} 3");
for placed in &mut mixed.placed {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.direction = crate::text::RunDirection::of(true, None);
}
}
assert_eq!(
shown(&visual(&mixed, false, false).line),
"3 \u{05D3}\u{05D2} 2 \u{05D1}\u{05D0}"
);
}
fn marked_from(text: &str, first: usize) -> Line {
let mut marked = line(text);
for placed in marked.placed.iter_mut().skip(first) {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.direction = crate::text::RunDirection::of(true, None);
}
}
marked
}
#[test]
fn puts_a_kept_line_end_space_of_an_rtl_run_before_its_word() {
let mut mixed = marked_from("ab \u{5d0}\u{5d1} ", 3);
assert_eq!(
super::end_space_runs(&mixed, true).collect::<Vec<_>>(),
[true]
);
let plain = visual(&mixed, false, false);
assert_eq!(shown(&plain.line), "ab \u{5d1}\u{5d0} ");
assert_eq!(plain.written, 5);
mixed.written_end_spaces = 1;
assert_eq!(mixed.written(), 6);
let kept = visual(&mixed, false, false);
assert_eq!(shown(&kept.line), "ab \u{5d1}\u{5d0}");
assert_eq!(kept.written, 6);
}
#[test]
fn tells_a_line_with_text_of_a_run_without_rtl() {
let marked = marked_from("\u{5d0}\u{5d1} \u{5d2} ", 0);
assert!(!marked.holds_left_to_right_text());
let mixed = marked_from("a \u{5d0}\u{5d1} ", 1);
assert!(mixed.holds_left_to_right_text());
let spaced = marked_from(" \u{5d0}\u{5d1}", 1);
assert!(!spaced.holds_left_to_right_text());
}
#[test]
fn leaves_a_list_label_to_its_own_classes() {
let mut mixed = line("1- \u{062A}\u{062A}");
for placed in mixed.placed.iter_mut().take(2) {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.label = true;
}
}
assert_eq!(ordering_text(&mixed.placed), "1- \u{062A}\u{062A}");
assert_eq!(
shown(&visual(&mixed, true, false).line),
"\u{062A}\u{062A} -1"
);
}
#[test]
fn keeps_a_numeric_token_across_run_boundaries() {
let mut mixed = line("\u{062A}\u{062A} (83.6%)");
for placed in mixed.placed.iter_mut().skip(3) {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.starts_run = true;
}
}
assert_eq!(
shown(&visual(&mixed, true, false).line),
"(83.6%) \u{062A}\u{062A}"
);
}
fn runs(runs: &[(&str, bool)]) -> Line {
let text: String = runs.iter().map(|run| run.0).collect();
let mut built = line(&text);
let mut glyphs = built.placed.iter_mut();
for &(text, rtl) in runs {
for (index, placed) in glyphs.by_ref().take(text.chars().count()).enumerate() {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.starts_run = index == 0;
glyph.direction = crate::text::RunDirection::of(rtl, None);
}
}
}
built
}
const H1: &str = "\u{05D1}\u{05D3}";
const H2: &str = "\u{05D4}\u{05E7}";
const D1: &str = "\u{05D3}\u{05D1}";
const D2: &str = "\u{05E7}\u{05D4}";
fn both(line: &[(&str, bool)]) -> [String; 2] {
let line = runs(line);
[true, false].map(|rtl| shown(&visual(&line, rtl, false).line))
}
#[test]
fn draws_the_marks_of_a_run_without_rtl_from_the_left() {
let alone = both(&[(H1, true), (":;", false), (H2, true)]);
assert_eq!(alone, [format!("{D2}:;{D1}"), format!("{D1}:;{D2}")]);
let before = both(&[(H1, true), ("#*ef", false), (H2, true)]);
assert_eq!(before, [format!("{D2}#*ef{D1}"), format!("{D1}#*ef{D2}")]);
let after = both(&[(H1, true), ("ef#*", false), (H2, true)]);
assert_eq!(after, [format!("{D2}ef#*{D1}"), format!("{D1}ef#*{D2}")]);
let space = both(&[(H1, true), (" ", false), (H2, true)]);
assert_eq!(space, [format!("{D2} {D1}"), format!("{D1} {D2}")]);
}
#[test]
fn draws_the_spaces_of_a_run_without_rtl_from_the_left() {
assert_eq!(both(&[("- ", false), (H1, true)])[0], format!("{D1}- "));
assert_eq!(both(&[("ab ", false), (H1, true)])[0], format!("{D1}ab "));
assert_eq!(
both(&[(H1, true), (" ef", false)])[0],
format!(" ef{D1}")
);
assert_eq!(
both(&[(H1, true), (" ef", false), (H2, true)])[0],
format!("{D2} ef{D1}")
);
assert_eq!(
both(&[(H1, true), ("ef ", false), (H2, true)])[0],
format!("{D2}ef {D1}")
);
}
#[test]
fn puts_a_kept_line_end_space_of_an_ltr_run_after_its_word_in_bidi() {
let mut mixed = runs(&[(H1, true), (" ef ", false)]);
assert!(mixed.holds_right_to_left_text());
assert_eq!(
super::end_space_runs(&mixed, false).collect::<Vec<_>>(),
[true]
);
mixed.written_end_spaces = 1;
let kept = visual(&mixed, true, false);
assert_eq!(shown(&kept.line), format!(" ef {D1}"));
assert_eq!(kept.written, 8);
}
#[test]
fn draws_the_neutral_characters_of_a_run_with_rtl_from_the_right() {
let marks = both(&[("ef", false), (" ;", true), ("gh", false)]);
assert_eq!(marks, ["gh; ef", "ef; gh"]);
let spaces = both(&[
("\u{05D1}\u{05D3} ", true),
("ef", false),
(" \u{05D4}\u{05E7}", true),
]);
assert_eq!(spaces, [format!("{D2} ef {D1}"), format!(" {D1}ef{D2} ")]);
}
#[test]
fn keeps_a_number_after_arabic_letters_an_arabic_number_behind_the_marks() {
let all = both(&[("\u{062A}\u{062A} (27,4%)", true)]);
assert_eq!(all[0], ")%27,4( \u{062A}\u{062A}");
}
#[test]
fn keeps_a_space_between_a_latin_word_and_a_number_of_runs_with_rtl() {
let line = [(H1, true), (" ", true), ("ab", true), (" 7", true)];
assert_eq!(both(&line)[0], format!("ab 7 {D1}"));
}
#[test]
fn draws_runs_with_rtl_as_one_right_to_left_unit_in_both_paragraph_directions() {
let first = format!("{H1} ");
let last = format!(" {H2}");
let word = [
(first.as_str(), true),
("pq", true),
(" 46", true),
(&last, true),
];
let order = format!("{D2} pq 46 {D1}");
assert_eq!(both(&word), [order.clone(), order]);
let marks = [
("pq", true),
(" ", true),
(H1, true),
("!?", true),
("uv", true),
];
let order = format!("uv?!{D1} pq");
assert_eq!(both(&marks), [order.clone(), order]);
let plain = [
(first.as_str(), true),
("pq", false),
(" 46", true),
(&last, true),
];
assert_eq!(both(&plain)[1], format!(" {D1}pq{D2} 46 "));
}
#[test]
fn parts_a_number_with_rtl_from_marks_without_it() {
let first = format!("{H1} ");
let last = format!(" {H2}");
let after = both(&[(&first, true), ("37", true), ("-/", false), (&last, true)]);
assert_eq!(
after,
[format!("{D2} -/37 {D1}"), format!("37 {D1}-/{D2} ")]
);
let before = both(&[(&first, true), ("!?", false), ("58", true), (&last, true)]);
assert_eq!(
before,
[format!("{D2} 58!? {D1}"), format!(" {D1}!?{D2} 58")]
);
}
#[test]
fn parts_a_number_with_rtl_from_a_word_or_number_without_it() {
let first = format!("{H1} ");
let last = format!(" {H2}");
let word = both(&[(&first, true), ("6", true), ("ef", false), (&last, true)]);
assert_eq!(word, [format!("{D2} ef6 {D1}"), format!("6 {D1}ef{D2} ")]);
let number = both(&[(&first, true), ("12", false), ("9", true), (&last, true)]);
assert_eq!(number, [format!("{D2} 912 {D1}"), format!(" {D1}12{D2} 9")]);
}
fn classed(text: &str, class: BidiLanguageClass) -> Line {
let mut built = line(text);
for placed in &mut built.placed {
if let Piece::Glyph(glyph) = &mut placed.piece {
glyph.direction = crate::text::RunDirection::of(true, Some(class));
}
}
built
}
fn order(text: &str, class: BidiLanguageClass) -> String {
shown(&visual(&classed(text, class), false, true).line)
}
#[test]
fn leaves_the_numeric_types_of_a_language_of_the_unicode_class_unchanged() {
let mixed = classed("(83/6%)", BidiLanguageClass::Unicode);
assert_eq!(ordering_text(&mixed.placed), "\u{200F}83/6%\u{200F}");
assert_eq!(order("47%", BidiLanguageClass::Unicode), "47%");
assert_eq!(order("47/6", BidiLanguageClass::Unicode), "47/6");
}
#[test]
fn starts_a_sequence_of_the_arabic_class_as_after_an_arabic_letter() {
let class = BidiLanguageClass::Arabic;
assert_eq!(order("38%", class), "%38");
assert_eq!(order("%38", class), "38%");
assert_eq!(order("38+5", class), "5+38");
assert_eq!(order("38.5", class), "38.5");
let plain = classed("38%", BidiLanguageClass::default());
assert_eq!(shown(&visual(&plain, true, false).line), "%38");
}
#[test]
fn lets_a_letter_before_a_number_decide_in_the_arabic_class() {
let class = BidiLanguageClass::Arabic;
assert_eq!(order("\u{05D0}\u{05D1} 38%", class), "38% \u{05D1}\u{05D0}");
assert_eq!(order("ab 38%", class), "ab 38%");
assert_eq!(order("38%", BidiLanguageClass::OtherRightToLeft), "38%");
}
#[test]
fn makes_a_slash_a_neutral_character_but_for_the_unicode_class() {
for class in [
BidiLanguageClass::Arabic,
BidiLanguageClass::OtherRightToLeft,
] {
assert_eq!(order("38/5", class), "5/38");
assert_eq!(
order("\u{05D0}\u{05D1} 38/5", class),
"5/38 \u{05D1}\u{05D0}"
);
assert_eq!(
order("\u{062F}\u{0632} 38/5", class),
"5/38 \u{0632}\u{062F}"
);
assert_eq!(order("38:5", class), "38:5");
}
}
#[test]
fn starts_a_sequence_after_a_run_without_rtl_as_after_an_arabic_letter() {
assert_eq!(both(&[("ab ", false), ("47%", true)])[1], "ab %47");
}
#[test]
fn ends_numeric_tokens_at_spaces_letters_objects_and_rtl_runs() {
let mut mixed = line("(8) x (.)\u{FFFC}[3%]");
mixed.placed[9].piece = Piece::Note(NoteNumber::of_index(0));
assert_eq!(
ordering_text(&mixed.placed),
"\u{200E}\u{200E}\u{200E}\u{200E}x\u{200E}\u{200E}\u{200E}\u{200E}\u{FFFC}\u{200E}\u{200E}\u{200E}\u{200E}"
);
if let Piece::Glyph(glyph) = &mut mixed.placed[12].piece {
glyph.direction = crate::text::RunDirection::of(true, None);
}
assert_eq!(
ordering_text(&mixed.placed),
"\u{200E}\u{200E}\u{200E}\u{200E}x\u{200E}\u{200E}\u{200E}\u{200E}\u{FFFC}\u{200E}\u{200E}\u{200F}\u{200E}"
);
}
}