Skip to content

Truly independent web browser

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

use super::*;

// NB: Keep the addition order shared with intrinsic sizing: CssPixels arithmetic saturates.
pub(crate) fn inline_advance(
    leading_margin: CssPixels,
    leading_size: CssPixels,
    content_inline_size: CssPixels,
    trailing_size: CssPixels,
    trailing_margin: CssPixels,
) -> CssPixels {
    leading_margin + leading_size + content_inline_size + trailing_size + trailing_margin
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct StaticPositionMarker {
    pub(crate) box_: Node,
    pub(crate) inline_offset: CssPixels,
    pub(crate) block_offset: CssPixels,
    pub(crate) writing_mode: u8,
    pub(crate) preceded_by_in_flow_content: bool,
    /// How many fragments the line held when the marker was added, which places it in the line's logical order.
    pub(crate) fragments_before: usize,
}

impl StaticPositionMarker {
    pub(crate) fn offset(self) -> (CssPixels, CssPixels) {
        geometry::to_physical(self.writing_mode, self.inline_offset, self.block_offset)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct InlineBoxBaseline {
    pub(crate) box_: Node,
    pub(crate) baseline: CssPixels,
    pub(crate) accumulated_vertical_shift: CssPixels,
}

/// An inline box on a line, and where on the line its content begins. No fragment on the line belongs to a box that's
/// empty, or to one whose content there is only whitespace that collapsed away, the forced break that ends the line,
/// or a block-level box the line stops at.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct InlineBoxStrut {
    pub(crate) box_: Node,
    pub(crate) inline_offset: CssPixels,
}

/// What text-overflow elided from the end of a line.
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct TextOverflowElision {
    /// The inline length of the line before the ellipsis.
    pub(crate) inline_length: CssPixels,
    /// Where in the line the fragment that ends in the ellipsis starts.
    pub(crate) ellipsis_fragment_start: CssPixels,
    /// The inline length of the fragment that ends in the ellipsis before it was shortened.
    pub(crate) ellipsis_fragment_inline_length: CssPixels,
    /// How much of its inline length that fragment lost at its left end, where the ellipsis is on the left. And there,
    /// the fragments are still where the content put them, rather than where the line box starts.
    pub(crate) ellipsis_fragment_inline_length_lost_on_left: Option<CssPixels>,
}

/// What a line its block container interrupted for a block-level box keeps of the box, as the layout of the box left it.
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct BlockLevelBoxOnLine {
    /// The offset of the content box of the box in its containing block.
    pub(crate) content_offset: FfiCssPixelPoint,
    /// The sizes and box sides of the box.
    pub(crate) cells: used_values::RootInputCells,
    /// The baselines the box gives the line.
    pub(crate) baselines: formatting_context::LineBaselines,
}

#[derive(Clone, PartialEq)]
pub(crate) struct LineBoxData {
    pub(crate) start: super::fragmentation::LinePosition,
    pub(crate) fragments: Vec<line_box_fragment::LineBoxFragmentData>,
    pub(crate) static_position_markers: Vec<StaticPositionMarker>,
    pub(crate) inline_box_baselines: Vec<InlineBoxBaseline>,
    /// The inline boxes that are on the line whether or not a fragment on it belongs to them. One that no fragment
    /// belongs to takes part in the height and alignment of the line box by its strut (a box as wide as nothing, with
    /// its font and line height) — but only where the line holds content or ends in a forced break.
    /// https://drafts.csswg.org/css-inline-3/#invisible-line-boxes
    pub(crate) inline_box_struts: Vec<InlineBoxStrut>,
    pub(crate) text_overflow_elision: Option<TextOverflowElision>,
    /// The block-level box the line holds, where the line is interrupted for one.
    pub(crate) block_level_box: Option<BlockLevelBoxOnLine>,
    /// Whether placing the line aligned it as the last line of its block, or a line before a forced break, by
    /// text-align-last. Justification follows the same decision.
    pub(crate) uses_last_line_alignment: Option<bool>,
    /// Where the line box starts, past any floats, once the line is placed.
    pub(crate) placed_inline_start: CssPixels,
    pub(crate) record: inline_content::LineRecord,
}

impl std::ops::Deref for LineBoxData {
    type Target = inline_content::LineRecord;
    fn deref(&self) -> &Self::Target {
        &self.record
    }
}

impl std::ops::DerefMut for LineBoxData {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.record
    }
}

impl LineBoxData {
    pub(crate) fn new(direction: u8, writing_mode: u8, start: super::fragmentation::LinePosition) -> Self {
        Self {
            start,
            fragments: Vec::new(),
            static_position_markers: Vec::new(),
            inline_box_baselines: Vec::new(),
            inline_box_struts: Vec::new(),
            text_overflow_elision: None,
            block_level_box: None,
            uses_last_line_alignment: None,
            placed_inline_start: CssPixels::default(),
            record: inline_content::LineRecord {
                direction,
                writing_mode,
                is_empty: true,
                ..Default::default()
            },
        }
    }

    pub(crate) fn retained_metrics(&self) -> inline_content::LineRecord {
        inline_content::LineRecord {
            is_empty: self.is_empty(),
            horizontal_extent: inline_formatting_context::line_physical_horizontal_extent(self),
            ..self.record
        }
    }

    pub(crate) fn push_fragment(&mut self, fragment: line_box_fragment::LineBoxFragmentData) {
        // Many lines contain a single fragment, so avoid Vec's initial capacity of four large fragments.
        if self.fragments.capacity() == 0 {
            self.fragments.reserve_exact(1);
        }
        self.fragments.push(fragment);
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn add_fragment(
        &mut self,
        layout_node: Node,
        start: usize,
        length: usize,
        leading_size: CssPixels,
        trailing_size: CssPixels,
        leading_margin: CssPixels,
        trailing_margin: CssPixels,
        content_inline_size: CssPixels,
        content_block_size: CssPixels,
        border_box_block_start: CssPixels,
        border_box_block_end: CssPixels,
        glyphs: Option<line_box_fragment::ItemGlyphRun<'_>>,
        facts: line_box_fragment::FragmentBuildFacts,
        text_align_is_justify: bool,
        trailing_whitespace: line_box_fragment::TrailingWhitespace,
    ) {
        let can_merge = glyphs.as_ref().is_some_and(|glyphs| {
            !text_align_is_justify
                && self.fragments.last().is_some_and(|last| {
                    !last.has_soft_wrap_opportunity_after
                        && last.layout_node == layout_node
                        && last.glyphs.as_ref().is_some_and(|last_glyphs| {
                            last_glyphs.font == *glyphs.font && last_glyphs.is_upright == glyphs.is_upright
                        })
                        && last.start + last.length_in_code_units == start
                })
        });
        if can_merge {
            let last = self.fragments.last_mut().unwrap();
            last.length_in_code_units += length;
            last.append_glyph_run(&glyphs.unwrap(), content_inline_size, start - last.start);
            if trailing_whitespace.length_in_code_units == length {
                last.trailing_whitespace += trailing_whitespace;
            } else {
                last.trailing_whitespace = trailing_whitespace;
            }
        } else {
            let inline_offset = leading_margin + leading_size + self.record.inline_length;
            let mut fragment = line_box_fragment::LineBoxFragmentData::new(
                layout_node,
                start,
                length,
                inline_offset,
                CssPixels::default(),
                content_inline_size,
                content_block_size,
                border_box_block_start,
                self.direction,
                self.writing_mode,
                glyphs.map(line_box_fragment::ItemGlyphRun::into_glyph_data),
                facts,
            );
            fragment.trailing_whitespace = trailing_whitespace;
            self.push_fragment(fragment);
        }
        self.record.inline_length += inline_advance(
            leading_margin,
            leading_size,
            content_inline_size,
            trailing_size,
            trailing_margin,
        );
        self.block_length = self
            .block_length
            .max(content_block_size + border_box_block_start + border_box_block_end);
    }

    pub(crate) fn advance_inline_length(&mut self, inline_size: CssPixels) {
        self.record.inline_length += inline_size;
    }

    pub(crate) fn add_static_position_marker(&mut self, box_: Node, preceded_by_inline_box_start_edges: bool) {
        self.static_position_markers.push(StaticPositionMarker {
            box_,
            inline_offset: self.record.inline_length,
            block_offset: CssPixels::default(),
            writing_mode: self.writing_mode,
            preceded_by_in_flow_content: !self.fragments.is_empty() || preceded_by_inline_box_start_edges,
            fragments_before: self.fragments.len(),
        });
    }

    pub(crate) fn set_inline_box_baseline(
        &mut self,
        box_: Node,
        baseline: CssPixels,
        accumulated_vertical_shift: CssPixels,
    ) -> bool {
        if self.inline_box_baselines.iter().any(|entry| entry.box_ == box_) {
            return false;
        }
        self.inline_box_baselines.push(InlineBoxBaseline {
            box_,
            baseline,
            accumulated_vertical_shift,
        });
        true
    }

    pub(crate) fn inline_box_baseline(&self, box_: Node) -> Option<InlineBoxBaseline> {
        self.inline_box_baselines
            .iter()
            .find(|entry| entry.box_ == box_)
            .copied()
    }

    /// Puts `box_` on the line, with its content beginning `leading_edges` past the content the line holds so far.
    pub(crate) fn add_inline_box_strut(&mut self, box_: Node, leading_edges: CssPixels) {
        if self.inline_box_struts.iter().any(|strut| strut.box_ == box_) {
            return;
        }
        self.inline_box_struts.push(InlineBoxStrut {
            box_,
            inline_offset: self.record.inline_length + leading_edges,
        });
    }

    /// Whether the struts of the inline boxes on the line count, which they don't on a line with nothing else on it.
    pub(crate) fn takes_inline_box_struts(&self) -> bool {
        !self.has_block_level_box && (!self.fragments.is_empty() || self.has_forced_break)
    }

    pub(crate) fn clamp_static_position_markers_to_inline_length(&mut self) {
        for marker in &mut self.static_position_markers {
            if marker.inline_offset > self.record.inline_length {
                marker.inline_offset = self.record.inline_length;
            }
        }
    }

    fn calculate_or_trim_trailing_whitespace(&mut self, should_remove: bool) -> CssPixels {
        let mut whitespace_inline_size = CssPixels::default();
        // The whitespace fragments removed so far that follow on from the same node.
        let mut removed_whitespace: Option<(Node, line_box_fragment::TrailingWhitespace)> = None;
        let mut fragment_index = self.fragments.len();

        let last_fragment_index = loop {
            if fragment_index == 0 {
                return whitespace_inline_size;
            }
            fragment_index -= 1;
            let fragment = &self.fragments[fragment_index];
            if !matches!(
                fragment.white_space_collapse,
                white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS
            ) {
                return whitespace_inline_size;
            }
            // NB: A fragment that's all trailing white space other than a space, such as an element holding just an
            //     ideographic space, is trimmed to nothing rather than removed, so a line with nothing else on it stays.
            let is_all_trailing_whitespace = fragment.length_in_code_units > 0
                && fragment.trailing_whitespace.length_in_code_units == fragment.length_in_code_units;
            if is_all_trailing_whitespace && !fragment.is_justifiable_whitespace() {
                let fragment_trailing_whitespace = fragment.trailing_whitespace;
                whitespace_inline_size += fragment_trailing_whitespace.inline_size;
                if should_remove {
                    let fragment = &mut self.fragments[fragment_index];
                    fragment.length_in_code_units -= fragment_trailing_whitespace.length_in_code_units;
                    fragment.inline_length -= fragment_trailing_whitespace.inline_size;
                    fragment.trailing_whitespace = line_box_fragment::TrailingWhitespace::default();
                    fragment.record.trimmed_trailing_whitespace += fragment_trailing_whitespace;
                    self.record.inline_length -= fragment_trailing_whitespace.inline_size;
                    self.clamp_static_position_markers_to_inline_length();
                }
                continue;
            }
            if !fragment.is_justifiable_whitespace() {
                break fragment_index;
            }

            whitespace_inline_size += fragment.inline_length;
            if should_remove {
                let removed = line_box_fragment::TrailingWhitespace {
                    length_in_code_units: fragment.length_in_code_units,
                    inline_size: fragment.inline_length,
                    ascii_inline_size: fragment.inline_length,
                };
                removed_whitespace = match removed_whitespace {
                    Some((node, mut sum)) if node == fragment.layout_node => {
                        sum += removed;
                        Some((node, sum))
                    }
                    _ => Some((fragment.layout_node, removed)),
                };
                self.record.inline_length -= fragment.inline_length;
                self.fragments.remove(fragment_index);
                self.clamp_static_position_markers_to_inline_length();
            }
        };

        let last_fragment = &self.fragments[last_fragment_index];
        if last_fragment.text().is_empty() {
            return whitespace_inline_size;
        }

        // Trim the last fragment's trailing whitespace by the advance recorded when it was shaped.
        let fragment_trailing_whitespace = last_fragment.trailing_whitespace;
        whitespace_inline_size += fragment_trailing_whitespace.inline_size;
        if should_remove {
            let fragment = &mut self.fragments[last_fragment_index];
            fragment.length_in_code_units -= fragment_trailing_whitespace.length_in_code_units;
            fragment.inline_length -= fragment_trailing_whitespace.inline_size;
            fragment.trailing_whitespace = line_box_fragment::TrailingWhitespace::default();
            fragment.record.trimmed_trailing_whitespace += fragment_trailing_whitespace;
            if let Some((node, removed)) = removed_whitespace
                && node == fragment.layout_node
            {
                fragment.record.trimmed_trailing_whitespace += removed;
            }
            self.record.inline_length -= fragment_trailing_whitespace.inline_size;
            self.clamp_static_position_markers_to_inline_length();
        }
        whitespace_inline_size
    }

    pub(crate) fn trailing_whitespace_inline_size(&mut self) -> CssPixels {
        self.calculate_or_trim_trailing_whitespace(false)
    }

    pub(crate) fn trim_trailing_whitespace(&mut self) {
        let trimmed_inline_size = self.calculate_or_trim_trailing_whitespace(true);
        // An inline box after the trimmed whitespace is at the end of what the line keeps.
        if trimmed_inline_size != CssPixels::default()
            && let Some(last) = self.fragments.last()
        {
            let end = last.inline_offset + last.inline_length;
            for strut in &mut self.inline_box_struts {
                strut.inline_offset = strut.inline_offset.min(end);
            }
        }
    }

    pub(crate) fn trim_trailing_whitespace_before_block_ellipsis(&mut self) {
        while let Some(fragment) = self.fragments.last_mut() {
            let whitespace = std::mem::take(&mut fragment.trailing_whitespace);
            if whitespace.length_in_code_units == 0 {
                break;
            }
            self.record.inline_length -= whitespace.inline_size;
            if whitespace.length_in_code_units == fragment.length_in_code_units {
                self.fragments.pop();
                continue;
            }
            fragment.length_in_code_units -= whitespace.length_in_code_units;
            fragment.inline_length -= whitespace.inline_size;
            fragment.record.trimmed_trailing_whitespace += whitespace;
            break;
        }
        self.clamp_static_position_markers_to_inline_length();
    }
    pub(crate) fn is_empty_or_ends_in_whitespace(&self) -> bool {
        self.fragments
            .last()
            .is_none_or(line_box_fragment::LineBoxFragmentData::ends_in_whitespace)
    }

    pub(crate) fn visible_fragments(&self) -> impl DoubleEndedIterator<Item = &line_box_fragment::LineBoxFragmentData> {
        self.fragments.iter().filter(|fragment| !fragment.is_fully_truncated)
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.fragments.is_empty() && !self.has_break
    }

    pub(crate) fn counts_toward_widows_and_orphans(&self) -> bool {
        // Empty records can have a soft break when advancing below a float, without representing a line of content.
        !self.fragments.is_empty() || self.has_forced_break
    }
}