Skip to main content

layout/flow/inline/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! # Inline Formatting Context Layout
6//!
7//! Inline layout is divided into three phases:
8//!
9//! 1. Box Tree Construction
10//! 2. Box to Line Layout
11//! 3. Line to Fragment Layout
12//!
13//! The first phase happens during normal box tree constrution, while the second two phases happen
14//! during fragment tree construction (sometimes called just "layout").
15//!
16//! ## Box Tree Construction
17//!
18//! During box tree construction, DOM elements are transformed into a box tree. This phase collects
19//! all of the inline boxes, text, atomic inline elements (boxes with `display: inline-block` or
20//! `display: inline-table` as well as things like images and canvas), absolutely positioned blocks,
21//! and floated blocks.
22//!
23//! During the last part of this phase, whitespace is collapsed and text is segmented into
24//! [`TextRun`]s based on script, chosen font, and line breaking opportunities. In addition, default
25//! fonts are selected for every inline box. Each segment of text is shaped using HarfBuzz and
26//! turned into a series of glyphs, which all have a size and a position relative to the origin of
27//! the [`TextRun`] (calculated in later phases).
28//!
29//! The code for this phase is mainly in `construct.rs`, but text handling can also be found in
30//! `text_runs.rs.`
31//!
32//! ## Box to Line Layout
33//!
34//! During the first phase of fragment tree construction, box tree items are laid out into
35//! [`LineItem`]s and fragmented based on line boundaries. This is where line breaking happens. This
36//! part of layout fragments boxes and their contents across multiple lines while positioning floats
37//! and making sure non-floated contents flow around them. In addition, all atomic elements are laid
38//! out, which may descend into their respective trees and create fragments. Finally, absolutely
39//! positioned content is collected in order to later hoist it to the containing block for
40//! absolutes.
41//!
42//! Note that during this phase, layout does not know the final block position of content. Only
43//! during line to fragment layout, are the final block positions calculated based on the line's
44//! final content and its vertical alignment. Instead, positions and line heights are calculated
45//! relative to the line's final baseline which will be determined in the final phase.
46//!
47//! [`LineItem`]s represent a particular set of content on a line. Currently this is represented by
48//! a linear series of items that describe the line's hierarchy of inline boxes and content. The
49//! item types are:
50//!
51//!  - [`LineItem::InlineStartBoxPaddingBorderMargin`]
52//!  - [`LineItem::InlineEndBoxPaddingBorderMargin`]
53//!  - [`LineItem::TextRun`]
54//!  - [`LineItem::Atomic`]
55//!  - [`LineItem::AbsolutelyPositioned`]
56//!  - [`LineItem::Float`]
57//!
58//! The code for this can be found by looking for methods of the form `layout_into_line_item()`.
59//!
60//! ## Line to Fragment Layout
61//!
62//! During the second phase of fragment tree construction, the final block position of [`LineItem`]s
63//! is calculated and they are converted into [`Fragment`]s. After layout, the [`LineItem`]s are
64//! discarded and the new fragments are incorporated into the fragment tree. The final static
65//! position of absolutely positioned content is calculated and it is hoisted to its containing
66//! block via [`PositioningContext`].
67//!
68//! The code for this phase, can mainly be found in `line.rs`.
69//!
70
71pub mod construct;
72mod full_width;
73pub mod inline_box;
74pub mod line;
75mod line_breaker;
76mod mathml_italics;
77mod shaping_queue;
78mod small_kana;
79pub mod text_run;
80pub mod text_transform;
81
82use std::cell::{Cell, OnceCell};
83use std::mem;
84use std::ops::Range;
85use std::rc::Rc;
86use std::sync::{Arc, OnceLock};
87
88use app_units::{Au, MAX_AU};
89use atomic_refcell::AtomicRef;
90use bitflags::bitflags;
91use construct::InlineFormattingContextBuilder;
92use fonts::{FontMetrics, FontRef, ShapedTextSlice};
93use icu_locale_core::LanguageIdentifier;
94use icu_properties::props::{EnumeratedProperty, LineBreak as ICULineBreak};
95use icu_segmenter::options::{LineBreakOptions, LineBreakStrictness, LineBreakWordOption};
96use inline_box::{InlineBox, InlineBoxContainerState, InlineBoxIdentifier, InlineBoxes};
97use layout_api::LayoutNode;
98use line::{
99    AbsolutelyPositionedLineItem, AtomicLineItem, FloatLineItem, LineItem, LineItemLayout,
100    TextRunLineItem,
101};
102use malloc_size_of_derive::MallocSizeOf;
103use script::layout_dom::ServoLayoutNode;
104use servo_arc::Arc as ServoArc;
105use servo_base::text::{Utf8CodeUnits, Utf32CodeUnits};
106use style::Zero;
107use style::computed_values::line_break::T as LineBreak;
108use style::computed_values::text_wrap_mode::T as TextWrapMode;
109use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
110use style::computed_values::word_break::T as WordBreak;
111use style::context::{QuirksMode, SharedStyleContext};
112use style::properties::ComputedValues;
113use style::values::computed::BaselineShift;
114use style::values::generics::box_::BaselineShiftKeyword;
115use style::values::generics::font::LineHeight;
116use style::values::specified::box_::BaselineSource;
117use style::values::specified::text::TextAlignKeyword;
118use style::values::specified::{AlignmentBaseline, TextAlignLast, TextJustify};
119use text_run::{TextRun, get_font_for_first_font_for_style};
120use unicode_bidi::{BidiInfo, Level};
121
122use super::float::{Clear, PlacementAmongFloats};
123use super::{IndependentFloatOrAtomicLayoutResult, IndependentFormattingContextLayoutResult};
124use crate::SharedStyle;
125use crate::cell::{ArcRefCell, WeakRefCell};
126use crate::containing_block::{ConstraintSpace, ContainingBlock, IndefiniteContainingBlock};
127use crate::context::LayoutContext;
128use crate::dom::WeakLayoutBox;
129use crate::dom_traversal::NodeAndStyleInfo;
130use crate::flow::float::{FloatBox, SequentialLayoutState};
131use crate::flow::inline::shaping_queue::ShapingQueue;
132use crate::flow::inline::text_run::{
133    CaretPlaceholder, FontAndScriptInfo, TextRunItem, TextRunSegment,
134};
135use crate::flow::{
136    BlockLevelBox, CollapsibleWithParentStartMargin, FloatSide, PlacementState,
137    compute_inline_content_sizes_for_block_level_boxes, layout_block_level_child,
138    skippable_for_block_percentage_quirk,
139};
140use crate::formatting_contexts::{Baselines, IndependentFormattingContext};
141use crate::fragment_tree::{
142    CollapsedMargin, Fragment, FragmentChildren, FragmentFlags, PositioningFragment,
143};
144use crate::geom::{LogicalRect, LogicalSides1D, LogicalVec2};
145use crate::layout_box_base::LayoutBoxBase;
146use crate::positioned::{AbsolutelyPositionedBox, PositioningContext};
147use crate::sizing::{ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult};
148use crate::style_ext::{ComputedValuesExt, PaddingBorderMargin};
149
150// From gfxFontConstants.h in Firefox.
151static FONT_SUBSCRIPT_OFFSET_RATIO: f32 = 0.20;
152static FONT_SUPERSCRIPT_OFFSET_RATIO: f32 = 0.34;
153
154#[derive(Debug, MallocSizeOf)]
155pub(crate) struct InlineFormattingContext {
156    /// All [`InlineItem`]s in this [`InlineFormattingContext`] stored in a flat array.
157    /// [`InlineItem::StartInlineBox`] and [`InlineItem::EndInlineBox`] allow representing
158    /// the tree of inline boxes within the formatting context, but a flat array allows
159    /// easy iteration through all inline items.
160    inline_items: Vec<InlineItem>,
161
162    /// The tree of inline boxes in this [`InlineFormattingContext`]. These are stored in
163    /// a flat array with each being given a [`InlineBoxIdentifier`].
164    inline_boxes: InlineBoxes,
165
166    /// The text content of this inline formatting context.
167    #[conditional_malloc_size_of]
168    text_content: Arc<OnceLock<String>>,
169
170    /// The [`SharedInlineStyles`] for the root of this [`InlineFormattingContext`] that are used to
171    /// share styles with all [`TextRun`] children.
172    shared_inline_styles: SharedInlineStyles,
173
174    /// The default font that is used for the root of this [`InlineFormattingContext`]. This is the
175    /// font used when the font fallback code path is not taken. It may be `None` if no default
176    /// font was found (this typically means that no characters can be rendered).
177    default_font: Option<FontRef>,
178
179    /// Whether this IFC contains the 1st formatted line of an element:
180    /// <https://www.w3.org/TR/css-pseudo-4/#first-formatted-line>.
181    has_first_formatted_line: bool,
182
183    /// Whether or not this [`InlineFormattingContext`] contains floats.
184    pub(super) contains_floats: bool,
185
186    /// Whether or not this is an [`InlineFormattingContext`] for a single line text input's inner
187    /// text container.
188    is_single_line_text_input: bool,
189
190    /// Whether or not this is an [`InlineFormattingContext`] has right-to-left content, which
191    /// will require reordering during layout.
192    has_right_to_left_content: bool,
193
194    /// The cached multiplier for `tab-size: <number>`:
195    /// <https://drafts.csswg.org/css-text/#tab-size-property>
196    /// > the advance width of the space character (U+0020) of the nearest block container ancestor
197    /// > of the preserved tab, including its associated `letter-spacing` and `word-spacing`.
198    tab_size_multiplier: OnceLock<Au>,
199}
200
201/// [`TextRun`] and `TextFragment`s need a handle on their parent inline box (or inline
202/// formatting context root)'s style. In order to implement incremental layout, these are
203/// wrapped in [`SharedStyle`]. This allows updating the parent box tree element without
204/// updating every single descendant box tree node and fragment.
205#[derive(Clone, Debug, MallocSizeOf)]
206pub(crate) struct SharedInlineStyles {
207    pub style: SharedStyle,
208    pub selected: SharedStyle,
209}
210
211impl SharedInlineStyles {
212    pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
213        self.style.ptr_eq(&other.style) && self.selected.ptr_eq(&other.selected)
214    }
215
216    pub(crate) fn from_info_and_context(info: &NodeAndStyleInfo, context: &LayoutContext) -> Self {
217        Self {
218            style: SharedStyle::new(info.style.clone()),
219            selected: SharedStyle::new(info.node.selected_style(&context.style_context)),
220        }
221    }
222}
223
224impl BlockLevelBox {
225    fn layout_into_line_items(&self, layout: &mut InlineFormattingContextLayout) {
226        layout.process_soft_wrap_opportunity();
227        layout.commit_current_segment_to_line();
228        layout.process_line_break(
229            true, /* forced_line_break */
230            true, /* for_block_level */
231        );
232
233        let fragment = layout_block_level_child(
234            layout.layout_context,
235            layout.positioning_context,
236            self,
237            layout.sequential_layout_state.as_deref_mut(),
238            &mut layout.placement_state,
239            layout.ignore_block_margins_for_stretch,
240            true, /* has_inline_parent */
241        );
242
243        let Some(fragment) = fragment.retrieve_box_fragment() else {
244            unreachable!("The fragment should be a Fragment::Box()");
245        };
246
247        // If this Fragment's layout depends on the block size of the containing block,
248        // then the entire layout of the inline formatting context does as well.
249        layout.depends_on_block_constraints |= fragment.base.flags.contains(
250            FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
251        );
252
253        layout.push_line_item_to_unbreakable_segment(LineItem::BlockLevel(
254            layout.current_inline_box_identifier(),
255            fragment.clone(),
256        ));
257
258        layout.commit_current_segment_to_line();
259        layout.process_line_break(
260            true,  /* forced_line_break */
261            false, /* for_block_level */
262        );
263    }
264}
265
266#[derive(Clone, Debug, MallocSizeOf)]
267pub(crate) enum InlineItem {
268    StartInlineBox(ArcRefCell<InlineBox>),
269    EndInlineBox(ArcRefCell<InlineBox>),
270    TextRun(ArcRefCell<TextRun>),
271    OutOfFlowAbsolutelyPositionedBox(
272        ArcRefCell<AbsolutelyPositionedBox>,
273        Utf8CodeUnits, /* offset_in_text */
274    ),
275    OutOfFlowFloatBox(ArcRefCell<FloatBox>),
276    Atomic(
277        ArcRefCell<IndependentFormattingContext>,
278        Utf8CodeUnits, /* offset_in_text */
279        Level,         /* bidi_level */
280    ),
281    BlockLevel(ArcRefCell<BlockLevelBox>),
282}
283
284impl InlineItem {
285    pub(crate) fn repair_style(
286        &self,
287        context: &SharedStyleContext,
288        node: &ServoLayoutNode,
289        new_style: &ServoArc<ComputedValues>,
290    ) {
291        match self {
292            InlineItem::StartInlineBox(inline_box) => {
293                inline_box
294                    .borrow_mut()
295                    .repair_style(context, node, new_style);
296            },
297            InlineItem::EndInlineBox(..) => {},
298            // TextRun holds a handle the `InlineSharedStyles` which is updated when repairing inline box
299            // and `display: contents` styles.
300            InlineItem::TextRun(..) => {},
301            InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => positioned_box
302                .borrow_mut()
303                .context
304                .repair_style(context, node, new_style),
305            InlineItem::OutOfFlowFloatBox(float_box) => float_box
306                .borrow_mut()
307                .contents
308                .repair_style(context, node, new_style),
309            InlineItem::Atomic(atomic, ..) => {
310                atomic.borrow_mut().repair_style(context, node, new_style)
311            },
312            InlineItem::BlockLevel(block_level) => block_level
313                .borrow_mut()
314                .repair_style(context, node, new_style),
315        }
316    }
317
318    pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> T {
319        match self {
320            InlineItem::StartInlineBox(inline_box) => callback(&inline_box.borrow().base),
321            InlineItem::EndInlineBox(..) | InlineItem::TextRun(..) => {
322                unreachable!("Should never have these kind of fragments attached to a DOM node")
323            },
324            InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
325                callback(&positioned_box.borrow().context.base)
326            },
327            InlineItem::OutOfFlowFloatBox(float_box) => callback(&float_box.borrow().contents.base),
328            InlineItem::Atomic(independent_formatting_context, ..) => {
329                callback(&independent_formatting_context.borrow().base)
330            },
331            InlineItem::BlockLevel(block_level) => block_level.borrow().with_base(callback),
332        }
333    }
334
335    pub(crate) fn with_base_mut<T>(&self, callback: impl FnOnce(&mut LayoutBoxBase) -> T) -> T {
336        match self {
337            InlineItem::StartInlineBox(inline_box) => callback(&mut inline_box.borrow_mut().base),
338            InlineItem::EndInlineBox(..) | InlineItem::TextRun(..) => {
339                unreachable!("Should never have these kind of fragments attached to a DOM node")
340            },
341            InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
342                callback(&mut positioned_box.borrow_mut().context.base)
343            },
344            InlineItem::OutOfFlowFloatBox(float_box) => {
345                callback(&mut float_box.borrow_mut().contents.base)
346            },
347            InlineItem::Atomic(independent_formatting_context, ..) => {
348                callback(&mut independent_formatting_context.borrow_mut().base)
349            },
350            InlineItem::BlockLevel(block_level) => block_level.borrow_mut().with_base_mut(callback),
351        }
352    }
353
354    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
355        match self {
356            Self::StartInlineBox(_) | InlineItem::EndInlineBox(..) => {
357                // The parentage of inline items within an inline box is handled when the entire
358                // inline formatting context is attached to the tree.
359            },
360            Self::TextRun(_) => {
361                // Text runs can't have children, so no need to do anything.
362            },
363            Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
364                positioned_box.borrow().context.attached_to_tree(layout_box)
365            },
366            Self::OutOfFlowFloatBox(float_box) => {
367                float_box.borrow().contents.attached_to_tree(layout_box)
368            },
369            Self::Atomic(atomic, ..) => atomic.borrow().attached_to_tree(layout_box),
370            Self::BlockLevel(block_level) => block_level.borrow().attached_to_tree(layout_box),
371        }
372    }
373
374    pub(crate) fn downgrade(&self) -> WeakInlineItem {
375        match self {
376            Self::StartInlineBox(inline_box) => {
377                WeakInlineItem::StartInlineBox(inline_box.downgrade())
378            },
379            Self::EndInlineBox(inline_box) => WeakInlineItem::EndInlineBox(inline_box.downgrade()),
380            Self::TextRun(text_run) => WeakInlineItem::TextRun(text_run.downgrade()),
381            Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, offset_in_text) => {
382                WeakInlineItem::OutOfFlowAbsolutelyPositionedBox(
383                    positioned_box.downgrade(),
384                    *offset_in_text,
385                )
386            },
387            Self::OutOfFlowFloatBox(float_box) => {
388                WeakInlineItem::OutOfFlowFloatBox(float_box.downgrade())
389            },
390            Self::Atomic(atomic, offset_in_text, bidi_level) => {
391                WeakInlineItem::Atomic(atomic.downgrade(), *offset_in_text, *bidi_level)
392            },
393            Self::BlockLevel(block_level) => WeakInlineItem::BlockLevel(block_level.downgrade()),
394        }
395    }
396}
397
398#[derive(Clone, Debug, MallocSizeOf)]
399pub(crate) enum WeakInlineItem {
400    StartInlineBox(WeakRefCell<InlineBox>),
401    EndInlineBox(WeakRefCell<InlineBox>),
402    TextRun(WeakRefCell<TextRun>),
403    OutOfFlowAbsolutelyPositionedBox(
404        WeakRefCell<AbsolutelyPositionedBox>,
405        Utf8CodeUnits, /* offset_in_text */
406    ),
407    OutOfFlowFloatBox(WeakRefCell<FloatBox>),
408    Atomic(
409        WeakRefCell<IndependentFormattingContext>,
410        Utf8CodeUnits, /* offset_in_text */
411        Level,         /* bidi_level */
412    ),
413    BlockLevel(WeakRefCell<BlockLevelBox>),
414}
415
416impl WeakInlineItem {
417    pub(crate) fn upgrade(&self) -> Option<InlineItem> {
418        Some(match self {
419            Self::StartInlineBox(inline_box) => InlineItem::StartInlineBox(inline_box.upgrade()?),
420            Self::EndInlineBox(inline_box) => InlineItem::EndInlineBox(inline_box.upgrade()?),
421            Self::TextRun(text_run) => InlineItem::TextRun(text_run.upgrade()?),
422            Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, offset_in_text) => {
423                InlineItem::OutOfFlowAbsolutelyPositionedBox(
424                    positioned_box.upgrade()?,
425                    *offset_in_text,
426                )
427            },
428            Self::OutOfFlowFloatBox(float_box) => {
429                InlineItem::OutOfFlowFloatBox(float_box.upgrade()?)
430            },
431            Self::Atomic(atomic, offset_in_text, bidi_level) => {
432                InlineItem::Atomic(atomic.upgrade()?, *offset_in_text, *bidi_level)
433            },
434            Self::BlockLevel(block_level) => InlineItem::BlockLevel(block_level.upgrade()?),
435        })
436    }
437}
438
439/// Information about the current line under construction for a particular
440/// [`InlineFormattingContextLayout`]. This tracks position and size information while
441/// [`LineItem`]s are collected and is used as input when those [`LineItem`]s are
442/// converted into [`Fragment`]s during the final phase of line layout. Note that this
443/// does not store the [`LineItem`]s themselves, as they are stored as part of the
444/// nesting state in the [`InlineFormattingContextLayout`].
445struct LineUnderConstruction {
446    /// The position where this line will start once it is laid out. This includes any
447    /// offset from `text-indent`.
448    start_position: LogicalVec2<Au>,
449
450    /// The current inline position in the line being laid out into [`LineItem`]s in this
451    /// [`InlineFormattingContext`] independent of the depth in the nesting level.
452    inline_position: Au,
453
454    /// The maximum block size of all boxes that ended and are in progress in this line.
455    /// This uses [`LineBlockSizes`] instead of a simple value, because the final block size
456    /// depends on vertical alignment.
457    max_block_size: LineBlockSizes,
458
459    /// Whether any active linebox has added a glyph or atomic element to this line, which
460    /// indicates that the next run that exceeds the line length can cause a line break.
461    has_content: bool,
462
463    /// Whether or not there are floats that did not fit on the current line. Before
464    /// the [`LineItem`]s of this line are laid out, these floats will need to be
465    /// placed directly below this line, but still as children of this line's Fragments.
466    has_floats_waiting_to_be_placed: bool,
467
468    /// A rectangular area (relative to the containing block / inline formatting
469    /// context boundaries) where we can fit the line box without overlapping floats.
470    /// Note that when this is not empty, its start corner takes precedence over
471    /// [`LineUnderConstruction::start_position`].
472    placement_among_floats: OnceCell<LogicalRect<Au>>,
473
474    /// The LineItems for the current line under construction that have already
475    /// been committed to this line.
476    line_items: Vec<LineItem>,
477
478    /// Whether the current line is for a block-level box.
479    for_block_level: bool,
480
481    /// If this line is empty and contains a selection, this field will be used to create
482    /// an empty [`TextFragment`] for holding a text caret.
483    caret_placeholder: Option<CaretPlaceholder>,
484
485    /// The amount of space that will be taken up by all inline padding, borders and
486    /// margins of all inline boxes with `box-decoration-break: clone` that we are
487    /// currently inside of.
488    cloneable_inline_box_pbm_size: LogicalSides1D<Au>,
489
490    /// The inline size of any trailing hangable white space in this line.
491    trailing_hangable_white_space: Au,
492
493    /// The inline size of any trailing removable white space in this line.
494    trailing_removable_white_space: Au,
495}
496
497impl LineUnderConstruction {
498    fn new(start_position: LogicalVec2<Au>) -> Self {
499        Self {
500            inline_position: start_position.inline,
501            start_position,
502            max_block_size: LineBlockSizes::zero(),
503            has_content: false,
504            has_floats_waiting_to_be_placed: false,
505            placement_among_floats: OnceCell::new(),
506            line_items: Vec::new(),
507            for_block_level: false,
508            caret_placeholder: None,
509            cloneable_inline_box_pbm_size: Default::default(),
510            trailing_hangable_white_space: Au::zero(),
511            trailing_removable_white_space: Au::zero(),
512        }
513    }
514
515    fn replace_placement_among_floats(&mut self, new_placement: LogicalRect<Au>) {
516        self.placement_among_floats.take();
517        let _ = self.placement_among_floats.set(new_placement);
518    }
519
520    /// Trim the trailing removable white space in this line, returning the amount of
521    /// white space that hangs.
522    ///
523    /// This is <https://www.w3.org/TR/css-text-3/#white-space-phase-2> steps 3 and 4.
524    ///
525    /// > - Step 3. A sequence of collapsible spaces at the end of a line is removed, as well
526    /// >   as any trailing U+1680 OGHAM SPACE MARK whose white-space property is normal,
527    /// >   nowrap, or pre-line.
528    /// > - Step 4. If there remains any sequence of white space, other space separators,
529    /// >   and/or preserved tabs at the end of a line (after bidi reordering
530    /// >   [CSS-WRITING-MODES-4]):
531    /// >     * If white-space is set to normal, nowrap, or pre-line, the UA must hang this
532    /// >       sequence (unconditionally).
533    /// >     * If white-space is set to pre-wrap, the UA must (unconditionally) hang this
534    /// >       sequence, unless the sequence is followed by a forced line break, in which case it
535    /// >       must conditionally hang the sequence instead. It may also visually collapse the
536    /// >       character advance widths of any that would otherwise overflow.
537    /// >    * If white-space is set to break-spaces, spaces, tabs, and other space separators
538    /// >      are treated the same as other visible characters: they cannot hang nor have their
539    /// >      advance width collapsed.
540    fn trim_trailing_white_space_and_calculate_hanging(
541        &mut self,
542        available_inline_size: Au,
543        last_line_or_forced_line_break: bool,
544    ) -> Au {
545        let mut conditionally_hanging = Au::zero();
546        let mut unconditionally_hanging = Au::zero();
547        let mut removed = Au::zero();
548        let mut white_space_still_hanging_conditionally = last_line_or_forced_line_break;
549
550        for item in self.line_items.iter_mut().rev() {
551            let text_run = match item {
552                LineItem::InlineStartBoxPaddingBorderMargin(_) |
553                LineItem::InlineEndBoxPaddingBorderMargin(_) |
554                LineItem::Float(..) |
555                LineItem::AbsolutelyPositioned(..) => continue,
556                LineItem::Atomic(..) | LineItem::BlockLevel(..) => break,
557                LineItem::Tab {
558                    conditionally_hangs,
559                    advance,
560                    ..
561                } => {
562                    if !*conditionally_hangs {
563                        break;
564                    }
565
566                    if white_space_still_hanging_conditionally {
567                        conditionally_hanging += *advance;
568                    } else {
569                        unconditionally_hanging += *advance;
570                    }
571
572                    continue;
573                },
574                LineItem::TextRun(_, text_run) => text_run,
575            };
576
577            let (mut count, preceded_by_content) = text_run.trailing_white_space();
578            if conditionally_hanging.is_zero() && unconditionally_hanging.is_zero() {
579                text_run.trim_removable_white_space_at_end();
580                removed += count.removable;
581            } else {
582                count.hangable += count.removable;
583            }
584
585            let style = text_run.text_fragment_run_data.inline_styles.style.borrow();
586            if white_space_still_hanging_conditionally && style.white_space_may_hang_conditionally()
587            {
588                conditionally_hanging += count.hangable;
589            } else {
590                white_space_still_hanging_conditionally = false;
591                unconditionally_hanging += count.hangable;
592            }
593
594            if preceded_by_content {
595                break;
596            }
597        }
598
599        self.trailing_removable_white_space = Au::zero();
600        self.inline_position -= removed;
601
602        if !last_line_or_forced_line_break {
603            return unconditionally_hanging + conditionally_hanging;
604        }
605
606        let overflow = (self.inline_position - available_inline_size).max(Au::zero());
607        if overflow < conditionally_hanging {
608            overflow
609        } else {
610            unconditionally_hanging + conditionally_hanging
611        }
612    }
613
614    /// Count the number of justification opportunities in this line.
615    fn count_justification_opportunities(&self) -> usize {
616        let mut saw_content = false;
617        self.line_items
618            .iter()
619            .rev()
620            .filter_map(|item| match item {
621                LineItem::TextRun(_, text_run) => Some(
622                    text_run
623                        .text
624                        .iter()
625                        .rev()
626                        .map(|shaped_text_slice| {
627                            let mut word_separators = shaped_text_slice.total_word_separators();
628                            if !saw_content {
629                                word_separators -=
630                                    shaped_text_slice.hanging_and_removable_word_separators();
631                            }
632                            saw_content |=
633                                shaped_text_slice.has_non_hangable_non_removable_content();
634                            word_separators
635                        })
636                        .sum::<usize>(),
637                ),
638                LineItem::Atomic(..) | LineItem::Tab { .. } => {
639                    saw_content = true;
640                    None
641                },
642                _ => None,
643            })
644            .sum()
645    }
646
647    /// Whether this is a phantom line box.
648    /// <https://drafts.csswg.org/css-inline-3/#invisible-line-boxes>
649    fn is_phantom(&self) -> bool {
650        Self::is_phantom_inner(self.has_content, &self.line_items)
651    }
652
653    fn is_phantom_inner(has_content: bool, line_items: &[LineItem]) -> bool {
654        if has_content {
655            return false;
656        }
657
658        // If the line has no content it might have padding, border, or margin
659        // added by inline boxes.
660        !line_items.iter().any(|item| match item {
661            LineItem::InlineStartBoxPaddingBorderMargin(state) => state.has_pbm_inline_start(),
662            LineItem::InlineEndBoxPaddingBorderMargin(state) => state.has_pbm_inline_end(),
663            _ => false,
664        })
665    }
666
667    /// The advance of the whitespace at the end of this line that would either hang
668    /// or be trimmed if it was at the end of a line.
669    ///
670    /// Note: This is only valid during line construction, because it doesn't take
671    /// into account conditional hanging.
672    fn tentative_hanging_and_removable_white_space_advance(&self) -> Au {
673        self.trailing_hangable_white_space + self.trailing_removable_white_space
674    }
675}
676
677/// A block size relative to a line's final baseline. This is to track the size
678/// contribution of a particular element of a line above and below the baseline.
679/// These sizes can be combined with other baseline relative sizes before the
680/// final baseline position is known. The values here are relative to the
681/// overall line's baseline and *not* the nested baseline of an inline box.
682#[derive(Clone, Debug)]
683struct BaselineRelativeSize {
684    /// The ascent above the baseline, where a positive value means a larger
685    /// ascent. Thus, the top of this size contribution is `baseline_offset -
686    /// ascent`.
687    ascent: Au,
688
689    /// The descent below the baseline, where a positive value means a larger
690    /// descent. Thus, the bottom of this size contribution is `baseline_offset +
691    /// descent`.
692    descent: Au,
693}
694
695impl BaselineRelativeSize {
696    fn zero() -> Self {
697        Self {
698            ascent: Au::zero(),
699            descent: Au::zero(),
700        }
701    }
702
703    fn max(&self, other: &Self) -> Self {
704        BaselineRelativeSize {
705            ascent: self.ascent.max(other.ascent),
706            descent: self.descent.max(other.descent),
707        }
708    }
709
710    /// Given an offset from the line's root baseline, adjust this [`BaselineRelativeSize`]
711    /// by that offset. This is used to adjust a [`BaselineRelativeSize`] for different kinds
712    /// of baseline-relative `vertical-align`. This will "move" measured size of a particular
713    /// inline box's block size. For example, in the following HTML:
714    ///
715    /// ```html
716    ///     <div>
717    ///         <span style="vertical-align: 5px">child content</span>
718    ///     </div>
719    /// ````
720    ///
721    /// If this [`BaselineRelativeSize`] is for the `<span>` then the adjustment
722    /// passed here would be equivalent to -5px.
723    fn adjust_for_nested_baseline_offset(&mut self, baseline_offset: Au) {
724        self.ascent -= baseline_offset;
725        self.descent += baseline_offset;
726    }
727}
728
729#[derive(Clone, Debug)]
730struct LineBlockSizes {
731    line_height: Au,
732    baseline_relative_size_for_line_height: Option<BaselineRelativeSize>,
733    size_for_baseline_positioning: BaselineRelativeSize,
734}
735
736impl LineBlockSizes {
737    fn zero() -> Self {
738        LineBlockSizes {
739            line_height: Au::zero(),
740            baseline_relative_size_for_line_height: None,
741            size_for_baseline_positioning: BaselineRelativeSize::zero(),
742        }
743    }
744
745    fn resolve(&self) -> Au {
746        let height_from_ascent_and_descent = self
747            .baseline_relative_size_for_line_height
748            .as_ref()
749            .map(|size| (size.ascent + size.descent).abs())
750            .unwrap_or_else(Au::zero);
751        self.line_height.max(height_from_ascent_and_descent)
752    }
753
754    fn max(&self, other: &LineBlockSizes) -> LineBlockSizes {
755        let baseline_relative_size = match (
756            self.baseline_relative_size_for_line_height.as_ref(),
757            other.baseline_relative_size_for_line_height.as_ref(),
758        ) {
759            (Some(our_size), Some(other_size)) => Some(our_size.max(other_size)),
760            (our_size, other_size) => our_size.or(other_size).cloned(),
761        };
762        Self {
763            line_height: self.line_height.max(other.line_height),
764            baseline_relative_size_for_line_height: baseline_relative_size,
765            size_for_baseline_positioning: self
766                .size_for_baseline_positioning
767                .max(&other.size_for_baseline_positioning),
768        }
769    }
770
771    fn max_assign(&mut self, other: &LineBlockSizes) {
772        *self = self.max(other);
773    }
774
775    fn adjust_for_baseline_offset(&mut self, baseline_offset: Au) {
776        if let Some(size) = self.baseline_relative_size_for_line_height.as_mut() {
777            size.adjust_for_nested_baseline_offset(baseline_offset)
778        }
779        self.size_for_baseline_positioning
780            .adjust_for_nested_baseline_offset(baseline_offset);
781    }
782
783    /// From <https://drafts.csswg.org/css2/visudet.html#line-height>:
784    ///  > The inline-level boxes are aligned vertically according to their 'vertical-align'
785    ///  > property. In case they are aligned 'top' or 'bottom', they must be aligned so as
786    ///  > to minimize the line box height. If such boxes are tall enough, there are multiple
787    ///  > solutions and CSS 2 does not define the position of the line box's baseline (i.e.,
788    ///  > the position of the strut, see below).
789    fn find_baseline_offset(&self) -> Au {
790        match self.baseline_relative_size_for_line_height.as_ref() {
791            Some(size) => size.ascent,
792            None => {
793                // This is the case mentinoned above where there are multiple solutions.
794                // This code is putting the baseline roughly in the middle of the line.
795                let leading = self.resolve() -
796                    (self.size_for_baseline_positioning.ascent +
797                        self.size_for_baseline_positioning.descent);
798                leading.scale_by(0.5) + self.size_for_baseline_positioning.ascent
799            },
800        }
801    }
802}
803
804/// The current unbreakable segment under construction for an inline formatting context.
805/// Items accumulate here until we reach a soft line break opportunity during processing
806/// of inline content or we reach the end of the formatting context.
807struct UnbreakableSegmentUnderConstruction {
808    /// The size of this unbreakable segment in both dimension.
809    inline_size: Au,
810
811    /// The maximum block size that this segment has. This uses [`LineBlockSizes`] instead of a
812    /// simple value, because the final block size depends on vertical alignment.
813    max_block_size: LineBlockSizes,
814
815    /// The LineItems for the segment under construction
816    line_items: Vec<LineItem>,
817
818    /// Whether any active linebox has added a glyph or atomic element to this line
819    /// segment, which indicates that the next run that exceeds the line length can cause
820    /// a line break.
821    has_content: bool,
822
823    /// Whether or not this segment incorporates the trailing white space that came before
824    /// it on the line into the line's content.
825    incorporates_trailing_white_space: bool,
826
827    /// The inline size of any trailing hangable white space in this segment.
828    trailing_hangable_white_space: Au,
829
830    /// The inline size of any trailing removable white space in this segment.
831    trailing_removable_white_space: Au,
832}
833
834impl UnbreakableSegmentUnderConstruction {
835    fn new() -> Self {
836        Self {
837            inline_size: Au::zero(),
838            max_block_size: LineBlockSizes {
839                line_height: Au::zero(),
840                baseline_relative_size_for_line_height: None,
841                size_for_baseline_positioning: BaselineRelativeSize::zero(),
842            },
843            line_items: Vec::new(),
844            has_content: false,
845            trailing_hangable_white_space: Au::zero(),
846            trailing_removable_white_space: Au::zero(),
847            incorporates_trailing_white_space: false,
848        }
849    }
850
851    /// Reset this segment after its contents have been committed to a line.
852    fn reset(&mut self) {
853        assert!(self.line_items.is_empty()); // Preserve allocated memory.
854        self.inline_size = Au::zero();
855        self.max_block_size = LineBlockSizes::zero();
856        self.has_content = false;
857        self.trailing_hangable_white_space = Au::zero();
858        self.trailing_removable_white_space = Au::zero();
859        self.incorporates_trailing_white_space = false;
860    }
861
862    /// Push a single line item to this segment.
863    fn push_line_item(&mut self, line_item: LineItem) {
864        self.line_items.push(line_item);
865    }
866
867    /// Trim whitespace from the beginning of this UnbreakbleSegmentUnderConstruction.
868    ///
869    /// From <https://www.w3.org/TR/css-text-3/#white-space-phase-2>:
870    ///
871    /// > Then, the entire block is rendered. Inlines are laid out, taking bidi
872    /// > reordering into account, and wrapping as specified by the text-wrap
873    /// > property. As each line is laid out,
874    /// >  1. A sequence of collapsible spaces at the beginning of a line is removed.
875    ///
876    /// This prevents whitespace from being added to the beginning of a line.
877    fn trim_leading_whitespace(&mut self) {
878        let mut whitespace_trimmed = Au::zero();
879        for item in self.line_items.iter_mut() {
880            if !item.trim_whitespace_at_start(&mut whitespace_trimmed) {
881                break;
882            }
883        }
884        self.inline_size -= whitespace_trimmed;
885
886        // If there is no content in this segment, then trimming the leading whitespace may have
887        // also trimmed some of the trailing white space, so we need to adjust those lengths as
888        // well.
889        if !self.incorporates_trailing_white_space {
890            let trimmed_from_hanging = whitespace_trimmed.min(self.trailing_hangable_white_space);
891            self.trailing_hangable_white_space -= trimmed_from_hanging;
892            self.trailing_removable_white_space -= whitespace_trimmed - trimmed_from_hanging;
893        }
894    }
895
896    /// Whether this is segment is phantom. If false, its line box won't be phantom.
897    /// <https://drafts.csswg.org/css-inline-3/#invisible-line-boxes>
898    fn is_phantom(&self) -> bool {
899        LineUnderConstruction::is_phantom_inner(self.has_content, &self.line_items)
900    }
901
902    /// The size of the inline padding, border, and margin start edge of all trailing
903    /// opening inline boxes on this segment. In addition, if those inline boxes will
904    /// clone their box decorations, include the size of the cloned end padding, border,
905    /// and margin as well.
906    fn trailing_inline_box_start_size(&self) -> Au {
907        self.line_items
908            .iter()
909            .rev()
910            .map_while(|item| match item {
911                LineItem::InlineStartBoxPaddingBorderMargin(state) => Some(state),
912                _ => None,
913            })
914            .map(|state| {
915                if state.should_clone_pbm() {
916                    state.pbm_inline_start() + state.pbm_inline_end()
917                } else {
918                    state.pbm_inline_start()
919                }
920            })
921            .sum()
922    }
923
924    /// The advance of the whitespace at the end of this segment that would either hang
925    /// or be trimmed if it was at the end of a line.
926    fn hanging_and_removable_white_space_advance(&self) -> Au {
927        self.trailing_hangable_white_space + self.trailing_removable_white_space
928    }
929}
930
931bitflags! {
932    pub(super) struct InlineContainerStateFlags: u8 {
933        const CREATE_STRUT = 0b0001;
934        const IS_SINGLE_LINE_TEXT_INPUT = 0b0010;
935    }
936}
937
938struct InlineContainerState {
939    /// The style of this inline container.
940    style: ServoArc<ComputedValues>,
941
942    /// Flags which describe details of this [`InlineContainerState`].
943    flags: InlineContainerStateFlags,
944
945    /// Whether or not we have processed any content (an atomic element or text) for
946    /// this inline box on the current line OR any previous line.
947    has_content: Cell<bool>,
948
949    /// The block size contribution of this container's default font ie the size of the
950    /// "strut." Whether this is integrated into the [`Self::nested_strut_block_sizes`]
951    /// depends on the line-height quirk described in
952    /// <https://quirks.spec.whatwg.org/#the-line-height-calculation-quirk>.
953    strut_block_sizes: LineBlockSizes,
954
955    /// The strut block size of this inline container maxed with the strut block
956    /// sizes of all inline container ancestors. In quirks mode, this will be
957    /// zero, until we know that an element has inline content.
958    nested_strut_block_sizes: LineBlockSizes,
959
960    /// The baseline offset of this container from the baseline of the line. The is the
961    /// cumulative offset of this container and all of its parents. In contrast to the
962    /// `vertical-align` property a positive value indicates an offset "below" the
963    /// baseline while a negative value indicates one "above" it (when the block direction
964    /// is vertical).
965    pub baseline_offset: Au,
966
967    /// The primary font used for this container, if one exists. This is the font that is
968    /// used when not falling back.
969    default_font: Option<FontRef>,
970
971    /// The font metrics of the non-fallback font for this container.
972    font_metrics: Arc<FontMetrics>,
973}
974
975struct InlineFormattingContextLayout<'layout_data> {
976    positioning_context: &'layout_data mut PositioningContext,
977    placement_state: PlacementState<'layout_data>,
978    sequential_layout_state: Option<&'layout_data mut SequentialLayoutState>,
979    layout_context: &'layout_data LayoutContext<'layout_data>,
980
981    /// The [`InlineFormattingContext`] that we are laying out.
982    ifc: &'layout_data InlineFormattingContext,
983
984    /// The [`InlineContainerState`] for the container formed by the root of the
985    /// [`InlineFormattingContext`]. This is effectively the "root inline box" described
986    /// by <https://drafts.csswg.org/css-inline/#model>:
987    ///
988    /// > The block container also generates a root inline box, which is an anonymous
989    /// > inline box that holds all of its inline-level contents. (Thus, all text in an
990    /// > inline formatting context is directly contained by an inline box, whether the root
991    /// > inline box or one of its descendants.) The root inline box inherits from its
992    /// > parent block container, but is otherwise unstyleable.
993    root_nesting_level: InlineContainerState,
994
995    /// A stack of [`InlineBoxContainerState`] that is used to produce [`LineItem`]s either when we
996    /// reach the end of an inline box or when we reach the end of a line. Only at the end
997    /// of the inline box is the state popped from the stack.
998    inline_box_state_stack: Vec<Rc<InlineBoxContainerState>>,
999
1000    /// The amount of space that will be taken up by all inline padding, borders and
1001    /// margins of all inline boxes with `box-decoration-break: clone` that we are
1002    /// currently inside of.
1003    cloneable_inline_box_pbm_size: LogicalSides1D<Au>,
1004
1005    /// A collection of [`InlineBoxContainerState`] of all the inlines that are present
1006    /// in this inline formatting context. We keep this as well as the stack, so that we
1007    /// can access them during line layout, which may happen after relevant [`InlineBoxContainerState`]s
1008    /// have been popped of the stack.
1009    inline_box_states: Vec<Rc<InlineBoxContainerState>>,
1010
1011    /// A vector of fragment that are laid out. This includes one [`Fragment::Positioning`]
1012    /// per line that is currently laid out plus fragments for all floats, which
1013    /// are currently laid out at the top-level of each [`InlineFormattingContext`].
1014    fragments: Vec<Fragment>,
1015
1016    /// Information about the line currently being laid out into [`LineItem`]s.
1017    current_line: LineUnderConstruction,
1018
1019    /// Information about the unbreakable line segment currently being laid out into [`LineItem`]s.
1020    current_line_segment: UnbreakableSegmentUnderConstruction,
1021
1022    /// After a forced line break (for instance from a `<br>` element) we wait to actually
1023    /// break the line until seeing more content. This allows ongoing inline boxes to finish,
1024    /// since in the case where they have no more content they should not be on the next
1025    /// line.
1026    ///
1027    /// For instance:
1028    ///
1029    /// ``` html
1030    ///    <span style="border-right: 30px solid blue;">
1031    ///         first line<br>
1032    ///    </span>
1033    ///    second line
1034    /// ```
1035    ///
1036    /// In this case, the `<span>` should not extend to the second line. If we linebreak
1037    /// as soon as we encounter the `<br>` the `<span>`'s ending inline borders would be
1038    /// placed on the second line, because we add those borders in
1039    /// [`InlineFormattingContextLayout::finish_inline_box()`].
1040    ///
1041    /// If this field is `true`, a hard line break should be processed before any new content.
1042    force_line_break_before_new_content: bool,
1043
1044    /// When deferring a forced line break, this field stores a potential caret placeholder
1045    /// used to create a [`TextFragment`] to hold a caret on an otherwise empty line.
1046    caret_placeholder: Option<CaretPlaceholder>,
1047
1048    /// When a `<br>` element has `clear`, this needs to be applied after the linebreak,
1049    /// which will be processed *after* the `<br>` element is processed. This member
1050    /// stores any deferred `clear` to apply after a linebreak.
1051    deferred_br_clear: Clear,
1052
1053    /// Whether or not a soft wrap opportunity is queued. Soft wrap opportunities are
1054    /// queued after replaced content and they are processed when the next text content
1055    /// is encountered.
1056    pub have_deferred_soft_wrap_opportunity: bool,
1057
1058    /// Whether or not the layout of this InlineFormattingContext depends on the block size
1059    /// of its container for the purposes of flexbox layout.
1060    depends_on_block_constraints: bool,
1061
1062    /// The currently white-space-collapse setting of this line. This is stored on the
1063    /// [`InlineFormattingContextLayout`] because when a soft wrap opportunity is defined
1064    /// by the boundary between two characters, the white-space-collapse property of their
1065    /// nearest common ancestor is used.
1066    white_space_collapse: WhiteSpaceCollapse,
1067
1068    /// The currently text-wrap-mode setting of this line. This is stored on the
1069    /// [`InlineFormattingContextLayout`] because when a soft wrap opportunity is defined
1070    /// by the boundary between two characters, the text-wrap-mode property of their nearest
1071    /// common ancestor is used.
1072    text_wrap_mode: TextWrapMode,
1073
1074    /// Whether block-level boxes inside this inline formatting context should ignore their
1075    /// margins for the purpose of stretching in the block axis.
1076    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1077}
1078
1079impl InlineFormattingContextLayout<'_> {
1080    fn current_inline_container_state(&self) -> &InlineContainerState {
1081        match self.inline_box_state_stack.last() {
1082            Some(inline_box_state) => &inline_box_state.base,
1083            None => &self.root_nesting_level,
1084        }
1085    }
1086
1087    fn current_inline_box_identifier(&self) -> Option<InlineBoxIdentifier> {
1088        self.inline_box_state_stack
1089            .last()
1090            .map(|state| state.identifier)
1091    }
1092
1093    fn current_line_max_block_size_including_nested_containers(&self) -> LineBlockSizes {
1094        self.current_inline_container_state()
1095            .nested_strut_block_sizes
1096            .max(&self.current_line.max_block_size)
1097    }
1098
1099    fn current_line_block_start_considering_placement_among_floats(&self) -> Au {
1100        self.current_line.placement_among_floats.get().map_or(
1101            self.current_line.start_position.block,
1102            |placement_among_floats| placement_among_floats.start_corner.block,
1103        )
1104    }
1105
1106    fn propagate_current_nesting_level_white_space_style(&mut self) {
1107        let style = match self.inline_box_state_stack.last() {
1108            Some(inline_box_state) => &inline_box_state.base.style,
1109            None => self.placement_state.containing_block.style,
1110        };
1111        let style_text = style.get_inherited_text();
1112        self.white_space_collapse = style_text.white_space_collapse;
1113        self.text_wrap_mode = style_text.text_wrap_mode;
1114    }
1115
1116    fn processing_br_element(&self) -> bool {
1117        self.inline_box_state_stack.last().is_some_and(|state| {
1118            state
1119                .base_fragment_info
1120                .flags
1121                .contains(FragmentFlags::IS_BR_ELEMENT)
1122        })
1123    }
1124
1125    /// Start laying out a particular [`InlineBox`] into line items. This will push
1126    /// a new [`InlineBoxContainerState`] onto [`Self::inline_box_state_stack`].
1127    fn start_inline_box(&mut self, inline_box: &InlineBox) {
1128        let containing_block = self.containing_block();
1129        let inline_box_state = InlineBoxContainerState::new(
1130            inline_box,
1131            containing_block,
1132            self.layout_context,
1133            self.current_inline_container_state(),
1134            inline_box.default_font.clone(),
1135        );
1136
1137        self.depends_on_block_constraints |= inline_box
1138            .base
1139            .style
1140            .depends_on_block_constraints_due_to_relative_positioning(
1141                containing_block.style.writing_mode,
1142            );
1143
1144        // If we are starting a `<br>` element prepare to clear after its deferred linebreak has been
1145        // processed. Note that a `<br>` is composed of the element itself and the inner pseudo-element
1146        // with the actual linebreak. Both will have this `FragmentFlag`; that's why this code only
1147        // sets `deferred_br_clear` if it isn't set yet.
1148        if inline_box_state
1149            .base_fragment_info
1150            .flags
1151            .contains(FragmentFlags::IS_BR_ELEMENT) &&
1152            self.deferred_br_clear == Clear::None
1153        {
1154            self.deferred_br_clear = Clear::from_style_and_container_writing_mode(
1155                &inline_box_state.base.style,
1156                self.containing_block().style.writing_mode,
1157            );
1158        }
1159
1160        let inline_box_state = Rc::new(inline_box_state);
1161        let pbm_inline_start = inline_box_state.pbm_inline_start();
1162        self.current_line_segment.inline_size += pbm_inline_start;
1163
1164        if inline_box_state.should_clone_pbm() {
1165            self.cloneable_inline_box_pbm_size.start += pbm_inline_start;
1166            self.cloneable_inline_box_pbm_size.end += inline_box_state.pbm_inline_end();
1167        }
1168
1169        self.current_line_segment
1170            .line_items
1171            .push(LineItem::InlineStartBoxPaddingBorderMargin(
1172                inline_box_state.clone(),
1173            ));
1174
1175        // Push the state onto the IFC-wide collection of states. Inline boxes are numbered in
1176        // the order that they are encountered, so this should correspond to the order they
1177        // are pushed onto `self.inline_box_states`.
1178        assert_eq!(
1179            self.inline_box_states.len(),
1180            inline_box.identifier.index_in_inline_boxes as usize
1181        );
1182        self.inline_box_states.push(inline_box_state.clone());
1183        self.inline_box_state_stack.push(inline_box_state);
1184    }
1185
1186    /// Finish laying out a particular [`InlineBox`] into line items. This will
1187    /// pop its state off of [`Self::inline_box_state_stack`].
1188    fn finish_inline_box(&mut self) {
1189        let inline_box_state = match self.inline_box_state_stack.pop() {
1190            Some(inline_box_state) => inline_box_state,
1191            None => return, // We are at the root.
1192        };
1193
1194        self.current_line_segment
1195            .max_block_size
1196            .max_assign(&inline_box_state.base.nested_strut_block_sizes);
1197
1198        // If the inline box that we just finished had any content at all, we want to propagate
1199        // the `white-space` property of its parent to future inline children. This is because
1200        // when a soft wrap opportunity is defined by the boundary between two elements, the
1201        // `white-space` used is that of their nearest common ancestor.
1202        if inline_box_state.base.has_content.get() {
1203            self.propagate_current_nesting_level_white_space_style();
1204        }
1205
1206        let pbm_inline_end = inline_box_state.pbm_inline_end();
1207        self.current_line_segment.inline_size += pbm_inline_end;
1208
1209        if inline_box_state.should_clone_pbm() {
1210            self.cloneable_inline_box_pbm_size.start -= inline_box_state.pbm_inline_start();
1211            self.cloneable_inline_box_pbm_size.end -= pbm_inline_end;
1212        }
1213
1214        self.current_line_segment
1215            .line_items
1216            .push(LineItem::InlineEndBoxPaddingBorderMargin(inline_box_state));
1217    }
1218
1219    fn finish_last_line(&mut self) {
1220        // First, process any deferred forced line breaks.
1221        self.possibly_flush_deferred_forced_line_break();
1222
1223        // We are at the end of the IFC, and we need to do a few things to make sure that
1224        // the current segment is committed and that the final line is finished.
1225        //
1226        // A soft wrap opportunity makes it so the current segment is placed on a new line
1227        // if it doesn't fit on the current line under construction.
1228        self.process_soft_wrap_opportunity();
1229
1230        // `process_soft_line_wrap_opportunity` does not commit the segment to a line if
1231        // there is no line wrapping, so this forces the segment into the current line.
1232        self.commit_current_segment_to_line();
1233
1234        // Finally we finish the line itself and convert all of the LineItems into
1235        // fragments.
1236        self.finish_current_line_and_reset(
1237            true,  /* last_line_or_forced_line_break */
1238            false, /* for_block_level */
1239        );
1240    }
1241
1242    /// Finish layout of all inline boxes for the current line. This will gather all
1243    /// [`LineItem`]s and turn them into [`Fragment`]s, then reset the
1244    /// [`InlineFormattingContextLayout`] preparing it for laying out a new line.
1245    fn finish_current_line_and_reset(
1246        &mut self,
1247        last_line_or_forced_line_break: bool,
1248        for_block_level: bool,
1249    ) {
1250        let hanging_white_space = self
1251            .current_line
1252            .trim_trailing_white_space_and_calculate_hanging(
1253                self.available_line_space(),
1254                last_line_or_forced_line_break,
1255            );
1256
1257        self.possibly_push_empty_text_run_to_line_for_text_caret();
1258
1259        // Add space for any cloneable padding, border, and margin ends that will
1260        // be drawn for this line.
1261        if !self.current_line.for_block_level {
1262            self.current_line.inline_position +=
1263                self.current_line.cloneable_inline_box_pbm_size.end;
1264        }
1265
1266        let (inline_start_position, justification_adjustment) = self
1267            .calculate_current_line_inline_start_and_justification_adjustment(
1268                hanging_white_space,
1269                last_line_or_forced_line_break,
1270            );
1271
1272        // https://drafts.csswg.org/css-inline-3/#invisible-line-boxes
1273        // > Line boxes that contain no text, no preserved white space, no inline boxes with non-zero
1274        // > inline-axis margins, padding, or borders, and no other in-flow content (such as atomic
1275        // > inlines or ruby annotations), and do not end with a forced line break are phantom line boxes.
1276        // > Such boxes must be treated as zero-height line boxes for the purposes of determining the
1277        // > positions of any descendant content (such as absolutely positioned boxes), and both the
1278        // > line box and its in-flow content must be treated as not existing for any other layout or
1279        // > rendering purpose.
1280        let is_phantom_line = self.current_line.is_phantom();
1281        if !is_phantom_line {
1282            self.current_line.start_position.block += self.placement_state.current_margin.solve();
1283            self.placement_state.current_margin = CollapsedMargin::zero();
1284        }
1285        let block_start_position =
1286            self.current_line_block_start_considering_placement_among_floats();
1287
1288        let effective_block_advance = if is_phantom_line {
1289            LineBlockSizes::zero()
1290        } else {
1291            self.current_line_max_block_size_including_nested_containers()
1292        };
1293
1294        let resolved_block_advance = effective_block_advance.resolve();
1295        let block_end_position = if self.current_line.for_block_level {
1296            self.placement_state.current_block_direction_position
1297        } else {
1298            let mut block_end_position = block_start_position + resolved_block_advance;
1299            if let Some(sequential_layout_state) = self.sequential_layout_state.as_mut() {
1300                if !is_phantom_line {
1301                    sequential_layout_state.commit_margin();
1302                }
1303
1304                // This amount includes both the block size of the line and any extra space
1305                // added to move the line down in order to avoid overlapping floats.
1306                let increment = block_end_position - self.current_line.start_position.block;
1307                sequential_layout_state.advance_block_position(increment);
1308
1309                // This newline may have been triggered by a `<br>` with clearance, in which case we
1310                // want to make sure that we make space not only for the current line, but any clearance
1311                // from floats.
1312                if let Some(clearance) = sequential_layout_state
1313                    .calculate_clearance(self.deferred_br_clear, &CollapsedMargin::zero())
1314                {
1315                    sequential_layout_state.advance_block_position(clearance);
1316                    block_end_position += clearance;
1317                };
1318                self.deferred_br_clear = Clear::None;
1319            }
1320            block_end_position
1321        };
1322
1323        // Set up the new line now that we no longer need the old one.
1324        let line_to_layout = std::mem::replace(
1325            &mut self.current_line,
1326            LineUnderConstruction::new(LogicalVec2 {
1327                inline: Au::zero(),
1328                block: block_end_position,
1329            }),
1330        );
1331        self.current_line.for_block_level = for_block_level;
1332
1333        // Preserve the current state of the cloneable inline box PBM size.
1334        self.current_line.cloneable_inline_box_pbm_size =
1335            line_to_layout.cloneable_inline_box_pbm_size;
1336        // Reserve space for any cloned inline box starts that will be added to the new line, but
1337        // only if this is not for a block level.
1338        if !self.current_line.for_block_level {
1339            self.current_line.inline_position +=
1340                self.current_line.cloneable_inline_box_pbm_size.start;
1341        }
1342
1343        if !line_to_layout.for_block_level {
1344            self.placement_state.current_block_direction_position = block_end_position;
1345        }
1346
1347        if line_to_layout.has_floats_waiting_to_be_placed {
1348            place_pending_floats(self, &line_to_layout.line_items);
1349        }
1350
1351        let start_position = LogicalVec2 {
1352            block: block_start_position,
1353            inline: inline_start_position,
1354        };
1355
1356        let baseline_offset = effective_block_advance.find_baseline_offset();
1357        let start_positioning_context_length = self.positioning_context.len();
1358        let fragments = LineItemLayout::layout_line_items(
1359            self,
1360            line_to_layout.line_items,
1361            start_position,
1362            &effective_block_advance,
1363            justification_adjustment,
1364            is_phantom_line,
1365            line_to_layout.for_block_level,
1366        );
1367
1368        if !is_phantom_line {
1369            let baseline = baseline_offset + block_start_position;
1370            self.placement_state
1371                .inflow_baselines
1372                .first
1373                .get_or_insert(baseline);
1374            self.placement_state.inflow_baselines.last = Some(baseline);
1375            self.placement_state
1376                .next_in_flow_margin_collapses_with_parent_start_margin = false;
1377        }
1378
1379        // If the line doesn't have any fragments, we don't need to add a containing fragment for it.
1380        if fragments.is_empty() &&
1381            self.positioning_context.len() == start_positioning_context_length
1382        {
1383            return;
1384        }
1385
1386        // The inline part of this start offset was taken into account when determining
1387        // the inline start of the line in `calculate_inline_start_for_current_line` so
1388        // we do not need to include it in the `start_corner` of the line's main Fragment.
1389        let containing_block = self.containing_block();
1390        let containing_block_writing_mode = containing_block.style.writing_mode;
1391        let logical_line_rect = LogicalRect {
1392            start_corner: LogicalVec2 {
1393                inline: Au::zero(),
1394                block: block_start_position,
1395            },
1396            size: LogicalVec2 {
1397                inline: containing_block.inline_size(),
1398                block: effective_block_advance.resolve(),
1399            },
1400        };
1401        let physical_line_rect = logical_line_rect.as_physical_deprecated(containing_block);
1402
1403        self.positioning_context
1404            .adjust_static_position_of_hoisted_fragments(
1405                &logical_line_rect,
1406                containing_block_writing_mode,
1407                start_positioning_context_length,
1408            );
1409
1410        self.fragments
1411            .push(Fragment::Positioning(PositioningFragment::new_anonymous(
1412                self.root_nesting_level.style.clone(),
1413                physical_line_rect,
1414                FragmentChildren::PhysicalDeprecated(fragments),
1415                true, /* is_line_box */
1416            )));
1417    }
1418
1419    fn available_line_space(&self) -> Au {
1420        match self.current_line.placement_among_floats.get() {
1421            Some(placement_among_floats) => placement_among_floats.size.inline,
1422            None => self.containing_block().inline_size(),
1423        }
1424    }
1425
1426    /// Given the amount of whitespace trimmed from the line and taking into consideration
1427    /// the `text-align` property, calculate where the line under construction starts in
1428    /// the inline axis as well as the adjustment needed for every justification opportunity
1429    /// to account for `text-align: justify`.
1430    fn calculate_current_line_inline_start_and_justification_adjustment(
1431        &self,
1432        hanging_white_space: Au,
1433        last_line_or_forced_line_break: bool,
1434    ) -> (Au, Au) {
1435        enum TextAlign {
1436            Start,
1437            Center,
1438            End,
1439        }
1440        let containing_block = self.containing_block();
1441        let style = containing_block.style;
1442        let mut text_align_keyword = style.get_text_align();
1443
1444        if last_line_or_forced_line_break {
1445            text_align_keyword = match style.get_text_align_last() {
1446                TextAlignLast::Auto if text_align_keyword == &TextAlignKeyword::Justify => {
1447                    &TextAlignKeyword::Start
1448                },
1449                TextAlignLast::Auto => text_align_keyword,
1450                TextAlignLast::Start => &TextAlignKeyword::Start,
1451                TextAlignLast::End => &TextAlignKeyword::End,
1452                TextAlignLast::Left => &TextAlignKeyword::Left,
1453                TextAlignLast::Right => &TextAlignKeyword::Right,
1454                TextAlignLast::Center => &TextAlignKeyword::Center,
1455                TextAlignLast::Justify => &TextAlignKeyword::Justify,
1456            };
1457        }
1458
1459        let text_align = match text_align_keyword {
1460            TextAlignKeyword::Start => TextAlign::Start,
1461            TextAlignKeyword::Center | TextAlignKeyword::MozCenter => TextAlign::Center,
1462            TextAlignKeyword::End => TextAlign::End,
1463            TextAlignKeyword::Left | TextAlignKeyword::MozLeft => {
1464                if style.writing_mode.line_left_is_inline_start() {
1465                    TextAlign::Start
1466                } else {
1467                    TextAlign::End
1468                }
1469            },
1470            TextAlignKeyword::Right | TextAlignKeyword::MozRight => {
1471                if style.writing_mode.line_left_is_inline_start() {
1472                    TextAlign::End
1473                } else {
1474                    TextAlign::Start
1475                }
1476            },
1477            TextAlignKeyword::Justify => TextAlign::Start,
1478        };
1479
1480        let available_space = self.available_line_space();
1481        let line_start = match self.current_line.placement_among_floats.get() {
1482            Some(placement_among_floats) => placement_among_floats.start_corner.inline,
1483            None => Au::zero(),
1484        };
1485
1486        // Properly handling text-indent requires that we do not align the text
1487        // into the text-indent.
1488        // See <https://drafts.csswg.org/css-text/#text-indent-property>
1489        // "This property specifies the indentation applied to lines of inline content in
1490        // a block. The indent is treated as a margin applied to the start edge of the
1491        // line box."
1492        let text_indent = self.current_line.start_position.inline;
1493        let line_length = self.current_line.inline_position - hanging_white_space - text_indent;
1494        let adjusted_line_start = line_start +
1495            match text_align {
1496                TextAlign::Start => text_indent,
1497                TextAlign::End => (available_space - line_length).max(text_indent),
1498                TextAlign::Center => (available_space - line_length + text_indent)
1499                    .scale_by(0.5)
1500                    .max(text_indent),
1501            };
1502
1503        // Calculate the justification adjustment. This is simply the remaining space on the line,
1504        // divided by the number of justification opportunities that we recorded when building
1505        // the line.
1506        let text_justify = containing_block.style.get_text_justify();
1507        let justification_adjustment = match (text_align_keyword, text_justify) {
1508            // `text-justify: none` should disable text justification.
1509            // TODO: Handle more `text-justify` values.
1510            (TextAlignKeyword::Justify, TextJustify::None) => Au::zero(),
1511            (TextAlignKeyword::Justify, _) => {
1512                match self.current_line.count_justification_opportunities() {
1513                    0 => Au::zero(),
1514                    num_justification_opportunities => {
1515                        (available_space - text_indent - line_length)
1516                            .scale_by(1. / num_justification_opportunities as f32)
1517                    },
1518                }
1519            },
1520            _ => Au::zero(),
1521        };
1522
1523        // If the content overflows the line, then justification adjustment will become negative. In
1524        // that case, do not make any adjustment for justification.
1525        let justification_adjustment = justification_adjustment.max(Au::zero());
1526
1527        (adjusted_line_start, justification_adjustment)
1528    }
1529
1530    fn place_float_fragment(&mut self, float: &FloatLineItem) {
1531        let state = self
1532            .sequential_layout_state
1533            .as_mut()
1534            .expect("Tried to lay out a float with no sequential placement state!");
1535
1536        let block_offset_from_containining_block_top = state
1537            .current_block_position_including_margins() -
1538            state.current_containing_block_offset();
1539        let float_content_rect = state.place_float_fragment(
1540            &float.fragment,
1541            self.placement_state.containing_block,
1542            CollapsedMargin::zero(),
1543            block_offset_from_containining_block_top,
1544        );
1545        self.positioning_context
1546            .adjust_static_position_of_hoisted_fragments_in_range(
1547                &float_content_rect,
1548                self.placement_state.containing_block.style.writing_mode,
1549                &float.range,
1550            )
1551    }
1552
1553    /// Place a FloatLineItem. This is done when an unbreakable segment is committed to
1554    /// the current line. Placement of FloatLineItems might need to be deferred until the
1555    /// line is complete in the case that floats stop fitting on the current line.
1556    ///
1557    /// When placing floats we do not want to take into account any trailing whitespace on
1558    /// the line, because that whitespace will be trimmed in the case that the line is
1559    /// broken. Thus this function takes as an argument the new size (without whitespace) of
1560    /// the line that these floats are joining.
1561    fn place_float_line_item_for_commit_to_line(
1562        &mut self,
1563        float_item: &mut FloatLineItem,
1564        potential_line_length: Au,
1565    ) {
1566        let containing_block = self.containing_block();
1567        let float_fragment = &float_item.fragment;
1568        let logical_margin_rect_size = LogicalVec2::from_physical_size(
1569            &float_fragment.margin_rect().size,
1570            containing_block.style.writing_mode,
1571        );
1572        let inline_size = logical_margin_rect_size.inline.max(Au::zero());
1573
1574        let available_inline_size = match self.current_line.placement_among_floats.get() {
1575            Some(placement_among_floats) => placement_among_floats.size.inline,
1576            None => containing_block.inline_size(),
1577        } - potential_line_length;
1578
1579        // If this float doesn't fit on the current line or a previous float didn't fit on
1580        // the current line, we need to place it starting at the next line BUT still as
1581        // children of this line's hierarchy of inline boxes (for the purposes of properly
1582        // parenting in their stacking contexts). Once all the line content is gathered we
1583        // will place them later.
1584        let has_content = self.current_line.has_content || self.current_line_segment.has_content;
1585        let fits_on_line = !has_content || inline_size <= available_inline_size;
1586        let needs_placement_later =
1587            self.current_line.has_floats_waiting_to_be_placed || !fits_on_line;
1588
1589        if needs_placement_later {
1590            self.current_line.has_floats_waiting_to_be_placed = true;
1591        } else {
1592            self.place_float_fragment(float_item);
1593            float_item.needs_placement = false;
1594        }
1595
1596        // We've added a new float to the IFC, but this may have actually changed the
1597        // position of the current line. In order to determine that we regenerate the
1598        // placement among floats for the current line, which may adjust its inline
1599        // start position.
1600        let new_placement = self.place_line_among_floats(&LogicalVec2 {
1601            inline: potential_line_length,
1602            block: self.current_line.max_block_size.resolve(),
1603        });
1604        self.current_line
1605            .replace_placement_among_floats(new_placement);
1606    }
1607
1608    /// Given a new potential line size for the current line, create a "placement" for that line.
1609    /// This tells us whether or not the new potential line will fit in the current block position
1610    /// or need to be moved. In addition, the placement rect determines the inline start and end
1611    /// of the line if it's used as the final placement among floats.
1612    fn place_line_among_floats(&self, potential_line_size: &LogicalVec2<Au>) -> LogicalRect<Au> {
1613        let sequential_layout_state = self
1614            .sequential_layout_state
1615            .as_ref()
1616            .expect("Should not have called this function without having floats.");
1617
1618        let ifc_offset_in_float_container = LogicalVec2 {
1619            inline: sequential_layout_state
1620                .floats
1621                .containing_block_info
1622                .inline_start,
1623            block: sequential_layout_state.current_containing_block_offset(),
1624        };
1625
1626        let ceiling = self.current_line_block_start_considering_placement_among_floats();
1627        let mut placement = PlacementAmongFloats::new(
1628            &sequential_layout_state.floats,
1629            ceiling + ifc_offset_in_float_container.block,
1630            LogicalVec2 {
1631                inline: potential_line_size.inline,
1632                block: potential_line_size.block,
1633            },
1634            &PaddingBorderMargin::zero(),
1635        );
1636
1637        let mut placement_rect = placement.place();
1638        placement_rect.start_corner -= ifc_offset_in_float_container;
1639        placement_rect
1640    }
1641
1642    /// Returns true if a new potential line size for the current line would require a line
1643    /// break. This takes into account floats and will also update the "placement among
1644    /// floats" for this line if the potential line size would not cause a line break.
1645    /// Thus, calling this method has side effects and should only be done while in the
1646    /// process of laying out line content that is always going to be committed to this
1647    /// line or the next.
1648    fn new_potential_line_size_causes_line_break(
1649        &mut self,
1650        potential_line_size: &LogicalVec2<Au>,
1651    ) -> bool {
1652        let containing_block = self.containing_block();
1653        let available_line_space = if self.sequential_layout_state.is_some() {
1654            self.current_line
1655                .placement_among_floats
1656                .get_or_init(|| self.place_line_among_floats(potential_line_size))
1657                .size
1658        } else {
1659            LogicalVec2 {
1660                inline: containing_block.inline_size(),
1661                block: MAX_AU,
1662            }
1663        };
1664
1665        let inline_would_overflow = potential_line_size.inline > available_line_space.inline;
1666        let block_would_overflow = potential_line_size.block > available_line_space.block;
1667
1668        // The first content that is added to a line cannot trigger a line break and
1669        // the `white-space` propertly can also prevent all line breaking.
1670        let can_break = self.current_line.has_content;
1671
1672        // If this is the first content on the line and we already have a float placement,
1673        // that means that the placement was initialized by a leading float in the IFC.
1674        // This placement needs to be updated, because the first line content might push
1675        // the block start of the line downward. If there is no float placement, we want
1676        // to make one to properly set the block position of the line.
1677        if !can_break {
1678            // Even if we cannot break, adding content to this line might change its position.
1679            // In that case we need to redo our placement among floats.
1680            if self.sequential_layout_state.is_some() &&
1681                (inline_would_overflow || block_would_overflow)
1682            {
1683                let new_placement = self.place_line_among_floats(potential_line_size);
1684                self.current_line
1685                    .replace_placement_among_floats(new_placement);
1686            }
1687
1688            return false;
1689        }
1690
1691        // If the potential line is larger than the containing block we do not even need to consider
1692        // floats. We definitely have to do a linebreak.
1693        if potential_line_size.inline > containing_block.inline_size() {
1694            return true;
1695        }
1696
1697        // Not fitting in the block space means that our block size has changed and we had a
1698        // placement among floats that is no longer valid. This same placement might just
1699        // need to be expanded or perhaps we need to line break.
1700        if block_would_overflow {
1701            // If we have a limited block size then we are wedging this line between floats.
1702            assert!(self.sequential_layout_state.is_some());
1703            let new_placement = self.place_line_among_floats(potential_line_size);
1704            if new_placement.start_corner.block !=
1705                self.current_line_block_start_considering_placement_among_floats()
1706            {
1707                return true;
1708            } else {
1709                self.current_line
1710                    .replace_placement_among_floats(new_placement);
1711                return false;
1712            }
1713        }
1714
1715        // Otherwise the new potential line size will require a newline if it fits in the
1716        // inline space available for this line. This space may be smaller than the
1717        // containing block if floats shrink the available inline space.
1718        potential_line_size.inline > available_line_space.inline
1719    }
1720
1721    fn defer_forced_line_break_at_character_offset(
1722        &mut self,
1723        caret_placeholder: &Option<CaretPlaceholder>,
1724    ) {
1725        // If the current portion of the unbreakable segment does not fit on the current line
1726        // we need to put it on a new line *before* actually triggering the hard line break.
1727        if !self.unbreakable_segment_fits_on_line() {
1728            self.rewind_trailing_inline_box_starts();
1729            self.process_line_break(
1730                false, /* forced_line_break */
1731                false, /* for_block_level */
1732            );
1733        }
1734
1735        // Defer the actual line break until we've cleared all ending inline boxes.
1736        self.force_line_break_before_new_content = true;
1737        self.caret_placeholder = caret_placeholder.clone();
1738
1739        // In quirks mode, the line-height isn't automatically added to the line. If we consider a
1740        // forced line break a kind of preserved white space, quirks mode requires that we add the
1741        // line-height of the current element to the line box height.
1742        //
1743        // The exception here is `<br>` elements. They are implemented with `pre-line` in Servo, but
1744        // this is an implementation detail. The "magic" behavior of `<br>` elements is that they
1745        // add line-height to the line conditionally: only when they are on an otherwise empty line.
1746        let line_is_empty =
1747            !self.current_line_segment.has_content && !self.current_line.has_content;
1748        if !self.processing_br_element() || line_is_empty {
1749            let strut_size = self
1750                .current_inline_container_state()
1751                .strut_block_sizes
1752                .clone();
1753            self.update_unbreakable_segment_for_new_content(
1754                &strut_size,
1755                Au::zero(),
1756                Au::zero(),
1757                Au::zero(),
1758                SegmentContentFlags::Contentful,
1759            );
1760        }
1761    }
1762
1763    fn possibly_flush_deferred_forced_line_break(&mut self) {
1764        if !self.force_line_break_before_new_content {
1765            return;
1766        }
1767        self.force_line_break_before_new_content = false;
1768
1769        self.commit_current_segment_to_line();
1770        self.process_line_break(
1771            true,  /* forced_line_break */
1772            false, /* for_block_level */
1773        );
1774
1775        self.current_line.caret_placeholder = self.caret_placeholder.take();
1776    }
1777
1778    fn push_line_item_to_unbreakable_segment(&mut self, line_item: LineItem) {
1779        self.current_line_segment.push_line_item(line_item);
1780    }
1781
1782    fn push_shaped_text_slice_to_unbreakable_segment(
1783        &mut self,
1784        slice: Arc<ShapedTextSlice>,
1785        text_run: &TextRun,
1786        info: &FontAndScriptInfo,
1787        character_range: Range<Utf32CodeUnits>,
1788    ) {
1789        let mut block_contribution = LineBlockSizes::zero();
1790        let quirks_mode = self.layout_context.style_context.quirks_mode() != QuirksMode::NoQuirks;
1791        let current_inline_container_state = self.current_inline_container_state();
1792        if quirks_mode && !slice.all_removable() {
1793            // Normally, the strut is incorporated into the nested block size. In quirks mode though
1794            // if we find any text that isn't collapsed whitespace, we need to incorporate the strut.
1795            // TODO(mrobinson): This isn't quite right for situations where collapsible white space
1796            // ultimately does not collapse because it is between two other pieces of content.
1797            block_contribution.max_assign(&current_inline_container_state.strut_block_sizes);
1798        }
1799
1800        // If the metrics of this font don't match the default font, we are likely using another
1801        // font from the font list or a fallback and should incorporate its block size into the block
1802        // size of the container.
1803        let font_metrics = info.font_info.font.metrics();
1804        if current_inline_container_state
1805            .font_metrics
1806            .block_metrics_meaningfully_differ(font_metrics)
1807        {
1808            // TODO(mrobinson): This value should probably be cached somewhere.
1809            let baseline_shift = effective_baseline_shift(
1810                &current_inline_container_state.style,
1811                self.inline_box_state_stack.last().map(|c| &c.base),
1812            );
1813            let mut font_block_conribution = current_inline_container_state
1814                .get_block_size_contribution(
1815                    &baseline_shift,
1816                    font_metrics,
1817                    &current_inline_container_state.font_metrics,
1818                );
1819            font_block_conribution
1820                .adjust_for_baseline_offset(current_inline_container_state.baseline_offset);
1821            block_contribution.max_assign(&font_block_conribution);
1822        }
1823
1824        let mut segment_flags = SegmentContentFlags::empty();
1825        if slice.has_non_hangable_non_removable_content() {
1826            segment_flags.insert(SegmentContentFlags::IncorporateTrailingWhiteSpace);
1827        }
1828        if !slice.all_removable() {
1829            segment_flags.insert(SegmentContentFlags::Contentful);
1830        }
1831
1832        self.update_unbreakable_segment_for_new_content(
1833            &block_contribution,
1834            slice.total_advance(),
1835            slice.hangable_advance(),
1836            slice.removable_advance(),
1837            segment_flags,
1838        );
1839
1840        let current_inline_box_identifier = self.current_inline_box_identifier();
1841        self.push_line_item_to_unbreakable_segment(LineItem::TextRun(
1842            current_inline_box_identifier,
1843            TextRunLineItem {
1844                text: vec![slice],
1845                text_fragment_run_data: text_run.run_data.clone(),
1846                base_fragment_info: text_run.base_fragment_info,
1847                info: info.clone(),
1848                character_range_in_dom_node: character_range,
1849                is_empty_for_text_cursor: false,
1850            },
1851        ));
1852    }
1853
1854    /// If the current line is empty and this [`InlineFormattingContext`] has a selection, push an
1855    /// empty [`LineItem::TextRun`] so that text carets can be placed on otherwise empty lines.
1856    fn possibly_push_empty_text_run_to_line_for_text_caret(&mut self) {
1857        let Some(caret_placeholder) = self.current_line.caret_placeholder.take() else {
1858            return;
1859        };
1860
1861        // If the last content line item is a text item, then the placeholder for the text caret is not necessary.
1862        if self
1863            .current_line
1864            .line_items
1865            .iter()
1866            .rev()
1867            .find(|line_item| line_item.is_in_flow_content())
1868            .is_some_and(|line_item| matches!(line_item, LineItem::TextRun(..)))
1869        {
1870            return;
1871        }
1872
1873        let inline_container_state = self.current_inline_container_state();
1874        let Some(font) = inline_container_state.default_font.clone() else {
1875            return;
1876        };
1877
1878        self.push_line_item_to_unbreakable_segment(LineItem::TextRun(
1879            self.current_inline_box_identifier(),
1880            TextRunLineItem {
1881                text: Default::default(),
1882                text_fragment_run_data: caret_placeholder.run_data,
1883                base_fragment_info: caret_placeholder.base_fragment_info,
1884                info: FontAndScriptInfo::simple_for_font(font),
1885                character_range_in_dom_node: caret_placeholder.character_index..
1886                    caret_placeholder.character_index + Utf32CodeUnits(1),
1887                is_empty_for_text_cursor: true,
1888            },
1889        ));
1890
1891        let strut_size = self
1892            .current_inline_container_state()
1893            .strut_block_sizes
1894            .clone();
1895        self.update_unbreakable_segment_for_new_content(
1896            &strut_size,
1897            Au::zero(),
1898            Au::zero(),
1899            Au::zero(),
1900            SegmentContentFlags::empty(),
1901        );
1902
1903        self.current_line_segment.has_content = true;
1904        self.commit_current_segment_to_line();
1905    }
1906
1907    fn update_unbreakable_segment_for_new_content(
1908        &mut self,
1909        block_sizes_of_content: &LineBlockSizes,
1910        inline_size: Au,
1911        hangable_size: Au,
1912        removable_size: Au,
1913        segment_flags: SegmentContentFlags,
1914    ) {
1915        if segment_flags.contains(SegmentContentFlags::IncorporateTrailingWhiteSpace) {
1916            self.current_line_segment.trailing_hangable_white_space = Au::zero();
1917            self.current_line_segment.trailing_removable_white_space = Au::zero();
1918            self.current_line_segment.incorporates_trailing_white_space = true;
1919        }
1920
1921        if segment_flags.contains(SegmentContentFlags::Contentful) {
1922            self.current_line_segment.has_content = true;
1923        }
1924
1925        if hangable_size > Au::zero() {
1926            // When hangable space follows space previously considered removable, it can
1927            // no longer be trimmed from the end of the line, but it can hang.
1928            let old_removable_space =
1929                std::mem::take(&mut self.current_line_segment.trailing_removable_white_space);
1930            self.current_line_segment.trailing_hangable_white_space +=
1931                old_removable_space + hangable_size;
1932        }
1933        self.current_line_segment.trailing_removable_white_space += removable_size;
1934
1935        // This may or may not include the size of the strut depending on the quirks mode setting.
1936        let container_max_block_size = &self
1937            .current_inline_container_state()
1938            .nested_strut_block_sizes
1939            .clone();
1940        self.current_line_segment
1941            .max_block_size
1942            .max_assign(container_max_block_size);
1943        self.current_line_segment
1944            .max_block_size
1945            .max_assign(block_sizes_of_content);
1946
1947        self.current_line_segment.inline_size += inline_size;
1948
1949        // Propagate the whitespace setting to the current nesting level.
1950        self.current_inline_container_state().has_content.set(true);
1951        self.propagate_current_nesting_level_white_space_style();
1952    }
1953
1954    fn process_line_break(&mut self, forced_line_break: bool, for_block_level: bool) {
1955        self.current_line_segment.trim_leading_whitespace();
1956        self.finish_current_line_and_reset(forced_line_break, for_block_level);
1957    }
1958
1959    fn hypothetical_line_size(&self) -> LogicalVec2<Au> {
1960        let mut hanging_and_removable_whitespace = self
1961            .current_line_segment
1962            .hanging_and_removable_white_space_advance();
1963        if !self.current_line_segment.incorporates_trailing_white_space {
1964            hanging_and_removable_whitespace += self
1965                .current_line
1966                .tentative_hanging_and_removable_white_space_advance();
1967        }
1968        let inline = self.current_line.inline_position +
1969            self.current_line_segment.inline_size +
1970            self.cloneable_inline_box_pbm_size.end -
1971            hanging_and_removable_whitespace -
1972            self.current_line_segment.trailing_inline_box_start_size();
1973
1974        LogicalVec2 {
1975            inline,
1976            block: self
1977                .current_line_max_block_size_including_nested_containers()
1978                .max(&self.current_line_segment.max_block_size)
1979                .resolve(),
1980        }
1981    }
1982
1983    fn unbreakable_segment_fits_on_line(&mut self) -> bool {
1984        !self.new_potential_line_size_causes_line_break(&self.hypothetical_line_size())
1985    }
1986
1987    /// After a line break triggered by a soft wrap opportunity, any trailing opening
1988    /// inline box items should belong to the next line so that they "stick" to their
1989    /// content. This method runs before the line break and moves those trailing opening
1990    /// inline box items from the line to the segment (which will be part of the next
1991    /// line).
1992    fn rewind_trailing_inline_box_starts(&mut self) {
1993        let mut removal_start = self.current_line.line_items.len();
1994        for item in self.current_line.line_items.iter().rev() {
1995            let LineItem::InlineStartBoxPaddingBorderMargin(state) = item else {
1996                break;
1997            };
1998
1999            removal_start -= 1;
2000
2001            let inline_start = state.pbm_inline_start();
2002            self.current_line.inline_position -= inline_start;
2003            self.current_line_segment.inline_size += inline_start;
2004
2005            if state.should_clone_pbm() {
2006                self.current_line.cloneable_inline_box_pbm_size.start -= inline_start;
2007                self.current_line.cloneable_inline_box_pbm_size.end -= state.pbm_inline_end();
2008            }
2009        }
2010
2011        self.current_line_segment
2012            .line_items
2013            .splice(0..0, self.current_line.line_items.drain(removal_start..));
2014    }
2015
2016    /// Process a soft wrap opportunity. This will either commit the current unbreakable
2017    /// segment to the current line, if it fits within the containing block and float
2018    /// placement boundaries, or do a line break and then commit the segment.
2019    fn process_soft_wrap_opportunity(&mut self) {
2020        if self.current_line_segment.line_items.is_empty() {
2021            return;
2022        }
2023        if self.text_wrap_mode == TextWrapMode::Nowrap {
2024            return;
2025        }
2026        if !self.unbreakable_segment_fits_on_line() {
2027            self.rewind_trailing_inline_box_starts();
2028            self.process_line_break(
2029                false, /* forced_line_break */
2030                false, /* for_block_level */
2031            );
2032        }
2033        self.commit_current_segment_to_line();
2034    }
2035
2036    /// Commit the current unbreakable segment to the current line. In addition, this will
2037    /// place all floats in the unbreakable segment and expand the line dimensions.
2038    fn commit_current_segment_to_line(&mut self) {
2039        // Take a snapshot of the IFC layout's current cloneable PBM. This ensures that the
2040        // line reflects the reality of *only* the committed segments.
2041        self.current_line.cloneable_inline_box_pbm_size = self.cloneable_inline_box_pbm_size;
2042
2043        // The line segments might have no items and have content after processing a forced
2044        // linebreak on an empty line.
2045        if self.current_line_segment.line_items.is_empty() && !self.current_line_segment.has_content
2046        {
2047            return;
2048        }
2049
2050        if !self.current_line.has_content {
2051            self.current_line_segment.trim_leading_whitespace();
2052        }
2053
2054        let potential_line_length = self.hypothetical_line_size().inline;
2055
2056        let old_removable_space =
2057            std::mem::take(&mut self.current_line.trailing_removable_white_space);
2058        let old_hangable_space =
2059            std::mem::take(&mut self.current_line.trailing_hangable_white_space);
2060        let mut new_removable_space = self.current_line_segment.trailing_removable_white_space;
2061        let mut new_hangable_space = self.current_line_segment.trailing_hangable_white_space;
2062
2063        // If the white space of the current line is not incorporated into the content by the
2064        // new segment, add it to the segment's white space values.
2065        if !self.current_line_segment.incorporates_trailing_white_space {
2066            // When hangable space follows space previously considered removable, it can
2067            // no longer be trimmed from the end of the line, but it can hang.
2068            if new_hangable_space > Au::zero() {
2069                new_hangable_space += old_removable_space;
2070            } else {
2071                new_removable_space += old_removable_space;
2072            }
2073            new_hangable_space += old_hangable_space;
2074        }
2075
2076        self.current_line.trailing_hangable_white_space = new_hangable_space;
2077        self.current_line.trailing_removable_white_space = new_removable_space;
2078
2079        self.current_line.inline_position += self.current_line_segment.inline_size;
2080        self.current_line.max_block_size = self
2081            .current_line_max_block_size_including_nested_containers()
2082            .max(&self.current_line_segment.max_block_size);
2083
2084        // Place all floats in this unbreakable segment.
2085        let mut segment_items = mem::take(&mut self.current_line_segment.line_items);
2086
2087        for item in segment_items.iter_mut() {
2088            if let LineItem::Float(_, float_item) = item {
2089                self.place_float_line_item_for_commit_to_line(float_item, potential_line_length);
2090            }
2091        }
2092
2093        // If the current line was never placed among floats, we need to do that now based on the
2094        // new size. Calling `new_potential_line_size_causes_line_break()` here triggers the
2095        // new line to be positioned among floats. This should never ask for a line
2096        // break because it is the first content on the line.
2097        if self.current_line.line_items.is_empty() {
2098            let will_break = self.new_potential_line_size_causes_line_break(&LogicalVec2 {
2099                inline: potential_line_length,
2100                block: self.current_line_segment.max_block_size.resolve(),
2101            });
2102            assert!(!will_break);
2103        }
2104
2105        debug_assert!(
2106            self.current_line_segment.line_items.is_empty(),
2107            "Committing a segment should not add items to it"
2108        );
2109        // Return the emptied buffer to the segment so that its allocation is reused.
2110        self.current_line.line_items.append(&mut segment_items);
2111        self.current_line_segment.line_items = segment_items;
2112        self.current_line.has_content |= self.current_line_segment.has_content;
2113
2114        self.current_line_segment.reset();
2115    }
2116
2117    #[inline]
2118    fn containing_block(&self) -> &ContainingBlock<'_> {
2119        self.placement_state.containing_block
2120    }
2121}
2122
2123bitflags! {
2124    struct SegmentContentFlags: u8 {
2125        const IncorporateTrailingWhiteSpace = 1 << 0;
2126        const Contentful = 1 << 1;
2127    }
2128}
2129
2130impl InlineFormattingContext {
2131    #[servo_tracing::instrument(name = "InlineFormattingContext::new_with_builder", skip_all)]
2132    fn new_with_builder(
2133        mut builder: InlineFormattingContextBuilder,
2134        layout_context: &LayoutContext,
2135        has_first_formatted_line: bool,
2136        is_single_line_text_input: bool,
2137        starting_bidi_level: Level,
2138    ) -> Self {
2139        // This is to prevent a double borrow.
2140        let text_content: String = builder.text_segments.into_iter().collect();
2141
2142        let bidi_levels = BidiLevels {
2143            info: builder
2144                .has_right_to_left_content
2145                .then(|| BidiInfo::new(&text_content, Some(starting_bidi_level))),
2146        };
2147
2148        let shared_inline_styles = builder
2149            .shared_inline_styles_stack
2150            .last()
2151            .expect("Should have at least one SharedInlineStyle for the root of an IFC")
2152            .clone();
2153        let (word_break, line_break, lang) = {
2154            let styles = shared_inline_styles.style.borrow();
2155            let text_style = styles.get_inherited_text();
2156            (
2157                text_style.word_break,
2158                text_style.line_break,
2159                styles.get_font()._x_lang.clone(),
2160            )
2161        };
2162
2163        let mut options = LineBreakOptions::default();
2164
2165        // TODO: These settings need to be handled on an inline box basis and not based
2166        // on the paragraph's style.
2167        options.strictness = Some(match line_break {
2168            LineBreak::Loose => LineBreakStrictness::Loose,
2169            LineBreak::Normal => LineBreakStrictness::Normal,
2170            LineBreak::Strict => LineBreakStrictness::Strict,
2171            LineBreak::Anywhere => LineBreakStrictness::Anywhere,
2172            // For `auto`, the UA determines the set of line-breaking restrictions to use.
2173            // So it's fine if we always treat it as `normal`.
2174            LineBreak::Auto => LineBreakStrictness::Normal,
2175        });
2176        options.word_option = Some(match word_break {
2177            WordBreak::Normal | WordBreak::KeepAll => LineBreakWordOption::Normal,
2178            // TODO: also apply `overflow-wrap: anywhere` for `break-word` once overflow-wrap is supported
2179            WordBreak::BreakWord => LineBreakWordOption::Normal,
2180            WordBreak::BreakAll => LineBreakWordOption::BreakAll,
2181        });
2182
2183        // Enable Chinese/Japanese line breaking behavior when this inline formatting context
2184        // has a Japanese or Chinese language set.
2185        let content_locale = LanguageIdentifier::try_from_locale_bytes(lang.0.as_bytes()).ok();
2186        options.content_locale = content_locale.as_ref();
2187
2188        let mut shaping_queue = ShapingQueue::new(&text_content, options);
2189        for item in &mut builder.inline_items {
2190            match item {
2191                InlineItem::TextRun(text_run) => {
2192                    let shaping_queue_entries = text_run.borrow_mut().segment(
2193                        text_run.clone(),
2194                        &text_content,
2195                        layout_context,
2196                        &bidi_levels,
2197                    );
2198                    for entry in shaping_queue_entries.into_iter() {
2199                        shaping_queue.push(entry);
2200                    }
2201                },
2202                InlineItem::StartInlineBox(inline_box) => {
2203                    let inline_box = &mut *inline_box.borrow_mut();
2204                    if let Some(font) = get_font_for_first_font_for_style(
2205                        &inline_box.base.style,
2206                        &layout_context.font_context,
2207                    ) {
2208                        inline_box.default_font = Some(font);
2209                    }
2210
2211                    if inline_box.breaks_shaping_at_start {
2212                        shaping_queue.flush();
2213                    }
2214                },
2215                InlineItem::Atomic(_, index_in_text, bidi_level) => {
2216                    shaping_queue.flush();
2217                    *bidi_level = bidi_levels.level(usize::from(*index_in_text));
2218                },
2219                InlineItem::EndInlineBox(inline_box) => {
2220                    if inline_box.borrow().breaks_shaping_at_end {
2221                        shaping_queue.flush();
2222                    }
2223                },
2224                InlineItem::OutOfFlowAbsolutelyPositionedBox(..) |
2225                InlineItem::OutOfFlowFloatBox(_) |
2226                InlineItem::BlockLevel { .. } => {},
2227            }
2228        }
2229
2230        shaping_queue.flush();
2231
2232        let default_font = get_font_for_first_font_for_style(
2233            &shared_inline_styles.style.borrow(),
2234            &layout_context.font_context,
2235        );
2236
2237        let has_right_to_left_content = bidi_levels.info.as_ref().is_some_and(BidiInfo::has_rtl);
2238        builder
2239            .text_content_slot
2240            .set(text_content)
2241            .expect("Text content should not yet be set.");
2242
2243        InlineFormattingContext {
2244            text_content: builder.text_content_slot,
2245            inline_items: builder.inline_items,
2246            inline_boxes: builder.inline_boxes,
2247            shared_inline_styles,
2248            default_font,
2249            has_first_formatted_line,
2250            contains_floats: builder.contains_floats,
2251            is_single_line_text_input,
2252            has_right_to_left_content,
2253            tab_size_multiplier: Default::default(),
2254        }
2255    }
2256
2257    pub(crate) fn text_content(&self) -> &str {
2258        self.text_content.get().map_or("", String::as_str)
2259    }
2260
2261    pub(crate) fn repair_style(
2262        &self,
2263        context: &SharedStyleContext,
2264        node: &ServoLayoutNode,
2265        new_style: &ServoArc<ComputedValues>,
2266    ) {
2267        *self.shared_inline_styles.style.borrow_mut() = new_style.clone();
2268        *self.shared_inline_styles.selected.borrow_mut() = node.selected_style(context);
2269    }
2270
2271    fn inline_start_for_first_line(&self, containing_block: IndefiniteContainingBlock) -> Au {
2272        if !self.has_first_formatted_line {
2273            return Au::zero();
2274        }
2275        containing_block
2276            .style
2277            .get_inherited_text()
2278            .text_indent
2279            .length
2280            .to_used_value(containing_block.size.inline_size.unwrap_or_default())
2281    }
2282
2283    pub(super) fn layout(
2284        &self,
2285        layout_context: &LayoutContext,
2286        positioning_context: &mut PositioningContext,
2287        containing_block: &ContainingBlock,
2288        sequential_layout_state: Option<&mut SequentialLayoutState>,
2289        collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
2290        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
2291    ) -> IndependentFormattingContextLayoutResult {
2292        // Clear any cached inline fragments from previous layouts.
2293        for inline_box in self.inline_boxes.iter() {
2294            inline_box.borrow().base.clear_fragments();
2295        }
2296
2297        let style = containing_block.style;
2298
2299        let style_text = containing_block.style.get_inherited_text();
2300        let mut inline_container_state_flags = InlineContainerStateFlags::empty();
2301        if inline_container_needs_strut(style, layout_context, None) {
2302            inline_container_state_flags.insert(InlineContainerStateFlags::CREATE_STRUT);
2303        }
2304        if self.is_single_line_text_input {
2305            inline_container_state_flags
2306                .insert(InlineContainerStateFlags::IS_SINGLE_LINE_TEXT_INPUT);
2307        }
2308        let placement_state =
2309            PlacementState::new(collapsible_with_parent_start_margin, containing_block);
2310
2311        let mut layout = InlineFormattingContextLayout {
2312            positioning_context,
2313            placement_state,
2314            sequential_layout_state,
2315            layout_context,
2316            ifc: self,
2317            fragments: Vec::new(),
2318            current_line: LineUnderConstruction::new(LogicalVec2 {
2319                inline: self.inline_start_for_first_line(containing_block.into()),
2320                block: Au::zero(),
2321            }),
2322            root_nesting_level: InlineContainerState::new(
2323                style.to_arc(),
2324                inline_container_state_flags,
2325                None, /* parent_container */
2326                self.default_font.clone(),
2327            ),
2328            inline_box_state_stack: Vec::new(),
2329            cloneable_inline_box_pbm_size: Default::default(),
2330            inline_box_states: Vec::with_capacity(self.inline_boxes.len()),
2331            current_line_segment: UnbreakableSegmentUnderConstruction::new(),
2332            force_line_break_before_new_content: false,
2333            caret_placeholder: None,
2334            deferred_br_clear: Clear::None,
2335            have_deferred_soft_wrap_opportunity: false,
2336            depends_on_block_constraints: false,
2337            white_space_collapse: style_text.white_space_collapse,
2338            text_wrap_mode: style_text.text_wrap_mode,
2339            ignore_block_margins_for_stretch,
2340        };
2341
2342        for item in self.inline_items.iter() {
2343            // Any new box should flush a pending hard line break.
2344            if !matches!(item, InlineItem::EndInlineBox(..)) {
2345                layout.possibly_flush_deferred_forced_line_break();
2346            }
2347
2348            match item {
2349                InlineItem::StartInlineBox(inline_box) => {
2350                    layout.start_inline_box(&inline_box.borrow());
2351                },
2352                InlineItem::EndInlineBox(..) => layout.finish_inline_box(),
2353                InlineItem::TextRun(run) => run.borrow().layout_into_line_items(&mut layout),
2354                InlineItem::Atomic(atomic_formatting_context, offset_in_text, bidi_level) => {
2355                    atomic_formatting_context.borrow().layout_into_line_items(
2356                        &mut layout,
2357                        *offset_in_text,
2358                        *bidi_level,
2359                    );
2360                },
2361                InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, _) => {
2362                    layout.push_line_item_to_unbreakable_segment(LineItem::AbsolutelyPositioned(
2363                        layout.current_inline_box_identifier(),
2364                        AbsolutelyPositionedLineItem {
2365                            absolutely_positioned_box: positioned_box.clone(),
2366                            preceding_line_content_would_produce_phantom_line: layout
2367                                .current_line
2368                                .is_phantom() &&
2369                                layout.current_line_segment.is_phantom(),
2370                        },
2371                    ));
2372                },
2373                InlineItem::OutOfFlowFloatBox(float_box) => {
2374                    float_box.borrow().layout_into_line_items(&mut layout);
2375                },
2376                InlineItem::BlockLevel(block_level) => {
2377                    block_level.borrow().layout_into_line_items(&mut layout);
2378                },
2379            }
2380        }
2381
2382        layout.finish_last_line();
2383        let (content_block_size, collapsible_margins_in_children, baselines) =
2384            layout.placement_state.finish();
2385
2386        IndependentFormattingContextLayoutResult {
2387            fragments: FragmentChildren::PhysicalDeprecated(layout.fragments),
2388            content_block_size,
2389            collapsible_margins_in_children,
2390            baselines,
2391            depends_on_block_constraints: layout.depends_on_block_constraints,
2392            content_inline_size_for_table: None,
2393            specific_layout_info: None,
2394        }
2395    }
2396
2397    pub(crate) fn subtree_size(&self) -> usize {
2398        self.inline_items
2399            .iter()
2400            .map(|item| match item {
2401                InlineItem::StartInlineBox(..) => 1,
2402                InlineItem::EndInlineBox(..) => 0,
2403                InlineItem::TextRun(..) => 1,
2404                InlineItem::OutOfFlowAbsolutelyPositionedBox(absolutely_positioned_box, _) => {
2405                    absolutely_positioned_box
2406                        .borrow()
2407                        .context
2408                        .base
2409                        .subtree_size()
2410                },
2411                InlineItem::OutOfFlowFloatBox(..) => 1,
2412                InlineItem::Atomic(..) => 1,
2413                InlineItem::BlockLevel(block_level_box) => block_level_box.borrow().subtree_size(),
2414            })
2415            .sum()
2416    }
2417
2418    fn next_character_prevents_soft_wrap_opportunity(&self, index: Utf8CodeUnits) -> bool {
2419        let Some(second_character) = self.text_content()[usize::from(index)..].chars().nth(1)
2420        else {
2421            return false;
2422        };
2423        char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(second_character)
2424    }
2425
2426    fn previous_character_prevents_soft_wrap_opportunity(&self, index: Utf8CodeUnits) -> bool {
2427        let Some(character) = self.text_content()[..usize::from(index)]
2428            .chars()
2429            .next_back()
2430        else {
2431            return false;
2432        };
2433        char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character)
2434    }
2435
2436    pub(crate) fn find_block_margin_collapsing_with_parent(
2437        &self,
2438        layout_context: &LayoutContext,
2439        collected_margin: &mut CollapsedMargin,
2440        containing_block_for_children: &ContainingBlock,
2441    ) -> bool {
2442        // Margins can't collapse through line boxes, unless they are phantom line boxes.
2443        // <https://drafts.csswg.org/css-inline-3/#invisible-line-boxes>
2444        // > Line boxes that contain no text, no preserved white space, no inline boxes with non-zero
2445        // > inline-axis margins, padding, or borders, and no other in-flow content (such as atomic
2446        // > inlines or ruby annotations), and do not end with a forced line break are phantom line boxes.
2447        let mut items_iter = self.inline_items.iter();
2448        items_iter.all(|inline_item| match inline_item {
2449            InlineItem::StartInlineBox(inline_box) => {
2450                let pbm = inline_box
2451                    .borrow()
2452                    .layout_style()
2453                    .padding_border_margin(containing_block_for_children);
2454                pbm.padding.inline_start.is_zero() &&
2455                    pbm.border.inline_start.is_zero() &&
2456                    pbm.margin.inline_start.auto_is(Au::zero).is_zero()
2457            },
2458            InlineItem::EndInlineBox(inline_box) => {
2459                let pbm = inline_box
2460                    .borrow()
2461                    .layout_style()
2462                    .padding_border_margin(containing_block_for_children);
2463                pbm.padding.inline_end.is_zero() &&
2464                    pbm.border.inline_end.is_zero() &&
2465                    pbm.margin.inline_end.auto_is(Au::zero).is_zero()
2466            },
2467            InlineItem::TextRun(text_run) => {
2468                let text_run = &*text_run.borrow();
2469                text_run.items.iter().all(|item| match item {
2470                    TextRunItem::LineBreak { .. } => false,
2471                    TextRunItem::Tab { .. } => false,
2472                    TextRunItem::TextSegment(segment) => {
2473                        segment.runs.iter().all(|run| run.all_removable())
2474                    },
2475                })
2476            },
2477            InlineItem::OutOfFlowAbsolutelyPositionedBox(..) => true,
2478            InlineItem::OutOfFlowFloatBox(..) => true,
2479            InlineItem::Atomic(..) => false,
2480            InlineItem::BlockLevel(block_level) => block_level
2481                .borrow()
2482                .find_block_margin_collapsing_with_parent(
2483                    layout_context,
2484                    collected_margin,
2485                    containing_block_for_children,
2486                ),
2487        })
2488    }
2489
2490    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
2491        let mut parent_box_stack = Vec::new();
2492        let current_parent_box = |parent_box_stack: &[WeakLayoutBox]| {
2493            parent_box_stack.last().unwrap_or(&layout_box).clone()
2494        };
2495        for inline_item in &self.inline_items {
2496            match inline_item {
2497                InlineItem::StartInlineBox(inline_box) => {
2498                    inline_box
2499                        .borrow_mut()
2500                        .base
2501                        .parent_box
2502                        .replace(current_parent_box(&parent_box_stack));
2503                    parent_box_stack.push(WeakLayoutBox::InlineLevel(
2504                        WeakInlineItem::StartInlineBox(inline_box.downgrade()),
2505                    ));
2506                },
2507                InlineItem::EndInlineBox(..) => {
2508                    parent_box_stack.pop();
2509                },
2510                InlineItem::TextRun(text_run) => {
2511                    text_run
2512                        .borrow_mut()
2513                        .parent_box
2514                        .replace(current_parent_box(&parent_box_stack));
2515                },
2516                _ => inline_item.with_base_mut(|base| {
2517                    base.parent_box
2518                        .replace(current_parent_box(&parent_box_stack));
2519                }),
2520            }
2521        }
2522    }
2523
2524    pub(crate) fn next_tab_stop_after_inline_advance(
2525        &self,
2526        style: &ServoArc<ComputedValues>,
2527        current_inline_advance: Au,
2528    ) -> Au {
2529        let Some(font) = self.default_font.as_ref() else {
2530            return Au::zero();
2531        };
2532
2533        let tab_size_multiplier = *self.tab_size_multiplier.get_or_init(|| {
2534            let root_style = self.shared_inline_styles.style.borrow();
2535            let inherited_text_style = root_style.get_inherited_text();
2536            let font_size = root_style.get_font().font_size.computed_size().into();
2537            let letter_spacing = inherited_text_style
2538                .letter_spacing
2539                .0
2540                .to_used_value(font_size);
2541            let word_spacing = inherited_text_style.word_spacing.to_used_value(font_size);
2542
2543            // Each "space" character in the tab is considered both a letter and a word separator for
2544            // the purposes of applying word spacing and letter spacing.
2545            font.metrics().space_advance + word_spacing + letter_spacing
2546        });
2547
2548        let tab_stop_advance = match style.get_inherited_text().tab_size {
2549            style::values::generics::length::LengthOrNumber::Number(number_of_spaces) => {
2550                tab_size_multiplier.scale_by(number_of_spaces.0)
2551            },
2552            // When a length is provided we do not apply word spacing or letter spacing.
2553            style::values::generics::length::LengthOrNumber::Length(length) => length.into(),
2554        };
2555
2556        if tab_stop_advance.is_zero() {
2557            return Au::zero();
2558        }
2559
2560        // From <https://drafts.csswg.org/css-text-4/#ref-for-tab-size-dfn>
2561        // > If this distance is less than 0.5ch, then the subsequent tab stop is used instead.
2562        // From <https://drafts.csswg.org/css-values/#ch>
2563        // > In the cases where it is impossible or impractical to determine the measure of the “0”
2564        // > glyph, it must be assumed to be 0.5em wide by 1em tall.
2565        let half_ch_advance = font
2566            .metrics()
2567            .zero_horizontal_advance
2568            .unwrap_or(font.metrics().em_size.scale_by(0.5))
2569            .scale_by(0.5);
2570        let number_of_tab_stops =
2571            (current_inline_advance + half_ch_advance).to_f32_px() / tab_stop_advance.to_f32_px();
2572        let number_of_tab_stops = number_of_tab_stops.ceil();
2573        tab_stop_advance.scale_by(number_of_tab_stops) - current_inline_advance
2574    }
2575
2576    pub(crate) fn non_pseudo_text_runs<'a>(
2577        &'a self,
2578    ) -> impl DoubleEndedIterator<Item = AtomicRef<'a, TextRun>> {
2579        self.inline_items
2580            .iter()
2581            .filter_map(|item| match item {
2582                InlineItem::TextRun(text_run) => Some(text_run.borrow()),
2583                _ => None,
2584            })
2585            .filter(|text_run| {
2586                text_run
2587                    .base_fragment_info
2588                    .tag
2589                    .is_some_and(|tag| tag.pseudo_element_chain.is_empty())
2590            })
2591    }
2592}
2593
2594impl InlineContainerState {
2595    fn new(
2596        style: ServoArc<ComputedValues>,
2597        flags: InlineContainerStateFlags,
2598        parent_container: Option<&InlineContainerState>,
2599        default_font: Option<FontRef>,
2600    ) -> Self {
2601        let font_metrics = default_font
2602            .as_ref()
2603            .map(|font| font.metrics().clone())
2604            .unwrap_or_else(FontMetrics::empty);
2605        let mut baseline_offset = Au::zero();
2606        let mut strut_block_sizes = {
2607            Self::get_block_sizes_with_style(
2608                &effective_baseline_shift(&style, parent_container),
2609                &style,
2610                &font_metrics,
2611                &font_metrics,
2612                &flags,
2613            )
2614        };
2615
2616        if let Some(parent_container) = parent_container {
2617            // The baseline offset from `vertical-align` might adjust where our block size contribution is
2618            // within the line.
2619            baseline_offset = parent_container.get_cumulative_baseline_offset_for_child(
2620                style.get_alignment_baseline(),
2621                style.get_baseline_shift(),
2622                &strut_block_sizes,
2623            );
2624            strut_block_sizes.adjust_for_baseline_offset(baseline_offset);
2625        }
2626
2627        let mut nested_block_sizes = parent_container
2628            .map(|container| container.nested_strut_block_sizes.clone())
2629            .unwrap_or_else(LineBlockSizes::zero);
2630        if flags.contains(InlineContainerStateFlags::CREATE_STRUT) {
2631            nested_block_sizes.max_assign(&strut_block_sizes);
2632        }
2633
2634        Self {
2635            style,
2636            flags,
2637            has_content: Cell::new(false),
2638            nested_strut_block_sizes: nested_block_sizes,
2639            strut_block_sizes,
2640            baseline_offset,
2641            default_font,
2642            font_metrics,
2643        }
2644    }
2645
2646    fn get_block_sizes_with_style(
2647        baseline_shift: &BaselineShift,
2648        style: &ComputedValues,
2649        font_metrics: &FontMetrics,
2650        font_metrics_of_first_font: &FontMetrics,
2651        flags: &InlineContainerStateFlags,
2652    ) -> LineBlockSizes {
2653        let line_height = line_height(style, font_metrics, flags);
2654
2655        if !is_baseline_relative(baseline_shift) {
2656            return LineBlockSizes {
2657                line_height,
2658                baseline_relative_size_for_line_height: None,
2659                size_for_baseline_positioning: BaselineRelativeSize::zero(),
2660            };
2661        }
2662
2663        // From https://drafts.csswg.org/css-inline/#inline-height
2664        // > If line-height computes to `normal` and either `text-box-edge` is `leading` or this
2665        // > is the root inline box, the font’s line gap metric may also be incorporated
2666        // > into A and D by adding half to each side as half-leading.
2667        //
2668        // `text-box-edge` isn't implemented (and this is a draft specification), so it's
2669        // always effectively `leading`, which means we always take into account the line gap
2670        // when `line-height` is normal.
2671        let mut ascent = font_metrics.ascent;
2672        let mut descent = font_metrics.descent;
2673        if style.get_font().line_height == LineHeight::Normal {
2674            let half_leading_from_line_gap =
2675                (font_metrics.line_gap - descent - ascent).scale_by(0.5);
2676            ascent += half_leading_from_line_gap;
2677            descent += half_leading_from_line_gap;
2678        }
2679
2680        // The ascent and descent we use for computing the line's final line height isn't
2681        // the same the ascent and descent we use for finding the baseline. For finding
2682        // the baseline we want the content rect.
2683        let size_for_baseline_positioning = BaselineRelativeSize { ascent, descent };
2684
2685        // From https://drafts.csswg.org/css-inline/#inline-height
2686        // > When its computed line-height is not normal, its layout bounds are derived solely
2687        // > from metrics of its first available font (ignoring glyphs from other fonts), and
2688        // > leading is used to adjust the effective A and D to add up to the used line-height.
2689        // > Calculate the leading L as L = line-height - (A + D). Half the leading (its
2690        // > half-leading) is added above A of the first available font, and the other half
2691        // > below D of the first available font, giving an effective ascent above the baseline
2692        // > of A′ = A + L/2, and an effective descent of D′ = D + L/2.
2693        //
2694        // Note that leading might be negative here and the line-height might be zero. In
2695        // the case where the height is zero, ascent and descent will move to the same
2696        // point in the block axis.  Even though the contribution to the line height is
2697        // zero in this case, the line may get some height when taking them into
2698        // considering with other zero line height boxes that converge on other block axis
2699        // locations when using the above formula.
2700        if style.get_font().line_height != LineHeight::Normal {
2701            ascent = font_metrics_of_first_font.ascent;
2702            descent = font_metrics_of_first_font.descent;
2703            let half_leading = (line_height - (ascent + descent)).scale_by(0.5);
2704            // We want the sum of `ascent` and `descent` to equal `line_height`.
2705            // If we just add `half_leading` to both, then we may not get `line_height`
2706            // due to precision limitations of `Au`. Instead, we set `descent` to
2707            // the value that will guarantee the correct sum.
2708            ascent += half_leading;
2709            descent = line_height - ascent;
2710        }
2711
2712        LineBlockSizes {
2713            line_height,
2714            baseline_relative_size_for_line_height: Some(BaselineRelativeSize { ascent, descent }),
2715            size_for_baseline_positioning,
2716        }
2717    }
2718
2719    fn get_block_size_contribution(
2720        &self,
2721        baseline_shift: &BaselineShift,
2722        font_metrics: &FontMetrics,
2723        font_metrics_of_first_font: &FontMetrics,
2724    ) -> LineBlockSizes {
2725        Self::get_block_sizes_with_style(
2726            baseline_shift,
2727            &self.style,
2728            font_metrics,
2729            font_metrics_of_first_font,
2730            &self.flags,
2731        )
2732    }
2733
2734    fn get_cumulative_baseline_offset_for_child(
2735        &self,
2736        child_alignment_baseline: &AlignmentBaseline,
2737        child_baseline_shift: &BaselineShift,
2738        child_block_size: &LineBlockSizes,
2739    ) -> Au {
2740        let block_size = self.get_block_size_contribution(
2741            child_baseline_shift,
2742            &self.font_metrics,
2743            &self.font_metrics,
2744        );
2745        self.baseline_offset +
2746            match child_alignment_baseline {
2747                AlignmentBaseline::Baseline => Au::zero(),
2748                AlignmentBaseline::TextTop => {
2749                    child_block_size.size_for_baseline_positioning.ascent - self.font_metrics.ascent
2750                },
2751                AlignmentBaseline::Middle => {
2752                    // "Align the vertical midpoint of the box with the baseline of the parent
2753                    // box plus half the x-height of the parent."
2754                    (child_block_size.size_for_baseline_positioning.ascent -
2755                        child_block_size.size_for_baseline_positioning.descent -
2756                        self.font_metrics.x_height)
2757                        .scale_by(0.5)
2758                },
2759                AlignmentBaseline::TextBottom => {
2760                    self.font_metrics.descent -
2761                        child_block_size.size_for_baseline_positioning.descent
2762                },
2763            } +
2764            match child_baseline_shift {
2765                // `top` and `bottom are not actually relative to the baseline, but this value is unused
2766                // in those cases.
2767                // TODO: We should distinguish these from `baseline` in order to implement "aligned subtrees" properly.
2768                // See https://drafts.csswg.org/css2/#aligned-subtree.
2769                BaselineShift::Keyword(
2770                    BaselineShiftKeyword::Top |
2771                    BaselineShiftKeyword::Bottom |
2772                    BaselineShiftKeyword::Center,
2773                ) => Au::zero(),
2774                BaselineShift::Keyword(BaselineShiftKeyword::Sub) => {
2775                    block_size.resolve().scale_by(FONT_SUBSCRIPT_OFFSET_RATIO)
2776                },
2777                BaselineShift::Keyword(BaselineShiftKeyword::Super) => {
2778                    -block_size.resolve().scale_by(FONT_SUPERSCRIPT_OFFSET_RATIO)
2779                },
2780                BaselineShift::Length(length_percentage) => {
2781                    -length_percentage.to_used_value(child_block_size.line_height)
2782                },
2783            }
2784    }
2785}
2786
2787impl IndependentFormattingContext {
2788    fn layout_into_line_items(
2789        &self,
2790        layout: &mut InlineFormattingContextLayout,
2791        offset_in_text: Utf8CodeUnits,
2792        bidi_level: Level,
2793    ) {
2794        // We need to know the inline size of the atomic before deciding whether to do the line break.
2795        let mut child_positioning_context = PositioningContext::default();
2796        let IndependentFloatOrAtomicLayoutResult {
2797            mut fragment,
2798            baselines,
2799            pbm_sums,
2800        } = self.layout_float_or_atomic_inline(
2801            layout.layout_context,
2802            &mut child_positioning_context,
2803            layout.containing_block(),
2804        );
2805
2806        // If this Fragment's layout depends on the block size of the containing block,
2807        // then the entire layout of the inline formatting context does as well.
2808        layout.depends_on_block_constraints |= fragment.base.flags.contains(
2809            FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
2810        );
2811
2812        // Offset the content rectangle by the physical offset of the padding, border, and margin.
2813        let container_writing_mode = layout.containing_block().style.writing_mode;
2814        let pbm_physical_offset = pbm_sums
2815            .start_offset()
2816            .to_physical_size(container_writing_mode);
2817        fragment.base.translate_rect(pbm_physical_offset);
2818
2819        // Apply baselines.
2820        fragment = fragment.with_baselines(baselines);
2821
2822        // Lay out absolutely positioned children if this new atomic establishes a containing block
2823        // for absolutes.
2824        let positioning_context = if self.is_replaced() {
2825            None
2826        } else {
2827            if fragment
2828                .style()
2829                .establishes_containing_block_for_absolute_descendants(fragment.base.flags)
2830            {
2831                child_positioning_context
2832                    .layout_collected_children(layout.layout_context, &mut fragment);
2833            }
2834            Some(child_positioning_context)
2835        };
2836
2837        if layout.text_wrap_mode == TextWrapMode::Wrap &&
2838            !layout
2839                .ifc
2840                .previous_character_prevents_soft_wrap_opportunity(offset_in_text)
2841        {
2842            layout.process_soft_wrap_opportunity();
2843        }
2844
2845        let size = pbm_sums.sum() +
2846            LogicalVec2::from_physical_size(&fragment.base.rect().size, container_writing_mode);
2847        let baseline_offset = self
2848            .pick_baseline(&fragment.baselines(container_writing_mode))
2849            .map(|baseline| pbm_sums.block_start + baseline)
2850            .unwrap_or(size.block);
2851
2852        let (block_sizes, baseline_offset_in_parent) =
2853            self.get_block_sizes_and_baseline_offset(layout, size.block, baseline_offset);
2854
2855        layout.update_unbreakable_segment_for_new_content(
2856            &block_sizes,
2857            size.inline,
2858            Au::zero(),
2859            Au::zero(),
2860            SegmentContentFlags::Contentful | SegmentContentFlags::IncorporateTrailingWhiteSpace,
2861        );
2862
2863        let fragment = Arc::new(fragment);
2864        self.base.set_fragment(Fragment::Box(fragment.clone()));
2865
2866        layout.push_line_item_to_unbreakable_segment(LineItem::Atomic(
2867            layout.current_inline_box_identifier(),
2868            AtomicLineItem {
2869                fragment,
2870                size,
2871                positioning_context,
2872                baseline_offset_in_parent,
2873                baseline_offset_in_item: baseline_offset,
2874                bidi_level,
2875            },
2876        ));
2877
2878        // If there's a soft wrap opportunity following this atomic, defer a soft wrap opportunity
2879        // for when we next process text content.
2880        if !layout
2881            .ifc
2882            .next_character_prevents_soft_wrap_opportunity(offset_in_text)
2883        {
2884            layout.have_deferred_soft_wrap_opportunity = true;
2885        }
2886    }
2887
2888    /// Picks either the first or the last baseline, depending on `baseline-source`.
2889    /// TODO: clarify that this is not to be used for box alignment in flex/grid
2890    /// <https://drafts.csswg.org/css-inline/#baseline-source>
2891    fn pick_baseline(&self, baselines: &Baselines) -> Option<Au> {
2892        match self.style().get_baseline_source() {
2893            BaselineSource::First => baselines.first,
2894            BaselineSource::Last => baselines.last,
2895            BaselineSource::Auto if self.is_block_container() => baselines.last,
2896            BaselineSource::Auto => baselines.first,
2897        }
2898    }
2899
2900    fn get_block_sizes_and_baseline_offset(
2901        &self,
2902        ifc: &InlineFormattingContextLayout,
2903        block_size: Au,
2904        baseline_offset_in_content_area: Au,
2905    ) -> (LineBlockSizes, Au) {
2906        let mut contribution = if !is_baseline_relative(self.style().get_baseline_shift()) {
2907            LineBlockSizes {
2908                line_height: block_size,
2909                baseline_relative_size_for_line_height: None,
2910                size_for_baseline_positioning: BaselineRelativeSize::zero(),
2911            }
2912        } else {
2913            let baseline_relative_size = BaselineRelativeSize {
2914                ascent: baseline_offset_in_content_area,
2915                descent: block_size - baseline_offset_in_content_area,
2916            };
2917            LineBlockSizes {
2918                line_height: block_size,
2919                baseline_relative_size_for_line_height: Some(baseline_relative_size.clone()),
2920                size_for_baseline_positioning: baseline_relative_size,
2921            }
2922        };
2923
2924        let style = self.style();
2925        let baseline_offset = ifc
2926            .current_inline_container_state()
2927            .get_cumulative_baseline_offset_for_child(
2928                style.get_alignment_baseline(),
2929                style.get_baseline_shift(),
2930                &contribution,
2931            );
2932        contribution.adjust_for_baseline_offset(baseline_offset);
2933
2934        (contribution, baseline_offset)
2935    }
2936}
2937
2938impl FloatBox {
2939    fn layout_into_line_items(&self, layout: &mut InlineFormattingContextLayout) {
2940        let old_len = layout.positioning_context.len();
2941        let fragment = Arc::new(self.layout(
2942            layout.layout_context,
2943            layout.positioning_context,
2944            layout.placement_state.containing_block,
2945        ));
2946        let new_len = layout.positioning_context.len();
2947
2948        self.contents
2949            .base
2950            .set_fragment(Fragment::Box(fragment.clone()));
2951        layout.push_line_item_to_unbreakable_segment(LineItem::Float(
2952            layout.current_inline_box_identifier(),
2953            FloatLineItem {
2954                fragment,
2955                needs_placement: true,
2956                range: old_len..new_len,
2957            },
2958        ));
2959    }
2960}
2961
2962fn place_pending_floats(ifc: &mut InlineFormattingContextLayout, line_items: &[LineItem]) {
2963    for item in line_items.iter() {
2964        if let LineItem::Float(_, float_line_item) = item &&
2965            float_line_item.needs_placement
2966        {
2967            ifc.place_float_fragment(float_line_item);
2968        }
2969    }
2970}
2971
2972pub(super) fn line_height(
2973    parent_style: &ComputedValues,
2974    font_metrics: &FontMetrics,
2975    flags: &InlineContainerStateFlags,
2976) -> Au {
2977    let font = parent_style.get_font();
2978    let font_size = font.font_size.computed_size();
2979    let mut line_height = match font.line_height {
2980        LineHeight::Normal => font_metrics.line_gap,
2981        LineHeight::Number(number) => (font_size * number.0).into(),
2982        LineHeight::Length(length) => length.0.into(),
2983    };
2984
2985    // The line height of a single-line text input's inner text container is clamped to
2986    // the size of `normal`.
2987    // <https://html.spec.whatwg.org/multipage/#the-input-element-as-a-text-entry-widget>
2988    if flags.contains(InlineContainerStateFlags::IS_SINGLE_LINE_TEXT_INPUT) {
2989        line_height.max_assign(font_metrics.line_gap);
2990    }
2991
2992    line_height
2993}
2994
2995fn effective_baseline_shift(
2996    style: &ComputedValues,
2997    container: Option<&InlineContainerState>,
2998) -> BaselineShift {
2999    if container.is_none() {
3000        // If we are at the root of the inline formatting context, we shouldn't use the
3001        // computed `baseline-shift`, since it has no effect on the contents of this IFC
3002        // (it can just affect how the block container is aligned within the parent IFC).
3003        BaselineShift::zero()
3004    } else {
3005        style.slow_clone_baseline_shift()
3006    }
3007}
3008
3009fn is_baseline_relative(baseline_shift: &BaselineShift) -> bool {
3010    !matches!(
3011        baseline_shift,
3012        BaselineShift::Keyword(
3013            BaselineShiftKeyword::Top | BaselineShiftKeyword::Bottom | BaselineShiftKeyword::Center
3014        )
3015    )
3016}
3017
3018/// Whether or not a strut should be created for an inline container. Normally
3019/// all inline containers get struts. In quirks mode this isn't always the case
3020/// though.
3021///
3022/// From <https://quirks.spec.whatwg.org/#the-line-height-calculation-quirk>
3023///
3024/// > ### § 3.3. The line height calculation quirk
3025/// > In quirks mode and limited-quirks mode, an inline box that matches the following
3026/// > conditions, must, for the purpose of line height calculation, act as if the box had a
3027/// > line-height of zero.
3028/// >
3029/// >  - The border-top-width, border-bottom-width, padding-top and padding-bottom
3030/// >    properties have a used value of zero and the box has a vertical writing mode, or the
3031/// >    border-right-width, border-left-width, padding-right and padding-left properties have
3032/// >    a used value of zero and the box has a horizontal writing mode.
3033/// >  - It either contains no text or it contains only collapsed whitespace.
3034/// >
3035/// > ### § 3.4. The blocks ignore line-height quirk
3036/// > In quirks mode and limited-quirks mode, for a block container element whose content is
3037/// > composed of inline-level elements, the element’s line-height must be ignored for the
3038/// > purpose of calculating the minimal height of line boxes within the element.
3039///
3040/// Since we incorporate the size of the strut into the line-height calculation when
3041/// adding text, we can simply not incorporate the strut at the start of inline box
3042/// processing. This also works the same for the root of the IFC.
3043fn inline_container_needs_strut(
3044    style: &ComputedValues,
3045    layout_context: &LayoutContext,
3046    pbm: Option<&PaddingBorderMargin>,
3047) -> bool {
3048    if layout_context.style_context.quirks_mode() == QuirksMode::NoQuirks {
3049        return true;
3050    }
3051
3052    // This is not in a standard yet, but all browsers disable this quirk for list items.
3053    // See https://github.com/whatwg/quirks/issues/38.
3054    if style.get_box().display.is_list_item() {
3055        return true;
3056    }
3057
3058    pbm.is_some_and(|pbm| !pbm.padding_border_sums.inline.is_zero())
3059}
3060
3061impl ComputeInlineContentSizes for InlineFormattingContext {
3062    // This works on an already-constructed `InlineFormattingContext`,
3063    // Which would have to change if/when
3064    // `BlockContainer::construct` parallelize their construction.
3065    fn compute_inline_content_sizes(
3066        &self,
3067        layout_context: &LayoutContext,
3068        constraint_space: &ConstraintSpace,
3069    ) -> InlineContentSizesResult {
3070        ContentSizesComputation::compute(self, layout_context, constraint_space)
3071    }
3072}
3073
3074/// A struct which takes care of computing [`ContentSizes`] for an [`InlineFormattingContext`].
3075struct ContentSizesComputation<'layout_data> {
3076    layout_context: &'layout_data LayoutContext<'layout_data>,
3077    constraint_space: &'layout_data ConstraintSpace<'layout_data>,
3078    paragraph: ContentSizes,
3079    current_line: ContentSizes,
3080    /// Size for whitespace pending to be added to this line.
3081    pending_whitespace: ContentSizes,
3082    /// Padding, border, and margins from the opening of inline boxes that
3083    /// has not yet been committed to the line.
3084    pending_opening_pbm_for_inline_boxes: Au,
3085    /// The size of the not yet cleared floats in the inline axis of the containing block.
3086    uncleared_floats: LogicalSides1D<ContentSizes>,
3087    /// The size of the already cleared floats in the inline axis of the containing block.
3088    cleared_floats: LogicalSides1D<ContentSizes>,
3089    /// Whether or not the current line has seen any content (excluding collapsed whitespace),
3090    /// when sizing under a min-content constraint.
3091    had_content_yet_for_min_content: bool,
3092    /// Whether or not the current line has seen any content (excluding collapsed whitespace),
3093    /// when sizing under a max-content constraint.
3094    had_content_yet_for_max_content: bool,
3095    /// Stack of ending padding, margin, and border to add to the length
3096    /// when an inline box finishes.
3097    ending_inline_pbm_stack: Vec<Au>,
3098    /// Stack of [`TextWrapMode`] of ongoing inline boxes.
3099    text_wrap_mode_stack: Vec<TextWrapMode>,
3100    /// Whether the inline content size depends on block constraints.
3101    depends_on_block_constraints: bool,
3102}
3103
3104impl<'layout_data> ContentSizesComputation<'layout_data> {
3105    fn traverse(
3106        mut self,
3107        inline_formatting_context: &InlineFormattingContext,
3108    ) -> InlineContentSizesResult {
3109        self.add_inline_size(
3110            inline_formatting_context.inline_start_for_first_line(self.constraint_space.into()),
3111        );
3112        for inline_item in &inline_formatting_context.inline_items {
3113            self.process_item(inline_item, inline_formatting_context);
3114        }
3115        self.forced_line_break();
3116        self.flush_floats();
3117
3118        InlineContentSizesResult {
3119            sizes: self.paragraph,
3120            depends_on_block_constraints: self.depends_on_block_constraints,
3121        }
3122    }
3123
3124    fn process_item(
3125        &mut self,
3126        inline_item: &InlineItem,
3127        inline_formatting_context: &InlineFormattingContext,
3128    ) {
3129        match inline_item {
3130            InlineItem::StartInlineBox(inline_box) => {
3131                // For margins and paddings, a cyclic percentage is resolved against zero
3132                // for determining intrinsic size contributions.
3133                // https://drafts.csswg.org/css-sizing-3/#min-percentage-contribution
3134                let inline_box = inline_box.borrow();
3135                let zero = Au::zero();
3136                let writing_mode = self.constraint_space.style.writing_mode;
3137                let layout_style = inline_box.layout_style();
3138                let padding = layout_style
3139                    .padding(writing_mode)
3140                    .percentages_relative_to(zero);
3141                let border = layout_style.border_width(writing_mode);
3142                let margin = inline_box
3143                    .base
3144                    .style
3145                    .margin(writing_mode)
3146                    .percentages_relative_to(zero)
3147                    .auto_is(Au::zero);
3148
3149                let pbm = margin + padding + border;
3150                self.pending_opening_pbm_for_inline_boxes += pbm.inline_start;
3151                self.current_line.max_content += pbm.inline_start;
3152                self.ending_inline_pbm_stack.push(pbm.inline_end);
3153
3154                self.text_wrap_mode_stack
3155                    .push(layout_style.style().slow_clone_text_wrap_mode());
3156            },
3157            InlineItem::EndInlineBox(..) => {
3158                let length = self.ending_inline_pbm_stack.pop().unwrap_or_else(Au::zero);
3159                self.commit_pending_opening_pbm_for_inline_boxes();
3160                self.add_inline_size(length);
3161                self.text_wrap_mode_stack.pop();
3162            },
3163            InlineItem::TextRun(text_run) => {
3164                let text_run = &*text_run.borrow();
3165                let parent_style = text_run.inline_styles().style.borrow();
3166                for item in text_run.items.iter() {
3167                    match item {
3168                        TextRunItem::LineBreak { .. } => {
3169                            // If this run is a forced line break, we *must* break the line
3170                            // and start measuring from the inline origin once more.
3171                            self.forced_line_break();
3172                        },
3173                        TextRunItem::Tab { break_at_start, .. } => self.process_preserved_tab(
3174                            &parent_style,
3175                            inline_formatting_context,
3176                            *break_at_start,
3177                        ),
3178                        TextRunItem::TextSegment(segment) => {
3179                            self.process_text_segment(&parent_style, segment)
3180                        },
3181                    }
3182                }
3183            },
3184            InlineItem::Atomic(atomic, offset_in_text, _level) => {
3185                let can_wrap = self.text_wrap_mode() == &TextWrapMode::Wrap;
3186                if can_wrap &&
3187                    self.had_content_yet_for_min_content &&
3188                    !inline_formatting_context
3189                        .previous_character_prevents_soft_wrap_opportunity(*offset_in_text)
3190                {
3191                    self.line_break_opportunity();
3192                }
3193
3194                self.commit_pending_opening_pbm_for_inline_boxes();
3195                self.commit_pending_whitespace();
3196                let outer = self.outer_inline_content_sizes_of_float_or_atomic(&atomic.borrow());
3197                self.current_line += outer;
3198
3199                if can_wrap &&
3200                    !inline_formatting_context
3201                        .next_character_prevents_soft_wrap_opportunity(*offset_in_text)
3202                {
3203                    self.line_break_opportunity();
3204                }
3205            },
3206            InlineItem::OutOfFlowFloatBox(float_box) => {
3207                let float_box = float_box.borrow();
3208                let sizes = self.outer_inline_content_sizes_of_float_or_atomic(&float_box.contents);
3209                let style = &float_box.contents.style();
3210                let container_writing_mode = self.constraint_space.style.writing_mode;
3211                let clear =
3212                    Clear::from_style_and_container_writing_mode(style, container_writing_mode);
3213                self.clear_floats(clear);
3214                let float_side =
3215                    FloatSide::from_style_and_container_writing_mode(style, container_writing_mode);
3216                match float_side.expect("A float box needs to float to some side") {
3217                    FloatSide::InlineStart => self.uncleared_floats.start.union_assign(&sizes),
3218                    FloatSide::InlineEnd => self.uncleared_floats.end.union_assign(&sizes),
3219                }
3220            },
3221            InlineItem::BlockLevel(block_level) => {
3222                self.forced_line_break();
3223                self.flush_floats();
3224                let inline_content_sizes_result =
3225                    compute_inline_content_sizes_for_block_level_boxes(
3226                        std::slice::from_ref(block_level),
3227                        self.layout_context,
3228                        &self.constraint_space.into(),
3229                    );
3230                self.depends_on_block_constraints |=
3231                    inline_content_sizes_result.depends_on_block_constraints;
3232                self.current_line = inline_content_sizes_result.sizes;
3233                self.forced_line_break();
3234            },
3235            InlineItem::OutOfFlowAbsolutelyPositionedBox(..) => {},
3236        }
3237    }
3238
3239    fn process_text_segment(
3240        &mut self,
3241        parent_style: &AtomicRef<'_, ServoArc<ComputedValues>>,
3242        segment: &TextRunSegment,
3243    ) {
3244        let style_text = parent_style.get_inherited_text();
3245        let can_wrap = style_text.text_wrap_mode == TextWrapMode::Wrap;
3246
3247        // TODO: This should take account whether or not the first and last character prevent
3248        // linebreaks after atomics as in layout.
3249        let break_at_start = segment.break_at_start && self.had_content_yet_for_min_content;
3250
3251        // From <https://drafts.csswg.org/css-text-3/#white-space-phase-2>:
3252        // > If white-space is set to pre-wrap, the UA must (unconditionally) hang
3253        // > this sequence, unless the sequence is followed by a forced line break, in
3254        // > which case it must conditionally hang the sequence instead. It may also
3255        // > visually collapse the character advance widths of any that would otherwise
3256        // > overflow.
3257        // From <https://drafts.csswg.org/css-text-3/#conditionally-hang>:
3258        // > In some cases, a glyph at the end of a line can conditionally hang: it hangs
3259        // > only if it does not otherwise fit in the line prior to justification. It is
3260        // > not considered when measuring the line’s contents for fit; however, any part
3261        // > of it that does not fit is considered to hang. Glyphs that conditionally hang
3262        // > are not taken into account when computing min-content sizes and any sizes
3263        // > derived thereof, but they are taken into account for max-content sizes and any
3264        // > sizes derived thereof.
3265        let hangable_characters_count_for_max_content =
3266            parent_style.white_space_may_hang_conditionally();
3267
3268        for (run_index, run) in segment.runs.iter().enumerate() {
3269            // Break before each unbreakable run in this TextRun, except the first unless the
3270            // linebreaker was set to break before the first run.
3271            if can_wrap && (run_index != 0 || break_at_start) {
3272                self.line_break_opportunity();
3273            }
3274
3275            let advance = run.total_advance();
3276            let removable_advance = run.removable_advance();
3277            let hangable_advance = run.hangable_advance();
3278            if run.has_non_hangable_non_removable_content() {
3279                self.commit_pending_opening_pbm_for_inline_boxes();
3280                self.commit_pending_whitespace();
3281                self.add_inline_size(advance - removable_advance - hangable_advance);
3282            }
3283
3284            self.pending_whitespace.min_content += hangable_advance;
3285            if hangable_characters_count_for_max_content {
3286                self.current_line.max_content += hangable_advance;
3287            } else {
3288                self.pending_whitespace.max_content += hangable_advance;
3289            }
3290
3291            if self.had_content_yet_for_min_content {
3292                self.pending_whitespace.min_content += removable_advance;
3293            }
3294            if self.had_content_yet_for_max_content {
3295                self.pending_whitespace.max_content += removable_advance;
3296            }
3297        }
3298    }
3299
3300    fn process_preserved_tab(
3301        &mut self,
3302        parent_style: &AtomicRef<'_, ServoArc<ComputedValues>>,
3303        inline_formatting_context: &InlineFormattingContext,
3304        break_at_start: bool,
3305    ) {
3306        let can_wrap = parent_style.get_inherited_text().text_wrap_mode == TextWrapMode::Wrap;
3307        if break_at_start && can_wrap {
3308            self.line_break_opportunity();
3309        }
3310
3311        self.commit_pending_opening_pbm_for_inline_boxes();
3312
3313        let conditionally_hangs = parent_style.white_space_may_hang_conditionally();
3314        if !conditionally_hangs {
3315            self.commit_pending_whitespace();
3316        }
3317
3318        let next_tab_stop_for_min_content = inline_formatting_context
3319            .next_tab_stop_after_inline_advance(parent_style, self.current_line.min_content);
3320        let next_tab_stop_for_max_content = inline_formatting_context
3321            .next_tab_stop_after_inline_advance(parent_style, self.current_line.max_content);
3322
3323        if conditionally_hangs {
3324            self.pending_whitespace.min_content += next_tab_stop_for_min_content;
3325        } else {
3326            self.current_line.min_content += next_tab_stop_for_min_content;
3327        }
3328        self.current_line.max_content += next_tab_stop_for_max_content;
3329
3330        if can_wrap {
3331            self.line_break_opportunity();
3332        }
3333    }
3334
3335    fn add_inline_size(&mut self, size: Au) {
3336        self.current_line.min_content += size;
3337        self.current_line.max_content += size;
3338    }
3339
3340    fn line_break_opportunity(&mut self) {
3341        // Clear the pending whitespace, assuming that at the end of the line
3342        // it needs to either hang or be removed. If that isn't the case,
3343        // `commit_pending_whitespace()` should be called first.
3344        self.pending_whitespace.min_content = Au::zero();
3345        let current_min_content = mem::take(&mut self.current_line.min_content);
3346        self.paragraph.min_content.max_assign(current_min_content);
3347        self.had_content_yet_for_min_content = false;
3348    }
3349
3350    fn forced_line_break(&mut self) {
3351        // A forced line break causes any pending open inline box padding, border,
3352        // and margin to immediately be considered part of the current line.
3353        self.commit_pending_opening_pbm_for_inline_boxes();
3354
3355        // Handle the line break for min-content sizes.
3356        self.line_break_opportunity();
3357
3358        // Repeat the same logic as `line_break_opportunity()`, but now for max-content sizes.
3359        self.pending_whitespace.max_content = Au::zero();
3360        let current_max_content = mem::take(&mut self.current_line.max_content);
3361        self.paragraph.max_content.max_assign(current_max_content);
3362        self.had_content_yet_for_max_content = false;
3363    }
3364
3365    fn commit_pending_whitespace(&mut self) {
3366        self.current_line += mem::take(&mut self.pending_whitespace);
3367        self.had_content_yet_for_min_content = true;
3368        self.had_content_yet_for_max_content = true;
3369    }
3370
3371    fn commit_pending_opening_pbm_for_inline_boxes(&mut self) {
3372        self.current_line.min_content +=
3373            std::mem::take(&mut self.pending_opening_pbm_for_inline_boxes);
3374    }
3375
3376    fn outer_inline_content_sizes_of_float_or_atomic(
3377        &mut self,
3378        context: &IndependentFormattingContext,
3379    ) -> ContentSizes {
3380        let result = context.outer_inline_content_sizes(
3381            self.layout_context,
3382            &self.constraint_space.into(),
3383            &LogicalVec2::zero(),
3384            false, /* auto_block_size_stretches_to_containing_block */
3385            skippable_for_block_percentage_quirk(self.layout_context, &context.base, Some(context)),
3386        );
3387        self.depends_on_block_constraints |= result.depends_on_block_constraints;
3388        result.sizes
3389    }
3390
3391    fn clear_floats(&mut self, clear: Clear) {
3392        match clear {
3393            Clear::InlineStart => {
3394                let start_floats = mem::take(&mut self.uncleared_floats.start);
3395                self.cleared_floats.start.max_assign(start_floats);
3396            },
3397            Clear::InlineEnd => {
3398                let end_floats = mem::take(&mut self.uncleared_floats.end);
3399                self.cleared_floats.end.max_assign(end_floats);
3400            },
3401            Clear::Both => {
3402                let start_floats = mem::take(&mut self.uncleared_floats.start);
3403                let end_floats = mem::take(&mut self.uncleared_floats.end);
3404                self.cleared_floats.start.max_assign(start_floats);
3405                self.cleared_floats.end.max_assign(end_floats);
3406            },
3407            Clear::None => {},
3408        }
3409    }
3410
3411    fn flush_floats(&mut self) {
3412        self.clear_floats(Clear::Both);
3413        let start_floats = mem::take(&mut self.cleared_floats.start);
3414        let end_floats = mem::take(&mut self.cleared_floats.end);
3415        self.paragraph.union_assign(&start_floats);
3416        self.paragraph.union_assign(&end_floats);
3417    }
3418
3419    fn text_wrap_mode(&self) -> &TextWrapMode {
3420        self.text_wrap_mode_stack
3421            .last()
3422            .unwrap_or_else(|| self.constraint_space.style.get_text_wrap_mode())
3423    }
3424
3425    /// Compute the [`ContentSizes`] of the given [`InlineFormattingContext`].
3426    fn compute(
3427        inline_formatting_context: &InlineFormattingContext,
3428        layout_context: &'layout_data LayoutContext,
3429        constraint_space: &'layout_data ConstraintSpace,
3430    ) -> InlineContentSizesResult {
3431        Self {
3432            layout_context,
3433            constraint_space,
3434            paragraph: ContentSizes::zero(),
3435            current_line: ContentSizes::zero(),
3436            pending_whitespace: ContentSizes::zero(),
3437            pending_opening_pbm_for_inline_boxes: Au::zero(),
3438            uncleared_floats: LogicalSides1D::default(),
3439            cleared_floats: LogicalSides1D::default(),
3440            had_content_yet_for_min_content: false,
3441            had_content_yet_for_max_content: false,
3442            ending_inline_pbm_stack: Vec::new(),
3443            text_wrap_mode_stack: Vec::new(),
3444            depends_on_block_constraints: false,
3445        }
3446        .traverse(inline_formatting_context)
3447    }
3448}
3449
3450pub(crate) struct BidiLevels<'a> {
3451    info: Option<BidiInfo<'a>>,
3452}
3453
3454impl BidiLevels<'_> {
3455    fn level(&self, byte_offset_in_ifc_text: usize) -> Level {
3456        self.info
3457            .as_ref()
3458            .map_or_else(Level::ltr, |info| info.levels[byte_offset_in_ifc_text])
3459    }
3460}
3461
3462/// Whether or not this character will prevent a soft wrap opportunity when it
3463/// comes before or after an atomic inline element.
3464///
3465/// From <https://www.w3.org/TR/css-text-3/#line-break-details>:
3466///
3467/// > For Web-compatibility there is a soft wrap opportunity before and after each
3468/// > replaced element or other atomic inline, even when adjacent to a character that
3469/// > would normally suppress them, including U+00A0 NO-BREAK SPACE. However, with
3470/// > the exception of U+00A0 NO-BREAK SPACE, there must be no soft wrap opportunity
3471/// > between atomic inlines and adjacent characters belonging to the Unicode GL, WJ,
3472/// > or ZWJ line breaking classes.
3473fn char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character: char) -> bool {
3474    if character == '\u{00A0}' {
3475        return false;
3476    }
3477    matches!(
3478        ICULineBreak::for_char(character),
3479        ICULineBreak::Glue | ICULineBreak::WordJoiner | ICULineBreak::ZWJ
3480    )
3481}