Skip to content

Truly independent web browser

65.8 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

use super::*;

use std::borrow::Cow;

use libgfx_rust::font::{EmojiPresentation, FontHandle, FrozenFontList, emoji_presentation_for_code_point};

#[derive(Clone, Copy)]
#[repr(u8)]
enum LineBreakMode {
    Strict,
    Normal,
    Loose,
    LooseJapanese,
    LooseChinese,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LineBreakLanguage {
    Other,
    Japanese,
    Chinese,
}

impl LineBreakLanguage {
    pub(crate) fn from_tag(tag: &[u16]) -> Self {
        let is_alpha = |subtag: &[u16]| {
            subtag
                .iter()
                .all(|&unit| u8::try_from(unit).is_ok_and(|unit| unit.is_ascii_alphabetic()))
        };
        let matches = |subtag: &[u16], expected: &[u8]| {
            subtag.len() == expected.len()
                && subtag
                    .iter()
                    .zip(expected)
                    .all(|(&unit, &expected)| (unit | 0x20) == u16::from(expected))
        };
        let mut subtags = tag.split(|&unit| unit == u16::from(b'-'));
        let primary = subtags.next().unwrap_or_default();
        if !(2..=8).contains(&primary.len()) || !is_alpha(primary) {
            return Self::Other;
        }
        let mut candidate = subtags.next();
        // BCP47 permits up to three extlang subtags, only after a two- or three-letter primary language.
        if primary.len() <= 3 {
            for _ in 0..3 {
                if !candidate.is_some_and(|subtag| subtag.len() == 3 && is_alpha(subtag)) {
                    break;
                }
                candidate = subtags.next();
            }
        }
        // https://drafts.csswg.org/css-text-4/#script-tagging
        // Only this position can name a script. Region, variant, extension and private-use subtags cannot override it.
        if let Some(script) = candidate.filter(|subtag| subtag.len() == 4 && is_alpha(subtag)) {
            if [b"hant", b"hans", b"hani", b"hanb", b"bopo"]
                .iter()
                .any(|name| matches(script, *name))
            {
                return Self::Chinese;
            }
            if [b"jpan", b"hrkt", b"hira", b"kana"]
                .iter()
                .any(|name| matches(script, *name))
            {
                return Self::Japanese;
            }
            return Self::Other;
        }
        if matches(primary, b"ja") {
            Self::Japanese
        } else if matches(primary, b"zh") {
            Self::Chinese
        } else {
            Self::Other
        }
    }
}

#[cfg(test)]
mod language_tests {
    use super::LineBreakLanguage::{self, Chinese, Japanese, Other};

    #[test]
    fn explicit_script_overrides_line_break_language() {
        for (tag, expected) in [
            ("ko-Hani", Chinese),
            ("ja-Latn", Other),
            ("zh-Latn", Other),
            ("ja-Hans", Chinese),
            ("zh-Hira", Japanese),
            ("en-Jpan", Japanese),
            ("en-Hant", Chinese),
            ("en-Hans", Chinese),
            ("en-Hani", Chinese),
            ("en-Hanb", Chinese),
            ("en-Bopo", Chinese),
            ("en-Hrkt", Japanese),
            ("en-Hira", Japanese),
            ("en-Kana", Japanese),
            ("ja-Hang", Other),
            ("ja-Kore", Other),
            ("zh-Jamo", Other),
            ("zh-Zzzz", Other),
            ("JA-hAnS", Chinese),
            ("zh-cmn-Jpan", Japanese),
            ("ja-abc-def-ghi-Hans", Chinese),
            ("yue-Hant", Chinese),
        ] {
            let units: Vec<_> = tag.encode_utf16().collect();
            assert!(LineBreakLanguage::from_tag(&units) == expected, "{tag}");
        }
    }

    #[test]
    fn only_the_script_position_changes_line_break_language() {
        for (tag, expected) in [
            ("ja", Japanese),
            ("ja-JP", Japanese),
            ("JA-jp", Japanese),
            ("zh", Chinese),
            ("zh-Hant-TW", Chinese),
            ("ja-x-Latn", Japanese),
            ("ja-u-ca-hans", Japanese),
            ("ja-JP-Latn", Japanese),
            ("ja-1996-Latn", Japanese),
            ("ja-fonipa-Latn", Japanese),
            ("en-x-Jpan", Other),
            ("en-u-ca-jpan", Other),
            ("abcd-xyz-Jpan", Other),
            ("x-Jpan", Other),
            ("jあ-Jpan", Other),
            ("japanesee-Jpan", Other),
            ("", Other),
        ] {
            let units: Vec<_> = tag.encode_utf16().collect();
            assert!(LineBreakLanguage::from_tag(&units) == expected, "{tag}");
        }
    }
}

unsafe extern "C" {
    fn unicode_layout_grapheme_segmenter_create(text: *const u16, length_in_code_units: usize) -> *mut c_void;
    fn unicode_layout_line_segmenter_create(
        text: *const u16,
        length_in_code_units: usize,
        mode: LineBreakMode,
    ) -> *mut c_void;
    fn unicode_layout_segmenter_next_boundary(handle: *mut c_void, index: usize, inclusive: bool) -> i64;
    fn unicode_layout_segmenter_destroy(handle: *mut c_void);
    fn unicode_layout_word_boundaries(
        text: *const u16,
        length: usize,
        offset: usize,
        start: *mut usize,
        end: *mut usize,
    );
    safe fn unicode_layout_bidirectional_class(code_point: u32) -> u8;
    safe fn unicode_layout_line_break_class(code_point: u32) -> u8;
    safe fn unicode_layout_joining_type(code_point: u32) -> u8;
    safe fn unicode_layout_code_point_has_emoji_property(code_point: u32) -> bool;
    safe fn unicode_layout_vertical_orientation(code_point: u32) -> u8;
}

// LibUnicode's LineBreakClass, in declaration order.
mod line_break_class {
    pub(super) const ALPHABETIC: u8 = 0;
    pub(super) const NUMERIC: u8 = 1;
    pub(super) const IDEOGRAPHIC: u8 = 2;
    pub(super) const AMBIGUOUS: u8 = 3;
    pub(super) const COMPLEX_CONTEXT: u8 = 4;
    pub(super) const COMBINING_MARK: u8 = 5;
    pub(super) const CONDITIONAL_JAPANESE_STARTER: u8 = 6;
    pub(super) const HANGUL_JAMO: u8 = 7;
    pub(super) const OPEN_PUNCTUATION: u8 = 8;
    pub(super) const CLOSE_PUNCTUATION: u8 = 9;
    pub(super) const BREAK_SYMBOLS: u8 = 10;
    pub(super) const INFIX_NUMERIC_SEPARATOR: u8 = 11;
    pub(super) const PREFIX_NUMERIC: u8 = 12;
    pub(super) const POSTFIX_NUMERIC: u8 = 13;
    pub(super) const HYPHEN: u8 = 14;
    pub(super) const GLUE: u8 = 15;
    pub(super) const WORD_JOINER: u8 = 16;
    pub(super) const ZERO_WIDTH_JOINER: u8 = 17;
    pub(super) const OTHER: u8 = 18;
}

fn line_break_class(code_point: u32) -> u8 {
    unicode_layout_line_break_class(code_point)
}

pub(crate) const SOFT_HYPHEN: u16 = 0xad;

/// Whether a line that breaks right after `text[..end]` breaks at a soft hyphen there, and so ends in a hyphen: The
/// text has to end in a soft hyphen that no whitespace follows, since the line breaks at that whitespace instead.
pub(crate) fn breaks_at_soft_hyphen(text: &[u16], end: usize) -> bool {
    end > 0
        && text[end - 1] == SOFT_HYPHEN
        && text
            .get(end)
            .is_none_or(|&code_unit| !(code_unit < 0x80 && code_point_is_ascii_space(u32::from(code_unit))))
}

// LibUnicode's JoiningType, in declaration order.
mod joining_type {
    pub(super) const NON_JOINING: u8 = 0;
    pub(super) const TRANSPARENT: u8 = 1;
    pub(super) const DUAL_JOINING: u8 = 2;
    pub(super) const JOIN_CAUSING: u8 = 3;
    pub(super) const LEFT_JOINING: u8 = 4;
    pub(super) const RIGHT_JOINING: u8 = 5;
}

fn joining_type(code_point: u32) -> u8 {
    // OPTIMIZATION: Below U+0300, only U+00AD SOFT HYPHEN takes part in joining, as a transparent character.
    if code_point < 0x300 && code_point != 0xad {
        return joining_type::NON_JOINING;
    }
    unicode_layout_joining_type(code_point)
}

/// The joining type of the first character in `text[start..end]` that is not transparent to joining, such as most marks
/// are, which shaping looks past for the letter that a letter joins.
fn first_joining_type_in(text: &[u16], start: usize, end: usize) -> u8 {
    let mut index = start;
    while index < end {
        let code_point = code_point_at(text, index);
        let joining_type = joining_type(code_point);
        if joining_type != joining_type::TRANSPARENT {
            return joining_type;
        }
        index += code_unit_length_for_code_point(code_point);
    }
    joining_type::NON_JOINING
}

/// Like `first_joining_type_in()`, for the last such character.
fn last_joining_type_in(text: &[u16], start: usize, end: usize) -> u8 {
    let mut index = end;
    while index > start {
        let joining_type = joining_type(previous_code_point_at(text, &mut index));
        if joining_type != joining_type::TRANSPARENT {
            return joining_type;
        }
    }
    joining_type::NON_JOINING
}

/// Whether the letters at the edges of `range` join the letters of `text` around it, so that shaping the range on its
/// own gives them the forms they take in the whole text.
pub(crate) fn joining_context(text: &[u16], range: std::ops::Range<usize>) -> libgfx_rust::text_layout::JoiningContext {
    use joining_type::*;
    if range.is_empty() {
        return Default::default();
    }
    let joins_following = |joining_type| matches!(joining_type, DUAL_JOINING | JOIN_CAUSING | LEFT_JOINING);
    let joins_preceding = |joining_type| matches!(joining_type, DUAL_JOINING | JOIN_CAUSING | RIGHT_JOINING);
    libgfx_rust::text_layout::JoiningContext {
        joins_before: joins_preceding(first_joining_type_in(text, range.start, range.end))
            && joins_following(last_joining_type_in(text, 0, range.start)),
        joins_after: joins_following(last_joining_type_in(text, range.start, range.end))
            && joins_preceding(first_joining_type_in(text, range.end, text.len())),
    }
}

// Classifies a code point for direction-run splitting: strong LTR/RTL, direction-neutral Common, or ContextDependent
// (resolved from surrounding runs).
fn text_type_for_code_point(code_point: u32) -> u8 {
    use line_box_fragment::{
        GLYPH_TEXT_TYPE_COMMON as C, GLYPH_TEXT_TYPE_CONTEXT_DEPENDENT as X, GLYPH_TEXT_TYPE_LTR as L,
        GLYPH_TEXT_TYPE_RTL as R,
    };

    // Each ASCII character has a statically known bidi class.
    #[rustfmt::skip]
    const ASCII_TEXT_TYPES: [u8; 128] = [
        // 0x00-0x0F: Control characters (BN=Common, S/B/WS=ContextDependent)
        C, C, C, C, C, C, C, C, C, X, X, X, X, X, C, C,
        // 0x10-0x1F: Control characters
        C, C, C, C, C, C, C, C, C, C, C, C, X, X, X, X,
        // 0x20-0x2F: Space and punctuation
        X, C, C, X, X, X, C, C, C, C, C, X, X, X, X, X,
        // 0x30-0x3F: Digits and punctuation
        X, X, X, X, X, X, X, X, X, X, X, C, C, C, C, C,
        // 0x40-0x4F: @ and uppercase letters
        C, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
        // 0x50-0x5F: Uppercase letters and punctuation
        L, L, L, L, L, L, L, L, L, L, L, C, C, C, C, C,
        // 0x60-0x6F: ` and lowercase letters
        C, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
        // 0x70-0x7F: Lowercase letters and punctuation
        L, L, L, L, L, L, L, L, L, L, L, C, C, C, C, C,
    ];
    if let Some(&text_type) = ASCII_TEXT_TYPES.get(code_point as usize) {
        return text_type;
    }

    match unicode_layout_bidirectional_class(code_point) {
        // LibUnicode's BidiClass, in declaration order: AN, B, CS, NSM, EN, ES, ET, S, WS.
        0 | 1 | 3..=7 | 21 | 22 => X,
        // BN, FSI, ON, PDF, PDI.
        2 | 8 | 13..=15 => C,
        // L, LRE, LRI, LRO.
        9..=12 => L,
        // R, AL, RLE, RLI, RLO.
        16..=20 => R,
        _ => unreachable!("invalid bidi class"),
    }
}

// Stand-ins for the Unicode library's segmenters and the host's code point facts, which a unit test links through a
// document's render state but never reaches.
#[cfg(test)]
mod unicode_test_stubs {
    use std::ffi::c_void;

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_grapheme_segmenter_create(
        _text: *const u16,
        _length_in_code_units: usize,
    ) -> *mut c_void {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_line_segmenter_create(
        _text: *const u16,
        _length_in_code_units: usize,
        _mode: super::LineBreakMode,
    ) -> *mut c_void {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_segmenter_next_boundary(_handle: *mut c_void, _index: usize, _inclusive: bool) -> i64 {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_word_boundaries(
        _text: *const u16,
        _length: usize,
        _offset: usize,
        _start: *mut usize,
        _end: *mut usize,
    ) {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn ladybird_layout_code_point_category_facts(
        code_point: u32,
    ) -> crate::layout::tree_builder::FfiCodePointCategoryFacts {
        let code_point = u8::try_from(code_point).expect("unit tests only match ASCII first-letter text");
        assert!(code_point.is_ascii_alphanumeric() || code_point.is_ascii_whitespace());
        crate::layout::tree_builder::FfiCodePointCategoryFacts {
            is_space_separator: code_point == b' ',
            is_punctuation: false,
            is_letter: code_point.is_ascii_alphabetic(),
            is_number: code_point.is_ascii_digit(),
            is_symbol: false,
            is_open_punctuation: false,
            is_dash_punctuation: false,
        }
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_bidirectional_class(_code_point: u32) -> u8 {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_line_break_class(_code_point: u32) -> u8 {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_joining_type(_code_point: u32) -> u8 {
        unreachable!("no unit test shapes text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_code_point_has_emoji_property(_code_point: u32) -> bool {
        unreachable!("no unit test segments text");
    }

    #[unsafe(no_mangle)]
    extern "C" fn unicode_layout_vertical_orientation(_code_point: u32) -> u8 {
        unreachable!("no unit test sets text vertically");
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TextChunk {
    pub start: usize,
    pub length: usize,
    /// Which of the fonts of its [`ChunkedText`] the chunk is set in.
    pub font_index: u16,
    pub has_breaking_newline: bool,
    pub has_breaking_tab: bool,
    pub is_all_whitespace: bool,
    pub can_break_after: bool,
    pub text_type: u8,
}

pub(crate) struct TextChunkInputs<'text> {
    pub text: &'text [u16],
    pub frozen_font_list: &'text FrozenFontList,
    pub white_space_collapse: u8,
    pub word_break: u8,
    pub line_break: u8,
    pub line_break_language: LineBreakLanguage,
    /// Whether a soft hyphen (U+00AD) gives a soft wrap opportunity after it, which it does unless hyphens is none.
    pub breaks_after_soft_hyphen: bool,
    pub font_variant_emoji: u8,
    pub should_wrap_lines: bool,
    pub should_respect_linebreaks: bool,
    pub unidirectional_ltr: bool,
    /// Whether the text is vertical text in mixed orientation, where some characters are typeset upright and others
    /// sideways.
    pub splits_at_orientation_changes: bool,
}

impl TextChunk {
    /// The font index of a chunk made outside any chunked text, whose font its maker keeps beside it.
    pub(crate) const FONT_INDEX_OUTSIDE_ANY_CHUNKED_TEXT: u16 = u16::MAX;
}

/// The chunks of a text, and the fonts they are set in, each once.
#[derive(Default)]
pub(crate) struct ChunkedText {
    pub(crate) chunks: Vec<TextChunk>,
    pub(crate) fonts: Box<[FontHandle]>,
    /// The frozen cascade the chunks were made against, which a memo of the chunks looks up by its address.
    #[expect(dead_code, reason = "held so that no other cascade takes the address")]
    pub(crate) frozen_font_list_held_for_memo_key: Option<std::sync::Arc<FrozenFontList>>,
}

impl ChunkedText {
    pub(crate) fn font_of(&self, chunk: &TextChunk) -> &FontHandle {
        &self.fonts[usize::from(chunk.font_index)]
    }
}

impl std::ops::Deref for ChunkedText {
    type Target = [TextChunk];

    fn deref(&self) -> &Self::Target {
        &self.chunks
    }
}

pub(crate) fn chunk_text(inputs: TextChunkInputs<'_>) -> ChunkedText {
    let mut chunker = TextChunker::new(inputs);
    let mut chunks = Vec::new();
    while let Some(chunk) = chunker.next_chunk() {
        chunks.push(chunk);
    }
    ChunkedText {
        chunks,
        fonts: chunker.fonts.into_boxed_slice(),
        frozen_font_list_held_for_memo_key: None,
    }
}

pub(super) fn word_boundaries(text: &[u16], offset: usize) -> std::ops::Range<usize> {
    let mut start = 0;
    let mut end = text.len();
    // SAFETY: The Unicode service borrows the buffer only for this call and
    // writes its boundaries into the two live output slots.
    unsafe { unicode_layout_word_boundaries(text.as_ptr(), text.len(), offset, &raw mut start, &raw mut end) };
    start..end
}

pub(crate) struct IcuSegmenterHandle {
    raw: *mut c_void,
}

// SAFETY: The handle owns its segmenter, which shares nothing with another, so the thread that holds the handle may
// change.
unsafe impl Send for IcuSegmenterHandle {}

impl IcuSegmenterHandle {
    fn next_boundary(&self, index: usize, inclusive: bool) -> Option<usize> {
        // SAFETY: The handle is live until drop, and the text it references
        // outlives it per the segmenter constructor contracts below.
        let boundary = unsafe { unicode_layout_segmenter_next_boundary(self.raw, index, inclusive) };
        (boundary >= 0).then_some(boundary as usize)
    }
}

impl Drop for IcuSegmenterHandle {
    fn drop(&mut self) {
        // SAFETY: The handle was created by a unicode_layout_*_segmenter_create
        // call and is destroyed exactly once.
        unsafe { unicode_layout_segmenter_destroy(self.raw) };
    }
}

pub(crate) enum GraphemeSegmenter {
    SingleCodeUnits {
        length_in_code_units: usize,
    },
    /// Text of code points below U+0300 only, where every code unit is a grapheme cluster except for CR LF.
    Latin {
        length_in_code_units: usize,
        /// Where each LF that follows a CR is, in increasing order.
        line_feeds_after_carriage_returns: Box<[usize]>,
    },
    Icu {
        handle: IcuSegmenterHandle,
        length_in_code_units: usize,
        /// One bit per code unit: whether it is a code point below U+0300 other than CR.
        latin_code_units: Box<[u64]>,
    },
}

// No code point below U+0300 extends or joins a grapheme cluster, and only CR joins the code point after it (CR LF).
fn is_latin_code_unit_outside_clusters(code_unit: u16) -> bool {
    code_unit < 0x300 && code_unit != 0x0d
}

impl GraphemeSegmenter {
    pub(crate) fn new(text: &[u16]) -> Self {
        let Some(first_cluster_candidate) = text.iter().position(|&unit| !is_latin_code_unit_outside_clusters(unit))
        else {
            return Self::SingleCodeUnits {
                length_in_code_units: text.len(),
            };
        };
        if text[first_cluster_candidate..].iter().all(|unit| *unit < 0x300) {
            let line_feeds_after_carriage_returns = text
                .windows(2)
                .enumerate()
                .filter(|(_, pair)| *pair == [0x0d, 0x0a])
                .map(|(index, _)| index + 1)
                .collect();
            return Self::Latin {
                length_in_code_units: text.len(),
                line_feeds_after_carriage_returns,
            };
        }
        let mut latin_code_units = vec![0u64; text.len().div_ceil(64)].into_boxed_slice();
        for (index, code_unit) in text.iter().enumerate() {
            if is_latin_code_unit_outside_clusters(*code_unit) {
                latin_code_units[index / 64] |= 1 << (index % 64);
            }
        }
        // SAFETY: The chunker borrows the text for its whole lifetime and the
        // segmenter handle is dropped with the chunker, so the ICU segmenter
        // never outlives the buffer it references.
        let raw = unsafe { unicode_layout_grapheme_segmenter_create(text.as_ptr(), text.len()) };
        Self::Icu {
            handle: IcuSegmenterHandle { raw },
            length_in_code_units: text.len(),
            latin_code_units,
        }
    }

    pub(crate) fn next_boundary(&self, index: usize, inclusive: bool) -> Option<usize> {
        match self {
            Self::SingleCodeUnits { length_in_code_units } => {
                if inclusive && index <= *length_in_code_units {
                    return Some(index);
                }
                if index >= *length_in_code_units {
                    return None;
                }
                Some(index + 1)
            }
            Self::Latin {
                length_in_code_units,
                line_feeds_after_carriage_returns,
            } => {
                let is_boundary = |index: usize| line_feeds_after_carriage_returns.binary_search(&index).is_err();
                if inclusive && index <= *length_in_code_units && is_boundary(index) {
                    return Some(index);
                }
                if index >= *length_in_code_units {
                    return None;
                }
                (index + 1..=*length_in_code_units).find(|&boundary| is_boundary(boundary))
            }
            Self::Icu {
                handle,
                length_in_code_units,
                latin_code_units,
            } => {
                // OPTIMIZATION: Two code points below U+0300 have a grapheme cluster boundary between them, unless the
                //               first one is CR. So do such a code point and the end of the text.
                let is_latin = |index: usize| latin_code_units[index / 64] & (1 << (index % 64)) != 0;
                let length = *length_in_code_units;
                let boundary = if inclusive {
                    (index > 0 && index < length && is_latin(index - 1) && is_latin(index)).then_some(index)
                } else {
                    (index < length && is_latin(index) && (index + 1 == length || is_latin(index + 1)))
                        .then_some(index + 1)
                };
                if boundary.is_some() {
                    debug_assert_eq!(boundary, handle.next_boundary(index, inclusive));
                    return boundary;
                }
                handle.next_boundary(index, inclusive)
            }
        }
    }
}

struct LineSegmenter<'text> {
    text: &'text [u16],
    mode: LineBreakMode,
    text_is_broken_with_ascii_rules: std::cell::OnceCell<bool>,
    handle: std::cell::OnceCell<IcuSegmenterHandle>,
    /// Where the last search for a boundary started, and the boundary it found, so that no boundary lies before it.
    last_search: std::cell::Cell<Option<(usize, usize)>>,
}

impl<'text> LineSegmenter<'text> {
    fn new(text: &'text [u16], line_break: u8, language: LineBreakLanguage) -> Self {
        let mode = match (line_break, language) {
            (line_break::LOOSE, LineBreakLanguage::Japanese) => LineBreakMode::LooseJapanese,
            (line_break::LOOSE, LineBreakLanguage::Chinese) => LineBreakMode::LooseChinese,
            (line_break::LOOSE, LineBreakLanguage::Other) => LineBreakMode::Loose,
            (line_break::NORMAL, _) => LineBreakMode::Normal,
            _ => LineBreakMode::Strict,
        };
        Self {
            text,
            mode,
            text_is_broken_with_ascii_rules: std::cell::OnceCell::new(),
            handle: std::cell::OnceCell::new(),
            last_search: std::cell::Cell::new(None),
        }
    }

    fn handle(&self) -> &IcuSegmenterHandle {
        self.handle.get_or_init(|| {
            // SAFETY: See GraphemeSegmenter::new; the same lifetime contract holds,
            // and the C++ side picks the ASCII line-breaking fast path internally.
            let raw = unsafe { unicode_layout_line_segmenter_create(self.text.as_ptr(), self.text.len(), self.mode) };
            IcuSegmenterHandle { raw }
        })
    }

    fn is_boundary(&self, index: usize) -> bool {
        let text_is_broken_with_ascii_rules = *self.text_is_broken_with_ascii_rules.get_or_init(|| {
            self.text
                .iter()
                .all(|&code_unit| matches!(code_unit, 0x09..=0x0d | 0x20..=0x7e))
        });
        if text_is_broken_with_ascii_rules
            && let Some(is_boundary) = ascii_line_break_at_whitespace_or_text_edge(self.text, index)
        {
            debug_assert_eq!(is_boundary, self.handle().next_boundary(index, true) == Some(index));
            return is_boundary;
        }
        self.next_boundary(index, true) == Some(index)
    }

    fn next_boundary(&self, index: usize, inclusive: bool) -> Option<usize> {
        // NB: The segmenter moves a search that starts inside a surrogate pair to the start of the pair, which can
        //     find a boundary before where the search started.
        let starts_inside_surrogate_pair = index > 0
            && index < self.text.len()
            && is_utf16_low_surrogate(self.text[index])
            && is_utf16_high_surrogate(self.text[index - 1]);
        if starts_inside_surrogate_pair {
            return self.handle().next_boundary(index, inclusive);
        }
        // OPTIMIZATION: The chunker asks about every position from the start of the text to its end. A search finds
        //               the first boundary at or after where it starts, so the boundary the last search found answers
        //               every search that starts between the two.
        let search_start = if inclusive { index } else { index + 1 };
        if let Some((last_search_start, boundary)) = self.last_search.get()
            && (last_search_start..=boundary).contains(&search_start)
        {
            return Some(boundary);
        }
        let boundary = self.handle().next_boundary(index, inclusive)?;
        self.last_search.set(Some((search_start, boundary)));
        Some(boundary)
    }
}

fn is_utf16_high_surrogate(code_unit: u16) -> bool {
    (0xd800..=0xdbff).contains(&code_unit)
}

fn is_utf16_low_surrogate(code_unit: u16) -> bool {
    (0xdc00..=0xdfff).contains(&code_unit)
}

/// Whether a code point is typeset upright in vertical text whose text orientation is 'mixed'.
// https://drafts.csswg.org/css-writing-modes-4/#vertical-orientations
// "When text-orientation is mixed, the UA must determine the orientation of each typographic character unit by its
//  Vertical_Orientation property: typesetting it upright if its orientation property is U, Tu, or Tr; or typesetting
//  it sideways (90° clockwise from horizontal) if its orientation property is R."
pub(crate) fn code_point_is_upright_in_mixed_orientation(code_point: u32) -> bool {
    // LibUnicode's VerticalOrientation, in declaration order: Rotated comes first.
    const ROTATED: u8 = 0;
    unicode_layout_vertical_orientation(code_point) != ROTATED
}

/// Mirrors AK::Utf16View::code_point_at, including its lone-surrogate
/// pass-through behavior.
pub(crate) fn code_point_at(text: &[u16], index: usize) -> u32 {
    let code_unit = text[index];
    let code_point = u32::from(code_unit);
    if !is_utf16_high_surrogate(code_unit) && !is_utf16_low_surrogate(code_unit) {
        return code_point;
    }
    if is_utf16_low_surrogate(code_unit) || index + 1 == text.len() {
        return code_point;
    }
    let second = text[index + 1];
    if !is_utf16_low_surrogate(second) {
        return code_point;
    }
    0x10000 + ((code_point - 0xd800) << 10) + (u32::from(second) - 0xdc00)
}

/// Mirrors AK::Utf16View::previous_code_point_at: steps `index` back over one
/// code point (surrogate-pair aware) and decodes it.
fn previous_code_point_at(text: &[u16], index: &mut usize) -> u32 {
    assert!(*index > 0 && *index <= text.len());
    *index -= 1;
    if *index > 0 && is_utf16_low_surrogate(text[*index]) && is_utf16_high_surrogate(text[*index - 1]) {
        *index -= 1;
    }
    code_point_at(text, *index)
}

pub(super) fn code_unit_length_for_code_point(code_point: u32) -> usize {
    if code_point >= 0x10000 { 2 } else { 1 }
}

fn code_point_is_ascii_space(code_point: u32) -> bool {
    matches!(code_point, 0x09..=0x0d | 0x20)
}

fn is_interword_space(code_point: u32) -> bool {
    code_point == 0x0020 || code_point == 0x00a0
}

// INTEROP: Use browser-compatible line-breaking rules for printable ASCII. Unicode line breaking alone permits
//          additional breaks within punctuation sequences, which also prevents contextual shaping when those
//          sequences are split into separate chunks.
fn ascii_line_break_at(text: &[u16], index: usize) -> Option<bool> {
    if index == 0 || index >= text.len() {
        return None;
    }
    let before = text[index - 1];
    let after = text[index];
    if !(0x21..=0x7f).contains(&before) || !(0x21..=0x7f).contains(&after) {
        return None;
    }

    let before = before as u8;
    let after = after as u8;
    if before == b'-' && after.is_ascii_digit() {
        return Some(index > 1 && text[index - 2] <= 0x7f && (text[index - 2] as u8).is_ascii_alphanumeric());
    }
    if before.is_ascii_alphanumeric()
        || matches!(
            before,
            b'$' | b'\'' | b'(' | b'/' | b'<' | b'@' | b'[' | b'^'..=b'`' | b'{' | 0x7f
        )
        || matches!(
            after,
            b'!' | b')' | b',' | b'.' | b'/' | b':' | b';' | b'?' | b']' | b'}'
        )
        || (before == b'?' && matches!(after, b'"' | b'\''))
        || (before == b'-' && after == b'$')
    {
        return Some(false);
    }
    Some(matches!(after, b'(' | b'<' | b'[' | b'{') || matches!(before, b'-' | b'?'))
}

/// Mirrors LibUnicode's compute_ascii_line_boundaries() at the edges of a text of printable ASCII and ASCII whitespace,
/// and next to its whitespace.
fn ascii_line_break_at_whitespace_or_text_edge(text: &[u16], index: usize) -> Option<bool> {
    if index == 0 || index == text.len() {
        return Some(true);
    }
    let (Some(&before), Some(&after)) = (text.get(index - 1), text.get(index)) else {
        return None;
    };
    let (Ok(before), Ok(after)) = (u8::try_from(before), u8::try_from(after)) else {
        return None;
    };
    let is_ascii_space = |code_unit: u8| matches!(code_unit, b'\t'..=b'\r' | b' ');
    if !is_ascii_space(before) && !is_ascii_space(after) {
        return None;
    }

    let is_mandatory_break = |code_unit: u8| matches!(code_unit, b'\n'..=b'\r');
    if before == b'\r' && after == b'\n' {
        return Some(false);
    }
    if is_mandatory_break(before) {
        return Some(true);
    }
    if is_mandatory_break(after) || after == b' ' {
        return Some(false);
    }
    let last_non_space_before = text[..index]
        .iter()
        .rev()
        .find(|&&code_unit| code_unit != u16::from(b' '));
    if last_non_space_before.is_some_and(|&code_unit| matches!(u8::try_from(code_unit), Ok(b'(' | b'[' | b'{'))) {
        return Some(false);
    }
    if matches!(after, b')' | b']' | b'}' | b'!' | b'?' | b'/') {
        return Some(false);
    }
    if matches!(after, b',' | b'.' | b':' | b';') {
        let followed_by_digit = text
            .get(index + 1)
            .is_some_and(|&code_unit| matches!(u8::try_from(code_unit), Ok(b'0'..=b'9')));
        return Some(before == b' ' && followed_by_digit);
    }
    if before == b' ' {
        return Some(true);
    }
    Some(!matches!(before, b'"' | b'\'') && !matches!(after, b'"' | b'\'' | b'\t' | b'|' | b'-'))
}

// A chunk while it is still being accumulated: where it starts, plus the properties shared by
// every chunk that can be committed from it.
#[derive(Clone, Copy)]
struct PendingChunk {
    start: usize,
    font_index: u16,
    text_type: u8,
    is_upright: bool,
    broken_on_tab: bool,
}

#[derive(Clone, Copy)]
struct ChunkBreakFlags {
    has_breaking_newline: bool,
    has_breaking_tab: bool,
    can_break_after: bool,
}

fn is_regional_indicator(code_point: u32) -> bool {
    (0x1F1E6..=0x1F1FF).contains(&code_point)
}

/// The number of regional indicators at the end of a text.
pub(crate) fn trailing_regional_indicator_count(text: &[u16]) -> usize {
    let mut index = text.len();
    let mut count = 0;
    while index > 0 && is_regional_indicator(previous_code_point_at(text, &mut index)) {
        count += 1;
    }
    count
}

/// Whether there is a soft wrap opportunity between the end of `before` and the start of `after`, such as the texts
/// of two text nodes that follow each other on a line. `code_unit_before` is the last code unit of the text before
/// `before`, if any. `regional_indicators_before` is the number of regional indicators that end `before`, including
/// any in text before it.
#[allow(clippy::too_many_arguments)]
pub(crate) fn soft_wrap_opportunity_between(
    before: &[u16],
    after: &[u16],
    code_unit_before: Option<u16>,
    regional_indicators_before: usize,
    word_break: u8,
    line_break: u8,
    line_break_language: LineBreakLanguage,
    breaks_after_soft_hyphen: bool,
) -> bool {
    let (Some(&last), Some(&first)) = (before.last(), after.first()) else {
        return false;
    };
    if last == SOFT_HYPHEN && !breaks_after_soft_hyphen && line_break != line_break::ANYWHERE {
        return false;
    }
    // NB: Whitespace gives its own soft wrap opportunities.
    if (last <= 0x7f && code_point_is_ascii_space(u32::from(last)))
        || (first <= 0x7f && code_point_is_ascii_space(u32::from(first)))
    {
        return false;
    }
    // NB: Only the number of regional indicators before the boundary tells whether it splits a flag, and they can
    //     reach further back than the context below.
    if regional_indicators_before > 0 && is_regional_indicator(code_point_at(after, 0)) {
        return regional_indicators_before.is_multiple_of(2);
    }
    // NB: A few code points on each side of the boundary are enough context to find a soft wrap opportunity there.
    const CONTEXT_LENGTH: usize = 8;
    let mut before_start = before.len().saturating_sub(CONTEXT_LENGTH);
    if before_start > 0 && is_utf16_low_surrogate(before[before_start]) {
        before_start -= 1;
    }
    let mut after_end = after.len().min(CONTEXT_LENGTH);
    if after_end < after.len() && is_utf16_low_surrogate(after[after_end]) {
        after_end += 1;
    }
    let mut text = Vec::with_capacity(before.len() - before_start + after_end + 1);
    // NB: Some rules look at the code point before the last one of `before`, which can be in the text before it.
    if before_start == 0
        && let Some(code_unit) = code_unit_before
        && !is_utf16_low_surrogate(code_unit)
    {
        text.push(code_unit);
    }
    text.extend_from_slice(&before[before_start..]);
    let boundary = text.len();
    text.extend_from_slice(&after[..after_end]);
    // OPTIMIZATION: Printable ASCII on both sides needs no line segmenter, unless line-break: anywhere breaks it.
    if word_break != word_break::BREAK_ALL
        && line_break != line_break::ANYWHERE
        && let Some(is_boundary) = ascii_line_break_at(&text, boundary)
    {
        return is_boundary;
    }
    // https://drafts.csswg.org/css-text-3/#text-encoding
    // [...] intervening inline box boundaries and out-of-flow elements must be ignored.
    // NB: The chunker of a single text only looks for soft wrap opportunities between grapheme clusters, so there is
    //     none inside a grapheme cluster that spans two texts either.
    if GraphemeSegmenter::new(&text).next_boundary(boundary, true) != Some(boundary) {
        return false;
    }
    LineBreaker::new(
        &text,
        word_break,
        line_break,
        line_break_language,
        breaks_after_soft_hyphen,
    )
    .is_at_line_break_opportunity(boundary)
}

/// Whether there is a soft wrap opportunity between an atomic inline and the text after it.
pub(crate) fn soft_wrap_opportunity_after_atomic_inline(after: &[u16]) -> bool {
    let Some(&first) = after.first() else {
        return false;
    };
    // NB: Whitespace gives its own soft wrap opportunities.
    if first <= 0x7f && code_point_is_ascii_space(u32::from(first)) {
        return false;
    }
    // https://drafts.csswg.org/css-text-3/#line-break-details
    // [...] with the exception of U+00A0 NO-BREAK SPACE, there must be no soft wrap opportunity between atomic inlines
    // and adjacent characters belonging to the Unicode GL, WJ, or ZWJ line breaking classes.
    // AD-HOC: A combining mark stays with the atomic inline, as UAX #14 keeps it with any character before it, rather
    //         than start the next line on its own.
    let code_point = code_point_at(after, 0);
    code_point == 0x00A0
        || !matches!(
            line_break_class(code_point),
            line_break_class::GLUE
                | line_break_class::WORD_JOINER
                | line_break_class::ZERO_WIDTH_JOINER
                | line_break_class::COMBINING_MARK
        )
}

/// Whether `word-break: break-all` has a soft wrap opportunity between two characters that `word-break: normal` lacks.
fn break_all_adds_soft_wrap_opportunity(before: u32, after: u32, line_break: u8) -> bool {
    use line_break_class::*;
    // https://drafts.csswg.org/css-text-3/#valdef-word-break-break-all
    // Breaking is allowed within “words”: specifically, in addition to soft wrap opportunities allowed for normal, any
    // typographic letter units (and any typographic character units resolving to the NU (“numeric”), AL
    // (“alphabetic”), or SA (“Southeast Asian”) line breaking classes [UAX14]) are instead treated as ID (“ideographic
    // characters”) for the purpose of line-breaking.
    let is_treated_as_ideographic = |class| {
        matches!(
            class,
            ALPHABETIC
                | NUMERIC
                | AMBIGUOUS
                | COMPLEX_CONTEXT
                | IDEOGRAPHIC
                | CONDITIONAL_JAPANESE_STARTER
                | HANGUL_JAMO
        )
    };
    let before_class = line_break_class(before);
    let after_class = line_break_class(after);
    // NB: Treating a character as ID only adds soft wrap opportunities next to the classes that UAX #14 keeps with AL,
    //     HL or NU but not with ID.
    match (
        is_treated_as_ideographic(before_class),
        is_treated_as_ideographic(after_class),
    ) {
        (true, true) => true,
        (true, false) => {
            matches!(after_class, OPEN_PUNCTUATION | PREFIX_NUMERIC)
                // https://drafts.csswg.org/css-text-3/#line-break-property
                // The following breaks are allowed for loose line breaking if the preceding character belongs to the
                // Unicode line breaking class ID [UAX14] (including when the preceding character is treated as ID due
                // to word-break: break-all), and are otherwise forbidden:
                // - breaks before hyphens: ‐ U+2010, – U+2013
                || (line_break == line_break::LOOSE && matches!(after, 0x2010 | 0x2013))
        }
        (false, true) => {
            matches!(
                before_class,
                CLOSE_PUNCTUATION | BREAK_SYMBOLS | INFIX_NUMERIC_SEPARATOR | POSTFIX_NUMERIC
            ) || (before_class == HYPHEN && after_class == NUMERIC)
        }
        (false, false) => false,
    }
}

/// Finds the soft wrap opportunities of a text.
struct LineBreaker<'text> {
    text: &'text [u16],
    line_segmenter: LineSegmenter<'text>,
    /// The grapheme clusters of the text, which `line-break: anywhere` breaks between.
    grapheme_segmenter: std::cell::OnceCell<GraphemeSegmenter>,
    word_break: u8,
    line_break: u8,
    breaks_after_soft_hyphen: bool,
}

impl<'text> LineBreaker<'text> {
    fn new(
        text: &'text [u16],
        word_break: u8,
        line_break: u8,
        line_break_language: LineBreakLanguage,
        breaks_after_soft_hyphen: bool,
    ) -> Self {
        Self {
            text,
            line_segmenter: LineSegmenter::new(text, line_break, line_break_language),
            grapheme_segmenter: std::cell::OnceCell::new(),
            word_break,
            line_break,
            breaks_after_soft_hyphen,
        }
    }

    fn is_at_line_break_opportunity(&self, index: usize) -> bool {
        // https://drafts.csswg.org/css-text-3/#valdef-line-break-anywhere
        // "There is a soft wrap opportunity around every typographic character unit, including around any punctuation
        // character or preserved white spaces, or in the middle of words, disregarding any prohibition against line
        // breaks, even those introduced by characters with the GL, WJ, or ZWJ line breaking classes or mandated by the
        // 'word-break' property."
        if self.line_break == line_break::ANYWHERE {
            return index > 0
                && index < self.text.len()
                && self
                    .grapheme_segmenter
                    .get_or_init(|| GraphemeSegmenter::new(self.text))
                    .next_boundary(index, true)
                    == Some(index);
        }
        // https://drafts.csswg.org/css-text-3/#valdef-hyphens-none
        // Words are not hyphenated, even if characters inside the word explicitly define hyphenation opportunities.
        if !self.breaks_after_soft_hyphen && index > 0 && self.text.get(index - 1) == Some(&SOFT_HYPHEN) {
            return false;
        }
        let get_previous_code_point = || -> Option<u32> {
            if index == 0 {
                return None;
            }
            let mut index = index;
            let mut previous_code_point = previous_code_point_at(self.text, &mut index);
            while line_break_class(previous_code_point) == line_break_class::COMBINING_MARK && index > 0 {
                previous_code_point = previous_code_point_at(self.text, &mut index);
            }
            Some(previous_code_point)
        };

        let is_at_line_segmenter_boundary = || {
            if self.word_break != word_break::BREAK_ALL
                && let Some(is_boundary) = ascii_line_break_at(self.text, index)
            {
                return is_boundary;
            }
            self.line_segmenter.is_boundary(index)
        };

        match self.word_break {
            word_break::NORMAL | word_break::BREAK_WORD => is_at_line_segmenter_boundary(),
            word_break::BREAK_ALL => {
                if index >= self.text.len() {
                    return false;
                }
                if let Some(previous_code_point) = get_previous_code_point()
                    && break_all_adds_soft_wrap_opportunity(
                        previous_code_point,
                        code_point_at(self.text, index),
                        self.line_break,
                    )
                {
                    return true;
                }
                is_at_line_segmenter_boundary()
            }
            word_break::KEEP_ALL => {
                if index >= self.text.len() {
                    return false;
                }
                use line_break_class::*;
                // https://drafts.csswg.org/css-text-3/#valdef-word-break-keep-all
                // Breaking is forbidden within “words”: implicit soft wrap opportunities between typographic letter
                // units (or other typographic character units belonging to the NU, AL, AI, or ID Unicode line breaking
                // classes [UAX14]) are suppressed, [...]
                // NB: A letter in a class of its own, such as the iteration mark U+3005 (class NS), is a typographic
                //     letter unit too.
                let keeps_together = |code_point| match line_break_class(code_point) {
                    ALPHABETIC | NUMERIC | AMBIGUOUS | IDEOGRAPHIC | CONDITIONAL_JAPANESE_STARTER | HANGUL_JAMO => true,
                    OTHER => super::tree_builder::ladybird_layout_code_point_category_facts(code_point).is_letter,
                    _ => false,
                };
                if let Some(previous_code_point) = get_previous_code_point()
                    && keeps_together(previous_code_point)
                    && keeps_together(code_point_at(self.text, index))
                {
                    return false;
                }
                is_at_line_segmenter_boundary()
            }
            _ => unreachable!("invalid word-break value"),
        }
    }
}

struct TextChunker<'text> {
    text: &'text [u16],
    frozen_font_list: &'text FrozenFontList,
    grapheme_segmenter: GraphemeSegmenter,
    line_breaker: LineBreaker<'text>,
    font_variant_emoji: u8,
    should_collapse_whitespace: bool,
    break_after_preserved_tabs: bool,
    should_wrap_lines: bool,
    should_respect_linebreaks: bool,
    unidirectional_ltr: bool,
    splits_at_orientation_changes: bool,
    current_index: usize,
    /// The fonts of the chunks, each once, which the chunks name by index.
    fonts: Vec<FontHandle>,
    first_font_and_ascii_code_points_it_resolves: Option<(&'text FontHandle, u128)>,
    font_for_every_space: Option<&'text FontHandle>,
}

impl<'text> TextChunker<'text> {
    fn new(inputs: TextChunkInputs<'text>) -> Self {
        let first_font_and_ascii_code_points_it_resolves = inputs
            .frozen_font_list
            .first_font_and_ascii_code_points_it_resolves_in_text_presentation()
            .filter(|_| inputs.font_variant_emoji != font_variant_emoji::EMOJI);
        let font_for_every_space = first_font_and_ascii_code_points_it_resolves.and_then(|(font, code_points)| {
            let space = 1u128 << b' ';
            let spaces_and_line_feeds = space | 1 << b'\n';
            let every_code_point_but_spaces_and_line_feeds_resolves_to_first_font = inputs
                .text
                .iter()
                .all(|&code_unit| code_unit < 128 && (code_points | spaces_and_line_feeds) & (1 << code_unit) != 0);
            (code_points & space != 0 && every_code_point_but_spaces_and_line_feeds_resolves_to_first_font)
                .then_some(font)
        });
        Self {
            text: inputs.text,
            frozen_font_list: inputs.frozen_font_list,
            grapheme_segmenter: GraphemeSegmenter::new(inputs.text),
            line_breaker: LineBreaker::new(
                inputs.text,
                inputs.word_break,
                inputs.line_break,
                inputs.line_break_language,
                inputs.breaks_after_soft_hyphen,
            ),
            font_variant_emoji: inputs.font_variant_emoji,
            should_collapse_whitespace: matches!(
                inputs.white_space_collapse,
                white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS
            ),
            break_after_preserved_tabs: inputs.white_space_collapse == white_space_collapse::BREAK_SPACES
                && inputs.should_wrap_lines,
            should_wrap_lines: inputs.should_wrap_lines,
            should_respect_linebreaks: inputs.should_respect_linebreaks,
            unidirectional_ltr: inputs.unidirectional_ltr,
            splits_at_orientation_changes: inputs.splits_at_orientation_changes,
            current_index: 0,
            fonts: Vec::new(),
            first_font_and_ascii_code_points_it_resolves,
            font_for_every_space,
        }
    }

    fn current_code_point(&self) -> u32 {
        code_point_at(self.text, self.current_index)
    }

    fn current_text_type(&self) -> u8 {
        if self.unidirectional_ltr {
            return line_box_fragment::GLYPH_TEXT_TYPE_LTR;
        }
        text_type_for_code_point(self.current_code_point())
    }

    fn current_code_point_is_upright(&self) -> bool {
        self.splits_at_orientation_changes && code_point_is_upright_in_mixed_orientation(self.current_code_point())
    }

    fn next_chunk_boundary(&self) -> usize {
        // CRLF is one grapheme, but the line feed must start its own chunk when CSS preserves line breaks.
        if self.should_respect_linebreaks && self.text.get(self.current_index) == Some(&u16::from(b'\r')) {
            return self.current_index + 1;
        }
        self.grapheme_segmenter
            .next_boundary(self.current_index, false)
            .unwrap_or(self.text.len())
    }

    fn is_collapsible(&self, code_point: u32) -> bool {
        // NB: A line feed that white-space-collapse: preserve-breaks keeps is a forced line break, not white space that
        //     collapses with the white space around it.
        self.should_collapse_whitespace
            && code_point_is_ascii_space(code_point)
            && !(self.should_respect_linebreaks && code_point == '\n' as u32)
    }

    fn is_at_line_break_opportunity(&self) -> bool {
        self.should_wrap_lines && self.line_breaker.is_at_line_break_opportunity(self.current_index)
    }

    fn emoji_presentation_at(&self, code_unit_offset: usize, code_point: u32) -> EmojiPresentation {
        let next_offset = code_unit_offset + code_unit_length_for_code_point(code_point);
        let next_code_point = (next_offset < self.text.len()).then(|| code_point_at(self.text, next_offset));
        let code_point_after_next = next_code_point.and_then(|next_code_point| {
            let offset_after_next = next_offset + code_unit_length_for_code_point(next_code_point);
            (offset_after_next < self.text.len()).then(|| code_point_at(self.text, offset_after_next))
        });
        // OPTIMIZATION: No code point below U+0300 has the Emoji_Presentation property, so only a variation selector
        //               or a zero width joiner can give one of them anything but the default text presentation.
        let default_presentation = if code_point < 0x300 && !matches!(next_code_point, Some(0xfe0e | 0xfe0f | 0x200d)) {
            EmojiPresentation {
                is_emoji: false,
                forced: false,
            }
        } else {
            emoji_presentation_for_code_point(code_point, next_code_point, code_point_after_next)
        };
        // OPTIMIZATION: Below U+0300, only '#', '*', the ASCII digits, U+00A9 and U+00AE have the Emoji property.
        let has_emoji_property = if code_point < 0x300 {
            matches!(code_point, 0x23 | 0x2a | 0x30..=0x39 | 0xa9 | 0xae)
        } else {
            unicode_layout_code_point_has_emoji_property(code_point)
        };
        debug_assert!(
            code_point >= 0x300 || {
                let presentation =
                    emoji_presentation_for_code_point(code_point, next_code_point, code_point_after_next);
                let has_property = unicode_layout_code_point_has_emoji_property(code_point);
                presentation.is_emoji == default_presentation.is_emoji
                    && presentation.forced == default_presentation.forced
                    && has_property == has_emoji_property
            }
        );
        if default_presentation.forced || !has_emoji_property {
            return default_presentation;
        }

        match self.font_variant_emoji {
            font_variant_emoji::TEXT => EmojiPresentation {
                is_emoji: false,
                forced: true,
            },
            font_variant_emoji::EMOJI => EmojiPresentation {
                is_emoji: true,
                forced: true,
            },
            font_variant_emoji::UNICODE => EmojiPresentation {
                is_emoji: default_presentation.is_emoji,
                forced: true,
            },
            _ => default_presentation,
        }
    }

    fn font_for_code_point_at(&self, code_unit_offset: usize, code_point: u32) -> Cow<'text, FontHandle> {
        if let Some((font, code_points)) = self.first_font_and_ascii_code_points_it_resolves
            && code_point < 128
            && code_points & (1 << code_point) != 0
            && !matches!(self.text.get(code_unit_offset + 1), Some(0xfe0e | 0xfe0f))
        {
            return Cow::Borrowed(font);
        }
        self.frozen_font_list
            .font_for_code_point_borrowed(code_point, self.emoji_presentation_at(code_unit_offset, code_point))
    }

    fn font_for_space(&self, space_code_point: u32) -> Cow<'text, FontHandle> {
        if let Some(font) = self.font_for_every_space {
            return Cow::Borrowed(font);
        }

        // https://drafts.csswg.org/css-fonts-4/#font-matching-algorithm
        // NB: A space is matched like any other character: It takes the first font in the list whose unicode-range
        //     covers it and that has a glyph for it, rather than the font of the text next to it.
        let font = self.frozen_font_list.font_for_code_point_borrowed(
            space_code_point,
            EmojiPresentation {
                is_emoji: false,
                forced: false,
            },
        );
        if !font.is_emoji_font() {
            return font;
        }
        // AD-HOC: An emoji font listed ahead of a text font would give spaces its width, so a space skips it for the
        //         first text font with a glyph for it.
        self.frozen_font_list.font_for_code_point_borrowed(
            space_code_point,
            EmojiPresentation {
                is_emoji: false,
                forced: true,
            },
        )
    }

    fn expected_font_for(&self, code_point: u32) -> Cow<'text, FontHandle> {
        if is_interword_space(code_point) {
            self.font_for_space(code_point)
        } else if code_point == '\t' as u32 {
            // NB: A tab is drawn as a shift to a tab stop rather than as a glyph, so it takes the font that a space in
            //     its place would take, not a fallback font that happens to have a glyph for it.
            self.font_for_space(' ' as u32)
        } else {
            self.font_for_code_point_at(self.current_index, code_point)
        }
    }

    fn is_font_at_index(&self, font: &FontHandle, font_index: u16) -> bool {
        *font == self.fonts[usize::from(font_index)]
    }

    fn index_of_font(&mut self, font: Cow<'text, FontHandle>) -> u16 {
        let index = match self.fonts.iter().rposition(|kept| *kept == *font) {
            Some(index) => index,
            None => {
                self.fonts.push(font.into_owned());
                self.fonts.len() - 1
            }
        };
        u16::try_from(index).expect("a text is set in fewer than 65536 fonts")
    }

    fn try_commit_chunk(
        &mut self,
        start: usize,
        end: usize,
        break_flags: ChunkBreakFlags,
        font_index: u16,
        text_type: u8,
    ) -> Option<TextChunk> {
        let length_in_code_units = end - start;
        if length_in_code_units == 0 {
            return None;
        }
        let is_all_whitespace = self.text[start..end]
            .iter()
            .all(|unit| *unit <= 0x7f && code_point_is_ascii_space(u32::from(*unit)));
        Some(TextChunk {
            start,
            length: length_in_code_units,
            font_index,
            has_breaking_newline: break_flags.has_breaking_newline,
            has_breaking_tab: break_flags.has_breaking_tab,
            is_all_whitespace,
            can_break_after: break_flags.can_break_after,
            text_type,
        })
    }

    fn next_chunk(&mut self) -> Option<TextChunk> {
        'restart: loop {
            if self.current_index >= self.text.len() {
                return None;
            }

            let mut code_point = self.current_code_point();
            let mut can_break_at_current_position = self.is_at_line_break_opportunity();
            let expected_font = self.expected_font_for(code_point);
            let mut pending = PendingChunk {
                start: self.current_index,
                font_index: self.index_of_font(expected_font),
                text_type: self.current_text_type(),
                is_upright: self.current_code_point_is_upright(),
                broken_on_tab: false,
            };

            while self.current_index < self.text.len() {
                code_point = self.current_code_point();

                if code_point == '\t' as u32 {
                    if let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, false) {
                        return Some(chunk);
                    }

                    pending.broken_on_tab = true;
                    self.current_index = tab_chunk_end(self.text, self.current_index, self.break_after_preserved_tabs);
                    can_break_at_current_position = self.is_at_line_break_opportunity();
                }

                let font_changes = !self.is_font_at_index(&self.expected_font_for(code_point), pending.font_index);

                if font_changes
                    && let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, can_break_at_current_position)
                {
                    return Some(chunk);
                }

                if self.should_respect_linebreaks && code_point == '\n' as u32 {
                    // Newline encountered, and we're supposed to preserve them.
                    // If we have accumulated some code points in the current chunk, commit them now and continue with
                    // the newline next time.
                    if let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, false) {
                        return Some(chunk);
                    }

                    // Otherwise, commit the newline!
                    self.current_index = self.next_chunk_boundary();
                    let chunk = self.try_commit_chunk(
                        pending.start,
                        self.current_index,
                        ChunkBreakFlags {
                            has_breaking_newline: true,
                            has_breaking_tab: pending.broken_on_tab,
                            can_break_after: false,
                        },
                        pending.font_index,
                        pending.text_type,
                    );
                    return Some(chunk.expect("newline chunk must be non-empty"));
                }

                // If both this code point and the previous code point are collapsible, skip code points until we're at
                // a non-collapsible code point.
                if self.is_collapsible(code_point)
                    && self.current_index > 0
                    && self.is_collapsible(code_point_at(self.text, self.current_index - 1))
                {
                    let chunk = self.try_commit_chunk_at_cursor(&pending, false);

                    while self.current_index < self.text.len() && self.is_collapsible(self.current_code_point()) {
                        self.current_index = self.next_chunk_boundary();
                    }

                    if let Some(chunk) = chunk {
                        return Some(chunk);
                    }

                    continue 'restart;
                }

                // Tabs can advance the cursor past the text. Split shaping runs at direction changes independently
                // of line wrapping, while keeping the direction lookup inside the text.
                if self.current_index < self.text.len()
                    && pending.text_type != self.current_text_type()
                    && let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, can_break_at_current_position)
                {
                    return Some(chunk);
                }

                // NB: Each chunk is typeset either upright or sideways as a whole, so split it where that changes.
                if self.current_index < self.text.len()
                    && pending.is_upright != self.current_code_point_is_upright()
                    && let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, can_break_at_current_position)
                {
                    return Some(chunk);
                }

                // NB: Leading collapsible whitespace must be a separate chunk even when wrapping is disabled.
                if self.should_wrap_lines || (self.should_collapse_whitespace && self.current_index == pending.start) {
                    if code_point_is_ascii_space(code_point) {
                        // Whitespace encountered, and we're allowed to break on whitespace.
                        // If we have accumulated some code points in the current chunk, commit them now and continue
                        // with the whitespace next time.
                        if let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, false) {
                            return Some(chunk);
                        }

                        // Otherwise, commit the whitespace!
                        self.current_index = self.next_chunk_boundary();
                        can_break_at_current_position = self.is_at_line_break_opportunity();
                        let space_font = self.font_for_space(code_point);
                        let space_font_index = self.index_of_font(space_font);
                        if let Some(chunk) = self.try_commit_chunk(
                            pending.start,
                            self.current_index,
                            ChunkBreakFlags {
                                has_breaking_newline: false,
                                has_breaking_tab: pending.broken_on_tab,
                                can_break_after: false,
                            },
                            space_font_index,
                            pending.text_type,
                        ) {
                            return Some(chunk);
                        }
                        continue;
                    }

                    if can_break_at_current_position
                        && let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, true)
                    {
                        return Some(chunk);
                    }
                }

                self.current_index = self.next_chunk_boundary();
                can_break_at_current_position = self.is_at_line_break_opportunity();
            }

            if pending.start != self.text.len() {
                // Try to output whatever's left at the end of the text node.
                if let Some(chunk) = self.try_commit_chunk(
                    pending.start,
                    self.text.len(),
                    ChunkBreakFlags {
                        has_breaking_newline: false,
                        has_breaking_tab: pending.broken_on_tab,
                        can_break_after: false,
                    },
                    pending.font_index,
                    pending.text_type,
                ) {
                    return Some(chunk);
                }
            }

            return None;
        }
    }

    // Commits everything accumulated since `pending.start` up to the cursor, if that range is non-empty.
    fn try_commit_chunk_at_cursor(&mut self, pending: &PendingChunk, can_break_after: bool) -> Option<TextChunk> {
        if self.current_index == pending.start {
            return None;
        }
        self.try_commit_chunk(
            pending.start,
            self.current_index,
            ChunkBreakFlags {
                has_breaking_newline: false,
                has_breaking_tab: pending.broken_on_tab,
                can_break_after,
            },
            pending.font_index,
            pending.text_type,
        )
    }
}

pub(crate) fn text_chunks(
    pass: &LayoutPass<'_>,
    node: Node,
    should_wrap_lines: bool,
    should_respect_linebreaks: bool,
    unidirectional_ltr: bool,
) -> std::sync::Arc<super::rendered_text::CachedTextChunks> {
    let parent_style = StyleValues::for_node(pass, pass.parent(node));
    let frozen_font_list = parent_style.frozen_font_list();
    let counted_frozen_font_list = &parent_style.font().frozen_font_list;
    let key = super::rendered_text::TextChunkCacheKey {
        should_wrap_lines,
        should_respect_linebreaks,
        unidirectional_ltr,
        white_space_collapse: parent_style.white_space_collapse(),
        word_break: parent_style.word_break(),
        line_break: parent_style.line_break(),
        line_break_language: if parent_style.line_break() == line_break::LOOSE {
            pass.arena().text_line_break_language(node)
        } else {
            LineBreakLanguage::Other
        },
        breaks_after_soft_hyphen: parent_style.hyphens() != hyphens::NONE,
        font_variant_emoji: parent_style.font_variant_emoji(),
        frozen_font_list: crate::css::style::pointer_key::PointerLookup::new(counted_frozen_font_list, ()),
        frozen_font_list_fill_generation: frozen_font_list.fill_generation(),
        splits_at_orientation_changes: matches!(
            parent_style.writing_mode(),
            writing_mode::VERTICAL_RL | writing_mode::VERTICAL_LR
        ) && parent_style.text_orientation() == text_orientation::MIXED,
    };
    let text = &pass.text_content(node).text;
    pass.text_chunks(node, &key, || ChunkedText {
        frozen_font_list_held_for_memo_key: Some(parent_style.frozen_font_list_ref()),
        ..chunk_text(TextChunkInputs {
            text,
            frozen_font_list,
            white_space_collapse: key.white_space_collapse,
            word_break: key.word_break,
            line_break: key.line_break,
            line_break_language: key.line_break_language,
            breaks_after_soft_hyphen: key.breaks_after_soft_hyphen,
            font_variant_emoji: key.font_variant_emoji,
            should_wrap_lines,
            should_respect_linebreaks,
            unidirectional_ltr,
            splits_at_orientation_changes: key.splits_at_orientation_changes,
        })
    })
}

// Tabs occupy one UTF-16 code unit each. Other preserved whitespace is split below by next_chunk().
fn tab_chunk_end(text: &[u16], start: usize, break_after_each_tab: bool) -> usize {
    let mut end = start + 1;
    while !break_after_each_tab && text.get(end) == Some(&u16::from(b'\t')) {
        end += 1;
    }
    end
}

#[cfg(test)]
mod tests {
    use super::tab_chunk_end;

    #[test]
    fn preserved_tab_chunk_boundaries_respect_break_spaces() {
        let text: Vec<_> = "\t\t\tX".encode_utf16().collect();
        assert_eq!(tab_chunk_end(&text, 0, true), 1);
        assert_eq!(tab_chunk_end(&text, 1, true), 2);
        assert_eq!(tab_chunk_end(&text, 2, true), 3);
        // pre/pre-wrap and nowrap retain the existing tab-run grouping.
        assert_eq!(tab_chunk_end(&text, 0, false), 3);
        assert_eq!(tab_chunk_end(&text, 2, false), 3);
        assert_eq!(tab_chunk_end(&[u16::from(b'\t')], 0, true), 1);
    }
}