f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! Classes of characters: scripts, symbols, mirrored brackets and invisible characters.

use super::FontSide;
use crate::character_class::CharacterClass;
use crate::props::EastAsianScript;
use crate::styles::EastAsianCharset;

/// Fallback Unicode bullet mapping for common private-use code points from Symbol and Wingdings
/// when a non-symbol text face lacks the private-use glyph.
pub(super) fn symbol_stand_in(ch: char) -> Option<char> {
    match ch {
        '\u{F0B7}' => Some('\u{2022}'),
        '\u{F0A7}' => Some('\u{25AA}'),
        '\u{F0A8}' => Some('\u{25A1}'),
        '\u{F0D8}' => Some('\u{27A2}'),
        '\u{F076}' => Some('\u{2756}'),
        '\u{F0FC}' => Some('\u{2713}'),
        '\u{F06F}' => Some('o'),
        '\u{F02D}' => Some('-'),
        _ => None,
    }
}

pub(super) use f_office_fonts::SymbolFont;

/// The text of a run with its paired brackets mirrored when the run reads from right to left.
pub(super) fn mirrored(text: &str, right_to_left: bool) -> std::borrow::Cow<'_, str> {
    if right_to_left && text.chars().any(|ch| mirror(ch) != ch) {
        std::borrow::Cow::Owned(text.chars().map(mirror).collect())
    } else {
        std::borrow::Cow::Borrowed(text)
    }
}

/// The mirrored form of a paired bracket in right-to-left text (Unicode `Bidi_Mirroring_Glyph`).
pub(super) fn mirror(ch: char) -> char {
    match ch {
        '(' => ')',
        ')' => '(',
        '[' => ']',
        ']' => '[',
        '{' => '}',
        '}' => '{',
        '<' => '>',
        '>' => '<',
        '\u{AB}' => '\u{BB}',
        '\u{BB}' => '\u{AB}',
        other => other,
    }
}

/// Which of a run's faces a character takes (a field of [`super::RunFaces`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FaceSlot {
    /// An ASCII character.
    Ascii,
    /// A character outside ASCII that no other slot takes.
    Other,
    /// An ASCII character at the size of small capitals.
    SmallAscii,
    /// A character outside ASCII at the size of small capitals.
    SmallOther,
    /// A complex script character, or any character of a run with complex formatting.
    Complex,
    /// An East Asian character.
    EastAsian,
}

/// The slot of the face that a character takes. With the East Asian hint, the punctuation that
/// Latin and East Asian fonts share takes the East Asian face.
pub(super) fn face_slot(
    ch: char,
    small: bool,
    (all_complex, hint): (bool, Option<HintedSet>),
) -> FaceSlot {
    if all_complex || complex_script(ch) {
        FaceSlot::Complex
    } else if takes_east_asian_face(ch, hint) {
        FaceSlot::EastAsian
    } else {
        match (ch.is_ascii(), small) {
            (true, false) => FaceSlot::Ascii,
            (false, false) => FaceSlot::Other,
            (true, true) => FaceSlot::SmallAscii,
            (false, true) => FaceSlot::SmallOther,
        }
    }
}

/// The characters besides those of East Asian scripts that a run with the East Asian hint draws
/// with its East Asian face (the variants of `HintedSlot`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HintedSet {
    /// The punctuation that Latin and East Asian fonts share ([`east_asian_shared`]).
    Punctuation,
    /// That punctuation and the symbols, Greek and Cyrillic of [`hinted_symbol`].
    Symbols,
}

/// The side that a run with the East Asian hint gives the characters of [`open_with_hint`]
/// (the variants of `HintedFontSide`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HintedLatin {
    /// They are open and keep no side.
    Open,
    /// They take the side of ECMA-376's table of the hint by the run's East Asian language and
    /// the character set of its East Asian font ([`HintLanguage::side`]).
    ByLanguage(HintLanguage),
}

/// What the table of the East Asian hint (ECMA-376 Part 1, 17.3.2.26) reads of a run for the
/// Latin letters: its East Asian language, and the character set of its East Asian font.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HintLanguage {
    /// The language part of the run's East Asian language is `zh`.
    Chinese,
    /// Another language or none, and the font table gives the run's East Asian font the
    /// character set GB 2312 or Big5.
    ChineseSet,
    /// Another language or none, and another character set or none.
    Other,
}

impl HintLanguage {
    /// What the table reads of a run whose East Asian language has the script `script` and
    /// whose East Asian font has the character set `charset` in the font table.
    pub(super) fn of(script: Option<EastAsianScript>, charset: Option<EastAsianCharset>) -> Self {
        if matches!(
            script,
            Some(EastAsianScript::Simplified | EastAsianScript::Traditional)
        ) {
            Self::Chinese
        } else if matches!(
            charset,
            Some(EastAsianCharset::Gb2312 | EastAsianCharset::Big5)
        ) {
            Self::ChineseSet
        } else {
            Self::Other
        }
    }

    /// The side of a character of [`open_with_hint`] in a run with the hint. The East Asian
    /// side: the Latin-1 characters of the table's first list; its Latin-1 letters for Chinese
    /// and Latin Extended Additional in a Chinese run; Latin Extended-A, Latin Extended-B and
    /// the IPA Extensions in a Chinese run or under a Chinese character set. The other side:
    /// the other Latin-1 characters, Greek Extended, and the letters above in the other runs.
    fn side(self, ch: char) -> FontSide {
        let east = if first_list(ch) {
            true
        } else if letter_for_chinese(ch) || ('\u{1E00}'..='\u{1EFF}').contains(&ch) {
            self == Self::Chinese
        } else if ('\u{0100}'..='\u{02AF}').contains(&ch) {
            self != Self::Other
        } else {
            false
        };
        if east {
            FontSide::EastAsian
        } else {
            FontSide::Other
        }
    }
}

/// Whether a Latin-1 character is one of the first list of ECMA-376's table of the East Asian
/// hint, which takes the East Asian font in every run with the hint.
const fn first_list(ch: char) -> bool {
    matches!(
        ch,
        '\u{00A1}'
            | '\u{00A4}'
            | '\u{00A7}'
            | '\u{00A8}'
            | '\u{00AA}'
            | '\u{00AD}'
            | '\u{00AF}'
            | '\u{00B0}'..='\u{00B4}'
            | '\u{00B6}'..='\u{00BA}'
            | '\u{00BC}'..='\u{00BF}'
            | '\u{00D7}'
            | '\u{00F7}'
    )
}

/// Whether a Latin-1 letter is one that ECMA-376's table of the East Asian hint gives the East
/// Asian font when the run's language is Chinese.
const fn letter_for_chinese(ch: char) -> bool {
    matches!(
        ch,
        '\u{00E0}'
            | '\u{00E1}'
            | '\u{00E8}'
            | '\u{00E9}'
            | '\u{00EA}'
            | '\u{00EC}'
            | '\u{00ED}'
            | '\u{00F2}'
            | '\u{00F3}'
            | '\u{00F9}'
            | '\u{00FA}'
            | '\u{00FC}'
    )
}

/// The font side of a character of a run that has complex formatting when `all_complex`, with
/// the East Asian hint when `hint` is some, and with distinct ASCII and High ANSI font slots
/// when `ascii_hansi_differ` is true: the East Asian side for a character of the class of the
/// East Asian font; without the hint, `Other` for ASCII and `HighAnsi` (when
/// `ascii_hansi_differ`) or `Other` otherwise; with the hint, `Other` for ASCII and the East
/// Asian side for the middle dot, the section sign and every character outside Latin-1 but the
/// Latin letters and Greek Extended. A space is `Other` when `ascii_hansi_differ` (so transitions
/// between High ANSI and ASCII spaces start a text object) and `Open` otherwise. A complex script
/// character is `Open`. With the hint, the other characters of Latin-1, the Latin letters outside
/// it and Greek Extended ([`open_with_hint`]) take the side that `hint` gives them (with
/// non-East-Asian characters taking `HighAnsi` when `ascii_hansi_differ`), and stay open where
/// `has_glyph` says that the face of that side has no glyph for them: Word then draws them in
/// another face.
pub(super) fn font_side(
    ch: char,
    all_complex: bool,
    hint: Option<HintedLatin>,
    ascii_hansi_differ: bool,
    has_glyph: impl FnOnce(FontSide) -> bool,
) -> FontSide {
    if all_complex || complex_script(ch) {
        return FontSide::Open;
    }
    if ch == ' ' {
        return if ascii_hansi_differ {
            FontSide::Other
        } else {
            FontSide::Open
        };
    }
    if CharacterClass::EastAsianFont.contains(ch) {
        return FontSide::EastAsian;
    }
    let non_ascii = if ascii_hansi_differ {
        FontSide::HighAnsi
    } else {
        FontSide::Other
    };
    let Some(hint) = hint else {
        return if ch.is_ascii() {
            FontSide::Other
        } else {
            non_ascii
        };
    };
    hinted_font_side(ch, hint, non_ascii, has_glyph)
}

/// The font side of a non-space, non-complex, non-East-Asian character in a run with the East
/// Asian hint, where `non_ascii` is the side taken by characters assigned to the High ANSI slot.
fn hinted_font_side(
    ch: char,
    hint: HintedLatin,
    non_ascii: FontSide,
    has_glyph: impl FnOnce(FontSide) -> bool,
) -> FontSide {
    if ch.is_ascii() {
        FontSide::Other
    } else if matches!(ch, '\u{00A7}' | '\u{00B7}') {
        FontSide::EastAsian
    } else if open_with_hint(ch) {
        match hint {
            HintedLatin::Open => FontSide::Open,
            HintedLatin::ByLanguage(language) => {
                let side = match language.side(ch) {
                    FontSide::Other => non_ascii,
                    other => other,
                };
                if has_glyph(side) {
                    side
                } else {
                    FontSide::Open
                }
            }
        }
    } else {
        FontSide::EastAsian
    }
}

/// Whether a character outside ASCII is one whose font side under the East Asian hint depends
/// on the run: a character of Latin-1 but the section sign and the middle dot, a Latin letter
/// of Latin Extended-A and -B, the IPA Extensions or Latin Extended Additional, or a character
/// of Greek Extended. ECMA-376 Part 1, 17.3.2.26, gives the East Asian font under the hint to
/// some of the Latin-1 characters, and to the Latin letters when the run's East Asian language
/// is Chinese or, for some blocks, when the East Asian font's character set is GB 2312 or Big5;
/// it keeps Greek Extended in the High ANSI font ([`HintLanguage::side`]).
const fn open_with_hint(ch: char) -> bool {
    matches!(
        ch,
        '\u{0080}'..='\u{02AF}' | '\u{1E00}'..='\u{1EFF}' | '\u{1F00}'..='\u{1FFF}'
    )
}

/// Whether the character at `index` of a run's text belongs to a number: a digit 0 to 9, or
/// a full stop, comma or colon between two digits.
pub(super) fn numeric_at(chars: &[char], index: usize) -> bool {
    let digit = |at: Option<usize>| {
        at.and_then(|at| chars.get(at))
            .is_some_and(char::is_ascii_digit)
    };
    match chars.get(index) {
        Some(ch) if ch.is_ascii_digit() => true,
        Some('.' | ',' | ':') => digit(index.checked_sub(1)) && digit(index.checked_add(1)),
        _ => false,
    }
}

/// Whether a character takes the East Asian face: a character of the class of the East Asian
/// font, and also a character of the set `hint` that a run's East Asian hint moves. It is the one check of both questions: whether a run gets an East Asian face, which
/// one character of its text that takes it decides, and whether a character is drawn with it,
/// unless it belongs to a complex script ([`face_slot`]). So no character asks for an East
/// Asian face that its run did not get.
pub(super) fn takes_east_asian_face(ch: char, hint: Option<HintedSet>) -> bool {
    CharacterClass::EastAsianFont.contains(ch)
        || match hint {
            None => false,
            Some(HintedSet::Punctuation) => east_asian_shared(ch),
            Some(HintedSet::Symbols) => east_asian_shared(ch) || hinted_symbol(ch),
        }
}

/// Whether a character is punctuation that Latin and East Asian fonts share, which a run with
/// `w:rFonts w:hint="eastAsia"` draws with its East Asian font: the middle dot, and the
/// dashes, quotes, bullets, ellipsis, primes and reference marks of General Punctuation, but
/// not its spaces, separators and format characters. Spaces keep the Latin font.
fn east_asian_shared(ch: char) -> bool {
    matches!(ch, '\u{00B7}' | '\u{2010}'..='\u{2027}' | '\u{2030}'..='\u{205E}')
}

/// Whether a character is a symbol, a Greek or a Cyrillic letter that a run with the East Asian
/// hint draws with its East Asian font where the target moves them: the spacing modifier
/// letters, Greek and Cyrillic, and every character from the superscripts to the dingbats, but
/// not the combining marks.
fn hinted_symbol(ch: char) -> bool {
    matches!(ch, '\u{02B0}'..='\u{02FF}' | '\u{0370}'..='\u{04FF}' | '\u{2070}'..='\u{27BF}')
}

/// Whether a character belongs to a complex script, which takes the complex script font:
/// Hebrew, Arabic and the scripts near them, the scripts of India, and Thai.
pub(super) fn complex_script(ch: char) -> bool {
    matches!(
        ch,
        '\u{0590}'..='\u{08FF}'
            | '\u{0900}'..='\u{0DFF}'
            | '\u{0E00}'..='\u{0E7F}'
            | '\u{FB1D}'..='\u{FDFF}'
            | '\u{FE70}'..='\u{FEFF}'
    )
}

/// The kinds of the characters that F-Office takes as invisible, which the target's
/// `InvisibleCharacters` treats apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InvisibleKind {
    /// The zero width space, joiners and marks, the bidirectional controls and the byte order
    /// mark: U+200B to U+200F, U+202A to U+202E and U+FEFF.
    Format,
    /// The word joiner and the invisible operators: U+2060 to U+2064.
    Operator,
    /// The variation selectors: U+FE00 to U+FE0F.
    Selector,
}

/// The kind of an invisible character, or `None` for any other character.
pub(crate) const fn invisible_kind(ch: char) -> Option<InvisibleKind> {
    match ch {
        '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{FEFF}' => {
            Some(InvisibleKind::Format)
        }
        '\u{2060}'..='\u{2064}' => Some(InvisibleKind::Operator),
        '\u{FE00}'..='\u{FE0F}' => Some(InvisibleKind::Selector),
        _ => None,
    }
}

pub(super) fn upper(ch: char, caps: bool) -> Vec<char> {
    if caps {
        ch.to_uppercase().collect()
    } else {
        vec![ch]
    }
}