1pub mod construct;
72pub mod inline_box;
73pub mod line;
74mod line_breaker;
75pub mod text_run;
76
77use std::cell::{Cell, OnceCell};
78use std::mem;
79use std::rc::Rc;
80use std::sync::{Arc, OnceLock};
81
82use app_units::{Au, MAX_AU};
83use atomic_refcell::AtomicRef;
84use bitflags::bitflags;
85use construct::InlineFormattingContextBuilder;
86use fonts::{FontMetrics, FontRef, ShapedTextSlice};
87use icu_locid::LanguageIdentifier;
88use icu_locid::subtags::{Language, language};
89use icu_properties::{self, LineBreak as ICULineBreak};
90use icu_segmenter::{LineBreakOptions, LineBreakStrictness, LineBreakWordOption};
91use inline_box::{InlineBox, InlineBoxContainerState, InlineBoxIdentifier, InlineBoxes};
92use layout_api::{LayoutNode, SharedSelection};
93use line::{
94 AbsolutelyPositionedLineItem, AtomicLineItem, FloatLineItem, LineItem, LineItemLayout,
95 TextRunLineItem,
96};
97use line_breaker::LineBreaker;
98use malloc_size_of_derive::MallocSizeOf;
99use script::layout_dom::ServoLayoutNode;
100use servo_arc::Arc as ServoArc;
101use style::Zero;
102use style::computed_values::line_break::T as LineBreak;
103use style::computed_values::text_wrap_mode::T as TextWrapMode;
104use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
105use style::computed_values::word_break::T as WordBreak;
106use style::context::{QuirksMode, SharedStyleContext};
107use style::properties::ComputedValues;
108use style::properties::style_structs::InheritedText;
109use style::values::computed::BaselineShift;
110use style::values::generics::box_::BaselineShiftKeyword;
111use style::values::generics::font::LineHeight;
112use style::values::specified::box_::BaselineSource;
113use style::values::specified::text::TextAlignKeyword;
114use style::values::specified::{AlignmentBaseline, TextAlignLast, TextJustify};
115use text_run::{TextRun, get_font_for_first_font_for_style};
116use unicode_bidi::{BidiInfo, Level};
117
118use super::float::{Clear, PlacementAmongFloats};
119use super::{IndependentFloatOrAtomicLayoutResult, IndependentFormattingContextLayoutResult};
120use crate::cell::{ArcRefCell, WeakRefCell};
121use crate::context::LayoutContext;
122use crate::dom::WeakLayoutBox;
123use crate::dom_traversal::NodeAndStyleInfo;
124use crate::flow::float::{FloatBox, SequentialLayoutState};
125use crate::flow::inline::line::TextRunOffsets;
126use crate::flow::inline::text_run::{FontAndScriptInfo, TextRunItem, TextRunSegment};
127use crate::flow::{
128 BlockLevelBox, CollapsibleWithParentStartMargin, FloatSide, PlacementState,
129 compute_inline_content_sizes_for_block_level_boxes, layout_block_level_child,
130};
131use crate::formatting_contexts::{Baselines, IndependentFormattingContext};
132use crate::fragment_tree::{
133 BaseFragmentInfo, BoxFragment, CollapsedMargin, Fragment, FragmentFlags, PositioningFragment,
134};
135use crate::geom::{LogicalRect, LogicalSides1D, LogicalVec2, ToLogical};
136use crate::layout_box_base::LayoutBoxBase;
137use crate::positioned::{AbsolutelyPositionedBox, PositioningContext};
138use crate::sizing::{ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult};
139use crate::style_ext::{ComputedValuesExt, PaddingBorderMargin};
140use crate::{ConstraintSpace, ContainingBlock, IndefiniteContainingBlock, SharedStyle};
141
142static FONT_SUBSCRIPT_OFFSET_RATIO: f32 = 0.20;
144static FONT_SUPERSCRIPT_OFFSET_RATIO: f32 = 0.34;
145
146#[derive(Debug, MallocSizeOf)]
147pub(crate) struct InlineFormattingContext {
148 inline_items: Vec<InlineItem>,
153
154 inline_boxes: InlineBoxes,
157
158 text_content: String,
160
161 shared_inline_styles: SharedInlineStyles,
164
165 default_font: Option<FontRef>,
169
170 has_first_formatted_line: bool,
173
174 pub(super) contains_floats: bool,
176
177 is_single_line_text_input: bool,
180
181 has_right_to_left_content: bool,
184
185 #[ignore_malloc_size_of = "This is stored primarily in the DOM"]
188 shared_selection: Option<SharedSelection>,
189
190 tab_size_multiplier: OnceLock<Au>,
195}
196
197#[derive(Clone, Debug, MallocSizeOf)]
202pub(crate) struct SharedInlineStyles {
203 pub style: SharedStyle,
204 pub selected: SharedStyle,
205}
206
207impl SharedInlineStyles {
208 pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
209 self.style.ptr_eq(&other.style) && self.selected.ptr_eq(&other.selected)
210 }
211
212 pub(crate) fn from_info_and_context(info: &NodeAndStyleInfo, context: &LayoutContext) -> Self {
213 Self {
214 style: SharedStyle::new(info.style.clone()),
215 selected: SharedStyle::new(info.node.selected_style(&context.style_context)),
216 }
217 }
218}
219
220impl BlockLevelBox {
221 fn layout_into_line_items(&self, layout: &mut InlineFormattingContextLayout) {
222 layout.process_soft_wrap_opportunity();
223 layout.commit_current_segment_to_line();
224 layout.process_line_break(true);
225 layout.current_line.for_block_level = true;
226
227 let fragment = layout_block_level_child(
228 layout.layout_context,
229 layout.positioning_context,
230 self,
231 layout.sequential_layout_state.as_deref_mut(),
232 &mut layout.placement_state,
233 LogicalSides1D::new(false, false),
235 true, );
237
238 let Some(fragment) = fragment.retrieve_box_fragment() else {
239 unreachable!("The fragment should be a Fragment::Box()");
240 };
241
242 layout.depends_on_block_constraints |= fragment.base.flags.contains(
245 FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
246 );
247
248 layout.push_line_item_to_unbreakable_segment(LineItem::BlockLevel(
249 layout.current_inline_box_identifier(),
250 fragment.clone(),
251 ));
252
253 layout.commit_current_segment_to_line();
254 layout.process_line_break(true);
255 layout.current_line.for_block_level = false;
256 }
257}
258
259#[derive(Clone, Debug, MallocSizeOf)]
260pub(crate) enum InlineItem {
261 StartInlineBox(ArcRefCell<InlineBox>),
262 EndInlineBox,
263 TextRun(ArcRefCell<TextRun>),
264 OutOfFlowAbsolutelyPositionedBox(
265 ArcRefCell<AbsolutelyPositionedBox>,
266 usize, ),
268 OutOfFlowFloatBox(ArcRefCell<FloatBox>),
269 Atomic(
270 ArcRefCell<IndependentFormattingContext>,
271 usize, Level, ),
274 BlockLevel(ArcRefCell<BlockLevelBox>),
275}
276
277impl InlineItem {
278 pub(crate) fn repair_style(
279 &self,
280 context: &SharedStyleContext,
281 node: &ServoLayoutNode,
282 new_style: &ServoArc<ComputedValues>,
283 ) {
284 match self {
285 InlineItem::StartInlineBox(inline_box) => {
286 inline_box
287 .borrow_mut()
288 .repair_style(context, node, new_style);
289 },
290 InlineItem::EndInlineBox => {},
291 InlineItem::TextRun(..) => {},
294 InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => positioned_box
295 .borrow_mut()
296 .context
297 .repair_style(context, node, new_style),
298 InlineItem::OutOfFlowFloatBox(float_box) => float_box
299 .borrow_mut()
300 .contents
301 .repair_style(context, node, new_style),
302 InlineItem::Atomic(atomic, ..) => {
303 atomic.borrow_mut().repair_style(context, node, new_style)
304 },
305 InlineItem::BlockLevel(block_level) => block_level
306 .borrow_mut()
307 .repair_style(context, node, new_style),
308 }
309 }
310
311 pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> T {
312 match self {
313 InlineItem::StartInlineBox(inline_box) => callback(&inline_box.borrow().base),
314 InlineItem::EndInlineBox | InlineItem::TextRun(..) => {
315 unreachable!("Should never have these kind of fragments attached to a DOM node")
316 },
317 InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
318 callback(&positioned_box.borrow().context.base)
319 },
320 InlineItem::OutOfFlowFloatBox(float_box) => callback(&float_box.borrow().contents.base),
321 InlineItem::Atomic(independent_formatting_context, ..) => {
322 callback(&independent_formatting_context.borrow().base)
323 },
324 InlineItem::BlockLevel(block_level) => block_level.borrow().with_base(callback),
325 }
326 }
327
328 pub(crate) fn with_base_mut<T>(&self, callback: impl FnOnce(&mut LayoutBoxBase) -> T) -> T {
329 match self {
330 InlineItem::StartInlineBox(inline_box) => callback(&mut inline_box.borrow_mut().base),
331 InlineItem::EndInlineBox | InlineItem::TextRun(..) => {
332 unreachable!("Should never have these kind of fragments attached to a DOM node")
333 },
334 InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
335 callback(&mut positioned_box.borrow_mut().context.base)
336 },
337 InlineItem::OutOfFlowFloatBox(float_box) => {
338 callback(&mut float_box.borrow_mut().contents.base)
339 },
340 InlineItem::Atomic(independent_formatting_context, ..) => {
341 callback(&mut independent_formatting_context.borrow_mut().base)
342 },
343 InlineItem::BlockLevel(block_level) => block_level.borrow_mut().with_base_mut(callback),
344 }
345 }
346
347 pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
348 match self {
349 Self::StartInlineBox(_) | InlineItem::EndInlineBox => {
350 },
353 Self::TextRun(_) => {
354 },
356 Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
357 positioned_box.borrow().context.attached_to_tree(layout_box)
358 },
359 Self::OutOfFlowFloatBox(float_box) => {
360 float_box.borrow().contents.attached_to_tree(layout_box)
361 },
362 Self::Atomic(atomic, ..) => atomic.borrow().attached_to_tree(layout_box),
363 Self::BlockLevel(block_level) => block_level.borrow().attached_to_tree(layout_box),
364 }
365 }
366
367 pub(crate) fn downgrade(&self) -> WeakInlineItem {
368 match self {
369 Self::StartInlineBox(inline_box) => {
370 WeakInlineItem::StartInlineBox(inline_box.downgrade())
371 },
372 Self::EndInlineBox => WeakInlineItem::EndInlineBox,
373 Self::TextRun(text_run) => WeakInlineItem::TextRun(text_run.downgrade()),
374 Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, offset_in_text) => {
375 WeakInlineItem::OutOfFlowAbsolutelyPositionedBox(
376 positioned_box.downgrade(),
377 *offset_in_text,
378 )
379 },
380 Self::OutOfFlowFloatBox(float_box) => {
381 WeakInlineItem::OutOfFlowFloatBox(float_box.downgrade())
382 },
383 Self::Atomic(atomic, offset_in_text, bidi_level) => {
384 WeakInlineItem::Atomic(atomic.downgrade(), *offset_in_text, *bidi_level)
385 },
386 Self::BlockLevel(block_level) => WeakInlineItem::BlockLevel(block_level.downgrade()),
387 }
388 }
389}
390
391#[derive(Clone, Debug, MallocSizeOf)]
392pub(crate) enum WeakInlineItem {
393 StartInlineBox(WeakRefCell<InlineBox>),
394 EndInlineBox,
395 TextRun(WeakRefCell<TextRun>),
396 OutOfFlowAbsolutelyPositionedBox(
397 WeakRefCell<AbsolutelyPositionedBox>,
398 usize, ),
400 OutOfFlowFloatBox(WeakRefCell<FloatBox>),
401 Atomic(
402 WeakRefCell<IndependentFormattingContext>,
403 usize, Level, ),
406 BlockLevel(WeakRefCell<BlockLevelBox>),
407}
408
409impl WeakInlineItem {
410 pub(crate) fn upgrade(&self) -> Option<InlineItem> {
411 Some(match self {
412 Self::StartInlineBox(inline_box) => InlineItem::StartInlineBox(inline_box.upgrade()?),
413 Self::EndInlineBox => InlineItem::EndInlineBox,
414 Self::TextRun(text_run) => InlineItem::TextRun(text_run.upgrade()?),
415 Self::OutOfFlowAbsolutelyPositionedBox(positioned_box, offset_in_text) => {
416 InlineItem::OutOfFlowAbsolutelyPositionedBox(
417 positioned_box.upgrade()?,
418 *offset_in_text,
419 )
420 },
421 Self::OutOfFlowFloatBox(float_box) => {
422 InlineItem::OutOfFlowFloatBox(float_box.upgrade()?)
423 },
424 Self::Atomic(atomic, offset_in_text, bidi_level) => {
425 InlineItem::Atomic(atomic.upgrade()?, *offset_in_text, *bidi_level)
426 },
427 Self::BlockLevel(block_level) => InlineItem::BlockLevel(block_level.upgrade()?),
428 })
429 }
430}
431
432struct LineUnderConstruction {
439 start_position: LogicalVec2<Au>,
442
443 inline_position: Au,
446
447 max_block_size: LineBlockSizes,
451
452 has_content: bool,
455
456 has_inline_pbm: bool,
459
460 has_floats_waiting_to_be_placed: bool,
464
465 placement_among_floats: OnceCell<LogicalRect<Au>>,
470
471 line_items: Vec<LineItem>,
474
475 for_block_level: bool,
477
478 starting_character_offset: usize,
487}
488
489impl LineUnderConstruction {
490 fn new(start_position: LogicalVec2<Au>) -> Self {
491 Self {
492 inline_position: start_position.inline,
493 start_position,
494 max_block_size: LineBlockSizes::zero(),
495 has_content: false,
496 has_inline_pbm: false,
497 has_floats_waiting_to_be_placed: false,
498 placement_among_floats: OnceCell::new(),
499 line_items: Vec::new(),
500 for_block_level: false,
501 starting_character_offset: 0,
502 }
503 }
504
505 fn replace_placement_among_floats(&mut self, new_placement: LogicalRect<Au>) {
506 self.placement_among_floats.take();
507 let _ = self.placement_among_floats.set(new_placement);
508 }
509
510 fn trim_trailing_whitespace(&mut self) -> Au {
512 let mut whitespace_trimmed = Au::zero();
517 for item in self.line_items.iter_mut().rev() {
518 if !item.trim_whitespace_at_end(&mut whitespace_trimmed) {
519 break;
520 }
521 }
522
523 whitespace_trimmed
524 }
525
526 fn count_justification_opportunities(&self) -> usize {
528 self.line_items
529 .iter()
530 .filter_map(|item| match item {
531 LineItem::TextRun(_, text_run) => Some(
532 text_run
533 .text
534 .iter()
535 .map(|shaped_text_slice| shaped_text_slice.total_word_separators())
536 .sum::<usize>(),
537 ),
538 _ => None,
539 })
540 .sum()
541 }
542
543 fn is_phantom(&self) -> bool {
546 !self.has_content && !self.has_inline_pbm
548 }
549}
550
551#[derive(Clone, Debug)]
557struct BaselineRelativeSize {
558 ascent: Au,
562
563 descent: Au,
567}
568
569impl BaselineRelativeSize {
570 fn zero() -> Self {
571 Self {
572 ascent: Au::zero(),
573 descent: Au::zero(),
574 }
575 }
576
577 fn max(&self, other: &Self) -> Self {
578 BaselineRelativeSize {
579 ascent: self.ascent.max(other.ascent),
580 descent: self.descent.max(other.descent),
581 }
582 }
583
584 fn adjust_for_nested_baseline_offset(&mut self, baseline_offset: Au) {
598 self.ascent -= baseline_offset;
599 self.descent += baseline_offset;
600 }
601}
602
603#[derive(Clone, Debug)]
604struct LineBlockSizes {
605 line_height: Au,
606 baseline_relative_size_for_line_height: Option<BaselineRelativeSize>,
607 size_for_baseline_positioning: BaselineRelativeSize,
608}
609
610impl LineBlockSizes {
611 fn zero() -> Self {
612 LineBlockSizes {
613 line_height: Au::zero(),
614 baseline_relative_size_for_line_height: None,
615 size_for_baseline_positioning: BaselineRelativeSize::zero(),
616 }
617 }
618
619 fn resolve(&self) -> Au {
620 let height_from_ascent_and_descent = self
621 .baseline_relative_size_for_line_height
622 .as_ref()
623 .map(|size| (size.ascent + size.descent).abs())
624 .unwrap_or_else(Au::zero);
625 self.line_height.max(height_from_ascent_and_descent)
626 }
627
628 fn max(&self, other: &LineBlockSizes) -> LineBlockSizes {
629 let baseline_relative_size = match (
630 self.baseline_relative_size_for_line_height.as_ref(),
631 other.baseline_relative_size_for_line_height.as_ref(),
632 ) {
633 (Some(our_size), Some(other_size)) => Some(our_size.max(other_size)),
634 (our_size, other_size) => our_size.or(other_size).cloned(),
635 };
636 Self {
637 line_height: self.line_height.max(other.line_height),
638 baseline_relative_size_for_line_height: baseline_relative_size,
639 size_for_baseline_positioning: self
640 .size_for_baseline_positioning
641 .max(&other.size_for_baseline_positioning),
642 }
643 }
644
645 fn max_assign(&mut self, other: &LineBlockSizes) {
646 *self = self.max(other);
647 }
648
649 fn adjust_for_baseline_offset(&mut self, baseline_offset: Au) {
650 if let Some(size) = self.baseline_relative_size_for_line_height.as_mut() {
651 size.adjust_for_nested_baseline_offset(baseline_offset)
652 }
653 self.size_for_baseline_positioning
654 .adjust_for_nested_baseline_offset(baseline_offset);
655 }
656
657 fn find_baseline_offset(&self) -> Au {
664 match self.baseline_relative_size_for_line_height.as_ref() {
665 Some(size) => size.ascent,
666 None => {
667 let leading = self.resolve() -
670 (self.size_for_baseline_positioning.ascent +
671 self.size_for_baseline_positioning.descent);
672 leading.scale_by(0.5) + self.size_for_baseline_positioning.ascent
673 },
674 }
675 }
676}
677
678struct UnbreakableSegmentUnderConstruction {
682 inline_size: Au,
684
685 max_block_size: LineBlockSizes,
688
689 line_items: Vec<LineItem>,
691
692 inline_box_hierarchy_depth: Option<usize>,
695
696 has_content: bool,
700
701 has_inline_pbm: bool,
704
705 trailing_whitespace_size: Au,
707}
708
709impl UnbreakableSegmentUnderConstruction {
710 fn new() -> Self {
711 Self {
712 inline_size: Au::zero(),
713 max_block_size: LineBlockSizes {
714 line_height: Au::zero(),
715 baseline_relative_size_for_line_height: None,
716 size_for_baseline_positioning: BaselineRelativeSize::zero(),
717 },
718 line_items: Vec::new(),
719 inline_box_hierarchy_depth: None,
720 has_content: false,
721 has_inline_pbm: false,
722 trailing_whitespace_size: Au::zero(),
723 }
724 }
725
726 fn reset(&mut self) {
728 assert!(self.line_items.is_empty()); self.inline_size = Au::zero();
730 self.max_block_size = LineBlockSizes::zero();
731 self.inline_box_hierarchy_depth = None;
732 self.has_content = false;
733 self.has_inline_pbm = false;
734 self.trailing_whitespace_size = Au::zero();
735 }
736
737 fn push_line_item(&mut self, line_item: LineItem, inline_box_hierarchy_depth: usize) {
742 if self.line_items.is_empty() {
743 self.inline_box_hierarchy_depth = Some(inline_box_hierarchy_depth);
744 }
745 self.line_items.push(line_item);
746 }
747
748 fn trim_leading_whitespace(&mut self) {
759 let mut whitespace_trimmed = Au::zero();
760 for item in self.line_items.iter_mut() {
761 if !item.trim_whitespace_at_start(&mut whitespace_trimmed) {
762 break;
763 }
764 }
765 self.inline_size -= whitespace_trimmed;
766 }
767
768 fn is_phantom(&self) -> bool {
771 !self.has_content && !self.has_inline_pbm
773 }
774}
775
776bitflags! {
777 struct InlineContainerStateFlags: u8 {
778 const CREATE_STRUT = 0b0001;
779 const IS_SINGLE_LINE_TEXT_INPUT = 0b0010;
780 }
781}
782
783struct InlineContainerState {
784 style: ServoArc<ComputedValues>,
786
787 flags: InlineContainerStateFlags,
789
790 has_content: Cell<bool>,
793
794 strut_block_sizes: LineBlockSizes,
799
800 nested_strut_block_sizes: LineBlockSizes,
804
805 pub baseline_offset: Au,
811
812 default_font: Option<FontRef>,
815
816 font_metrics: Arc<FontMetrics>,
818}
819
820struct InlineFormattingContextLayout<'layout_data> {
821 positioning_context: &'layout_data mut PositioningContext,
822 placement_state: PlacementState<'layout_data>,
823 sequential_layout_state: Option<&'layout_data mut SequentialLayoutState>,
824 layout_context: &'layout_data LayoutContext<'layout_data>,
825
826 ifc: &'layout_data InlineFormattingContext,
828
829 root_nesting_level: InlineContainerState,
839
840 inline_box_state_stack: Vec<Rc<InlineBoxContainerState>>,
844
845 inline_box_states: Vec<Rc<InlineBoxContainerState>>,
850
851 fragments: Vec<Fragment>,
855
856 current_line: LineUnderConstruction,
858
859 current_line_segment: UnbreakableSegmentUnderConstruction,
861
862 force_line_break_before_new_content: Option<usize>,
885
886 deferred_br_clear: Clear,
890
891 pub have_deferred_soft_wrap_opportunity: bool,
895
896 depends_on_block_constraints: bool,
899
900 white_space_collapse: WhiteSpaceCollapse,
905
906 text_wrap_mode: TextWrapMode,
911}
912
913impl InlineFormattingContextLayout<'_> {
914 fn current_inline_container_state(&self) -> &InlineContainerState {
915 match self.inline_box_state_stack.last() {
916 Some(inline_box_state) => &inline_box_state.base,
917 None => &self.root_nesting_level,
918 }
919 }
920
921 fn current_inline_box_identifier(&self) -> Option<InlineBoxIdentifier> {
922 self.inline_box_state_stack
923 .last()
924 .map(|state| state.identifier)
925 }
926
927 fn current_line_max_block_size_including_nested_containers(&self) -> LineBlockSizes {
928 self.current_inline_container_state()
929 .nested_strut_block_sizes
930 .max(&self.current_line.max_block_size)
931 }
932
933 fn current_line_block_start_considering_placement_among_floats(&self) -> Au {
934 self.current_line.placement_among_floats.get().map_or(
935 self.current_line.start_position.block,
936 |placement_among_floats| placement_among_floats.start_corner.block,
937 )
938 }
939
940 fn propagate_current_nesting_level_white_space_style(&mut self) {
941 let style = match self.inline_box_state_stack.last() {
942 Some(inline_box_state) => &inline_box_state.base.style,
943 None => self.placement_state.containing_block.style,
944 };
945 let style_text = style.get_inherited_text();
946 self.white_space_collapse = style_text.white_space_collapse;
947 self.text_wrap_mode = style_text.text_wrap_mode;
948 }
949
950 fn processing_br_element(&self) -> bool {
951 self.inline_box_state_stack.last().is_some_and(|state| {
952 state
953 .base_fragment_info
954 .flags
955 .contains(FragmentFlags::IS_BR_ELEMENT)
956 })
957 }
958
959 fn start_inline_box(&mut self, inline_box: &InlineBox) {
962 let containing_block = self.containing_block();
963 let inline_box_state = InlineBoxContainerState::new(
964 inline_box,
965 containing_block,
966 self.layout_context,
967 self.current_inline_container_state(),
968 inline_box.default_font.clone(),
969 );
970
971 self.depends_on_block_constraints |= inline_box
972 .base
973 .style
974 .depends_on_block_constraints_due_to_relative_positioning(
975 containing_block.style.writing_mode,
976 );
977
978 if inline_box_state
983 .base_fragment_info
984 .flags
985 .contains(FragmentFlags::IS_BR_ELEMENT) &&
986 self.deferred_br_clear == Clear::None
987 {
988 self.deferred_br_clear = Clear::from_style_and_container_writing_mode(
989 &inline_box_state.base.style,
990 self.containing_block().style.writing_mode,
991 );
992 }
993
994 let padding = inline_box_state.pbm.padding.inline_start;
995 let border = inline_box_state.pbm.border.inline_start;
996 let margin = inline_box_state.pbm.margin.inline_start.auto_is(Au::zero);
997 if !padding.is_zero() || !border.is_zero() || !margin.is_zero() {
1000 self.current_line_segment.has_inline_pbm = true;
1001 }
1002 self.current_line_segment.inline_size += padding + border + margin;
1003 self.current_line_segment
1004 .line_items
1005 .push(LineItem::InlineStartBoxPaddingBorderMargin(
1006 inline_box.identifier,
1007 ));
1008
1009 let inline_box_state = Rc::new(inline_box_state);
1010
1011 assert_eq!(
1015 self.inline_box_states.len(),
1016 inline_box.identifier.index_in_inline_boxes as usize
1017 );
1018 self.inline_box_states.push(inline_box_state.clone());
1019 self.inline_box_state_stack.push(inline_box_state);
1020 }
1021
1022 fn finish_inline_box(&mut self) {
1025 let inline_box_state = match self.inline_box_state_stack.pop() {
1026 Some(inline_box_state) => inline_box_state,
1027 None => return, };
1029
1030 self.current_line_segment
1031 .max_block_size
1032 .max_assign(&inline_box_state.base.nested_strut_block_sizes);
1033
1034 if inline_box_state.base.has_content.get() {
1039 self.propagate_current_nesting_level_white_space_style();
1040 }
1041
1042 let padding = inline_box_state.pbm.padding.inline_end;
1043 let border = inline_box_state.pbm.border.inline_end;
1044 let margin = inline_box_state.pbm.margin.inline_end.auto_is(Au::zero);
1045 if !padding.is_zero() || !border.is_zero() || !margin.is_zero() {
1048 self.current_line_segment.has_inline_pbm = true;
1049 }
1050 self.current_line_segment.inline_size += padding + border + margin;
1051 self.current_line_segment
1052 .line_items
1053 .push(LineItem::InlineEndBoxPaddingBorderMargin(
1054 inline_box_state.identifier,
1055 ))
1056 }
1057
1058 fn finish_last_line(&mut self) {
1059 self.possibly_flush_deferred_forced_line_break();
1061
1062 self.process_soft_wrap_opportunity();
1068
1069 self.commit_current_segment_to_line();
1072
1073 self.finish_current_line_and_reset(true );
1076 }
1077
1078 fn finish_current_line_and_reset(&mut self, last_line_or_forced_line_break: bool) {
1082 self.possibly_push_empty_text_run_to_line_for_text_caret();
1083
1084 let whitespace_trimmed = self.current_line.trim_trailing_whitespace();
1085 let (inline_start_position, justification_adjustment) = self
1086 .calculate_current_line_inline_start_and_justification_adjustment(
1087 whitespace_trimmed,
1088 last_line_or_forced_line_break,
1089 );
1090
1091 let is_phantom_line = self.current_line.is_phantom();
1100 if !is_phantom_line {
1101 self.current_line.start_position.block += self.placement_state.current_margin.solve();
1102 self.placement_state.current_margin = CollapsedMargin::zero();
1103 }
1104 let block_start_position =
1105 self.current_line_block_start_considering_placement_among_floats();
1106
1107 let effective_block_advance = if is_phantom_line {
1108 LineBlockSizes::zero()
1109 } else {
1110 self.current_line_max_block_size_including_nested_containers()
1111 };
1112
1113 let resolved_block_advance = effective_block_advance.resolve();
1114 let block_end_position = if self.current_line.for_block_level {
1115 self.placement_state.current_block_direction_position
1116 } else {
1117 let mut block_end_position = block_start_position + resolved_block_advance;
1118 if let Some(sequential_layout_state) = self.sequential_layout_state.as_mut() {
1119 if !is_phantom_line {
1120 sequential_layout_state.commit_margin();
1121 }
1122
1123 let increment = block_end_position - self.current_line.start_position.block;
1126 sequential_layout_state.advance_block_position(increment);
1127
1128 if let Some(clearance) = sequential_layout_state
1132 .calculate_clearance(self.deferred_br_clear, &CollapsedMargin::zero())
1133 {
1134 sequential_layout_state.advance_block_position(clearance);
1135 block_end_position += clearance;
1136 };
1137 self.deferred_br_clear = Clear::None;
1138 }
1139 block_end_position
1140 };
1141
1142 let line_to_layout = std::mem::replace(
1144 &mut self.current_line,
1145 LineUnderConstruction::new(LogicalVec2 {
1146 inline: Au::zero(),
1147 block: block_end_position,
1148 }),
1149 );
1150 if !line_to_layout.for_block_level {
1151 self.placement_state.current_block_direction_position = block_end_position;
1152 }
1153
1154 if line_to_layout.has_floats_waiting_to_be_placed {
1155 place_pending_floats(self, &line_to_layout.line_items);
1156 }
1157
1158 let start_position = LogicalVec2 {
1159 block: block_start_position,
1160 inline: inline_start_position,
1161 };
1162
1163 let baseline_offset = effective_block_advance.find_baseline_offset();
1164 let start_positioning_context_length = self.positioning_context.len();
1165 let fragments = LineItemLayout::layout_line_items(
1166 self,
1167 line_to_layout.line_items,
1168 start_position,
1169 &effective_block_advance,
1170 justification_adjustment,
1171 is_phantom_line,
1172 );
1173
1174 if !is_phantom_line {
1175 let baseline = baseline_offset + block_start_position;
1176 self.placement_state
1177 .inflow_baselines
1178 .first
1179 .get_or_insert(baseline);
1180 self.placement_state.inflow_baselines.last = Some(baseline);
1181 self.placement_state
1182 .next_in_flow_margin_collapses_with_parent_start_margin = false;
1183 }
1184
1185 if fragments.is_empty() &&
1187 self.positioning_context.len() == start_positioning_context_length
1188 {
1189 return;
1190 }
1191
1192 let start_corner = LogicalVec2 {
1196 inline: Au::zero(),
1197 block: block_start_position,
1198 };
1199
1200 let logical_origin_in_physical_coordinates =
1201 start_corner.to_physical_vector(self.containing_block().style.writing_mode);
1202 self.positioning_context
1203 .adjust_static_position_of_hoisted_fragments_with_offset(
1204 &logical_origin_in_physical_coordinates,
1205 start_positioning_context_length,
1206 );
1207
1208 let containing_block = self.containing_block();
1209 let physical_line_rect = LogicalRect {
1210 start_corner,
1211 size: LogicalVec2 {
1212 inline: containing_block.size.inline,
1213 block: effective_block_advance.resolve(),
1214 },
1215 }
1216 .as_physical(Some(containing_block));
1217 self.fragments
1218 .push(Fragment::Positioning(PositioningFragment::new_anonymous(
1219 self.root_nesting_level.style.clone(),
1220 physical_line_rect,
1221 fragments,
1222 true, )));
1224 }
1225
1226 fn calculate_current_line_inline_start_and_justification_adjustment(
1231 &self,
1232 whitespace_trimmed: Au,
1233 last_line_or_forced_line_break: bool,
1234 ) -> (Au, Au) {
1235 enum TextAlign {
1236 Start,
1237 Center,
1238 End,
1239 }
1240 let containing_block = self.containing_block();
1241 let style = containing_block.style;
1242 let mut text_align_keyword = style.clone_text_align();
1243
1244 if last_line_or_forced_line_break {
1245 text_align_keyword = match style.clone_text_align_last() {
1246 TextAlignLast::Auto if text_align_keyword == TextAlignKeyword::Justify => {
1247 TextAlignKeyword::Start
1248 },
1249 TextAlignLast::Auto => text_align_keyword,
1250 TextAlignLast::Start => TextAlignKeyword::Start,
1251 TextAlignLast::End => TextAlignKeyword::End,
1252 TextAlignLast::Left => TextAlignKeyword::Left,
1253 TextAlignLast::Right => TextAlignKeyword::Right,
1254 TextAlignLast::Center => TextAlignKeyword::Center,
1255 TextAlignLast::Justify => TextAlignKeyword::Justify,
1256 };
1257 }
1258
1259 let text_align = match text_align_keyword {
1260 TextAlignKeyword::Start => TextAlign::Start,
1261 TextAlignKeyword::Center | TextAlignKeyword::MozCenter => TextAlign::Center,
1262 TextAlignKeyword::End => TextAlign::End,
1263 TextAlignKeyword::Left | TextAlignKeyword::MozLeft => {
1264 if style.writing_mode.line_left_is_inline_start() {
1265 TextAlign::Start
1266 } else {
1267 TextAlign::End
1268 }
1269 },
1270 TextAlignKeyword::Right | TextAlignKeyword::MozRight => {
1271 if style.writing_mode.line_left_is_inline_start() {
1272 TextAlign::End
1273 } else {
1274 TextAlign::Start
1275 }
1276 },
1277 TextAlignKeyword::Justify => TextAlign::Start,
1278 };
1279
1280 let (line_start, available_space) = match self.current_line.placement_among_floats.get() {
1281 Some(placement_among_floats) => (
1282 placement_among_floats.start_corner.inline,
1283 placement_among_floats.size.inline,
1284 ),
1285 None => (Au::zero(), containing_block.size.inline),
1286 };
1287
1288 let text_indent = self.current_line.start_position.inline;
1295 let line_length = self.current_line.inline_position - whitespace_trimmed - text_indent;
1296 let adjusted_line_start = line_start +
1297 match text_align {
1298 TextAlign::Start => text_indent,
1299 TextAlign::End => (available_space - line_length).max(text_indent),
1300 TextAlign::Center => (available_space - line_length + text_indent)
1301 .scale_by(0.5)
1302 .max(text_indent),
1303 };
1304
1305 let text_justify = containing_block.style.clone_text_justify();
1309 let justification_adjustment = match (text_align_keyword, text_justify) {
1310 (TextAlignKeyword::Justify, TextJustify::None) => Au::zero(),
1313 (TextAlignKeyword::Justify, _) => {
1314 match self.current_line.count_justification_opportunities() {
1315 0 => Au::zero(),
1316 num_justification_opportunities => {
1317 (available_space - text_indent - line_length)
1318 .scale_by(1. / num_justification_opportunities as f32)
1319 },
1320 }
1321 },
1322 _ => Au::zero(),
1323 };
1324
1325 let justification_adjustment = justification_adjustment.max(Au::zero());
1328
1329 (adjusted_line_start, justification_adjustment)
1330 }
1331
1332 fn place_float_fragment(&mut self, fragment: &BoxFragment) {
1333 let state = self
1334 .sequential_layout_state
1335 .as_mut()
1336 .expect("Tried to lay out a float with no sequential placement state!");
1337
1338 let block_offset_from_containining_block_top = state
1339 .current_block_position_including_margins() -
1340 state.current_containing_block_offset();
1341 state.place_float_fragment(
1342 fragment,
1343 self.placement_state.containing_block,
1344 CollapsedMargin::zero(),
1345 block_offset_from_containining_block_top,
1346 );
1347 }
1348
1349 fn place_float_line_item_for_commit_to_line(
1358 &mut self,
1359 float_item: &mut FloatLineItem,
1360 line_inline_size_without_trailing_whitespace: Au,
1361 ) {
1362 let containing_block = self.containing_block();
1363 let float_fragment = &float_item.fragment;
1364 let logical_margin_rect_size = float_fragment
1365 .margin_rect()
1366 .size
1367 .to_logical(containing_block.style.writing_mode);
1368 let inline_size = logical_margin_rect_size.inline.max(Au::zero());
1369
1370 let available_inline_size = match self.current_line.placement_among_floats.get() {
1371 Some(placement_among_floats) => placement_among_floats.size.inline,
1372 None => containing_block.size.inline,
1373 } - line_inline_size_without_trailing_whitespace;
1374
1375 let has_content = self.current_line.has_content || self.current_line_segment.has_content;
1381 let fits_on_line = !has_content || inline_size <= available_inline_size;
1382 let needs_placement_later =
1383 self.current_line.has_floats_waiting_to_be_placed || !fits_on_line;
1384
1385 if needs_placement_later {
1386 self.current_line.has_floats_waiting_to_be_placed = true;
1387 } else {
1388 self.place_float_fragment(float_fragment);
1389 float_item.needs_placement = false;
1390 }
1391
1392 let new_placement = self.place_line_among_floats(&LogicalVec2 {
1397 inline: line_inline_size_without_trailing_whitespace,
1398 block: self.current_line.max_block_size.resolve(),
1399 });
1400 self.current_line
1401 .replace_placement_among_floats(new_placement);
1402 }
1403
1404 fn place_line_among_floats(&self, potential_line_size: &LogicalVec2<Au>) -> LogicalRect<Au> {
1409 let sequential_layout_state = self
1410 .sequential_layout_state
1411 .as_ref()
1412 .expect("Should not have called this function without having floats.");
1413
1414 let ifc_offset_in_float_container = LogicalVec2 {
1415 inline: sequential_layout_state
1416 .floats
1417 .containing_block_info
1418 .inline_start,
1419 block: sequential_layout_state.current_containing_block_offset(),
1420 };
1421
1422 let ceiling = self.current_line_block_start_considering_placement_among_floats();
1423 let mut placement = PlacementAmongFloats::new(
1424 &sequential_layout_state.floats,
1425 ceiling + ifc_offset_in_float_container.block,
1426 LogicalVec2 {
1427 inline: potential_line_size.inline,
1428 block: potential_line_size.block,
1429 },
1430 &PaddingBorderMargin::zero(),
1431 );
1432
1433 let mut placement_rect = placement.place();
1434 placement_rect.start_corner -= ifc_offset_in_float_container;
1435 placement_rect
1436 }
1437
1438 fn new_potential_line_size_causes_line_break(
1445 &mut self,
1446 potential_line_size: &LogicalVec2<Au>,
1447 ) -> bool {
1448 let containing_block = self.containing_block();
1449 let available_line_space = if self.sequential_layout_state.is_some() {
1450 self.current_line
1451 .placement_among_floats
1452 .get_or_init(|| self.place_line_among_floats(potential_line_size))
1453 .size
1454 } else {
1455 LogicalVec2 {
1456 inline: containing_block.size.inline,
1457 block: MAX_AU,
1458 }
1459 };
1460
1461 let inline_would_overflow = potential_line_size.inline > available_line_space.inline;
1462 let block_would_overflow = potential_line_size.block > available_line_space.block;
1463
1464 let can_break = self.current_line.has_content;
1467
1468 if !can_break {
1474 if self.sequential_layout_state.is_some() &&
1477 (inline_would_overflow || block_would_overflow)
1478 {
1479 let new_placement = self.place_line_among_floats(potential_line_size);
1480 self.current_line
1481 .replace_placement_among_floats(new_placement);
1482 }
1483
1484 return false;
1485 }
1486
1487 if potential_line_size.inline > containing_block.size.inline {
1490 return true;
1491 }
1492
1493 if block_would_overflow {
1497 assert!(self.sequential_layout_state.is_some());
1499 let new_placement = self.place_line_among_floats(potential_line_size);
1500 if new_placement.start_corner.block !=
1501 self.current_line_block_start_considering_placement_among_floats()
1502 {
1503 return true;
1504 } else {
1505 self.current_line
1506 .replace_placement_among_floats(new_placement);
1507 return false;
1508 }
1509 }
1510
1511 inline_would_overflow
1515 }
1516
1517 fn defer_forced_line_break_at_character_offset(&mut self, line_break_offset: usize) {
1518 if !self.unbreakable_segment_fits_on_line() {
1521 self.process_line_break(false );
1522 }
1523
1524 self.force_line_break_before_new_content = Some(line_break_offset);
1526
1527 let line_is_empty =
1535 !self.current_line_segment.has_content && !self.current_line.has_content;
1536 if !self.processing_br_element() || line_is_empty {
1537 let strut_size = self
1538 .current_inline_container_state()
1539 .strut_block_sizes
1540 .clone();
1541 self.update_unbreakable_segment_for_new_content(
1542 &strut_size,
1543 Au::zero(),
1544 SegmentContentFlags::empty(),
1545 );
1546 }
1547 }
1548
1549 fn possibly_flush_deferred_forced_line_break(&mut self) {
1550 let Some(line_break_character_offset) = self.force_line_break_before_new_content.take()
1551 else {
1552 return;
1553 };
1554
1555 self.commit_current_segment_to_line();
1556 self.process_line_break(true );
1557
1558 self.current_line.starting_character_offset = line_break_character_offset + 1;
1559 }
1560
1561 fn push_line_item_to_unbreakable_segment(&mut self, line_item: LineItem) {
1562 self.current_line_segment
1563 .push_line_item(line_item, self.inline_box_state_stack.len());
1564 }
1565
1566 fn push_glyph_store_to_unbreakable_segment(
1567 &mut self,
1568 glyph_store: Arc<ShapedTextSlice>,
1569 text_run: &TextRun,
1570 info: &Arc<FontAndScriptInfo>,
1571 offsets: Option<TextRunOffsets>,
1572 ) {
1573 let inline_advance = glyph_store.total_advance();
1574 let flags = if glyph_store.is_whitespace() {
1575 SegmentContentFlags::from(text_run.inline_styles.style.borrow().get_inherited_text())
1576 } else {
1577 SegmentContentFlags::empty()
1578 };
1579
1580 let mut block_contribution = LineBlockSizes::zero();
1581 let quirks_mode = self.layout_context.style_context.quirks_mode() != QuirksMode::NoQuirks;
1582 let current_inline_container_state = self.current_inline_container_state();
1583 if quirks_mode && !flags.is_collapsible_whitespace() {
1584 block_contribution.max_assign(¤t_inline_container_state.strut_block_sizes);
1589 }
1590
1591 let font_metrics = &info.font.metrics;
1595 if current_inline_container_state
1596 .font_metrics
1597 .block_metrics_meaningfully_differ(font_metrics)
1598 {
1599 let baseline_shift = effective_baseline_shift(
1601 ¤t_inline_container_state.style,
1602 self.inline_box_state_stack.last().map(|c| &c.base),
1603 );
1604 let mut font_block_conribution = current_inline_container_state
1605 .get_block_size_contribution(
1606 baseline_shift,
1607 font_metrics,
1608 ¤t_inline_container_state.font_metrics,
1609 );
1610 font_block_conribution
1611 .adjust_for_baseline_offset(current_inline_container_state.baseline_offset);
1612 block_contribution.max_assign(&font_block_conribution);
1613 }
1614
1615 self.update_unbreakable_segment_for_new_content(&block_contribution, inline_advance, flags);
1616
1617 let current_inline_box_identifier = self.current_inline_box_identifier();
1618 if let Some(LineItem::TextRun(inline_box_identifier, line_item)) =
1619 self.current_line_segment.line_items.last_mut() &&
1620 *inline_box_identifier == current_inline_box_identifier &&
1621 line_item.merge_if_possible(info, &glyph_store, &offsets, &text_run.inline_styles)
1622 {
1623 return;
1624 }
1625
1626 self.push_line_item_to_unbreakable_segment(LineItem::TextRun(
1627 current_inline_box_identifier,
1628 TextRunLineItem {
1629 text: vec![glyph_store],
1630 base_fragment_info: text_run.base_fragment_info,
1631 inline_styles: text_run.inline_styles.clone(),
1632 info: info.clone(),
1633 offsets: offsets.map(Box::new),
1634 is_empty_for_text_cursor: false,
1635 },
1636 ));
1637 }
1638
1639 fn possibly_push_empty_text_run_to_line_for_text_caret(&mut self) {
1642 let line_start_offset = self.current_line.starting_character_offset;
1643 let Some(shared_selection) = self.ifc.shared_selection.clone() else {
1644 return;
1645 };
1646 let offsets = TextRunOffsets {
1647 shared_selection,
1648 character_range: line_start_offset..line_start_offset + 1,
1649 };
1650
1651 if self
1653 .current_line
1654 .line_items
1655 .iter()
1656 .rev()
1657 .find(|line_item| line_item.is_in_flow_content())
1658 .is_some_and(|line_item| matches!(line_item, LineItem::TextRun(..)))
1659 {
1660 return;
1661 }
1662
1663 let inline_container_state = self.current_inline_container_state();
1664 let Some(font) = inline_container_state.default_font.clone() else {
1665 return;
1666 };
1667
1668 self.push_line_item_to_unbreakable_segment(LineItem::TextRun(
1669 self.current_inline_box_identifier(),
1670 TextRunLineItem {
1671 text: Default::default(),
1672 base_fragment_info: BaseFragmentInfo::anonymous(),
1673 inline_styles: self.ifc.shared_inline_styles.clone(),
1674 info: Arc::new(FontAndScriptInfo::simple_for_font(font)),
1675 offsets: Some(Box::new(offsets)),
1676 is_empty_for_text_cursor: true,
1677 },
1678 ));
1679 self.current_line_segment.has_content = true;
1680 self.commit_current_segment_to_line();
1681 }
1682
1683 fn update_unbreakable_segment_for_new_content(
1684 &mut self,
1685 block_sizes_of_content: &LineBlockSizes,
1686 inline_size: Au,
1687 flags: SegmentContentFlags,
1688 ) {
1689 if flags.is_collapsible_whitespace() || flags.is_wrappable_and_hangable() {
1690 self.current_line_segment.trailing_whitespace_size = inline_size;
1691 } else {
1692 self.current_line_segment.trailing_whitespace_size = Au::zero();
1693 }
1694 if !flags.is_collapsible_whitespace() {
1695 self.current_line_segment.has_content = true;
1696 }
1697
1698 let container_max_block_size = &self
1700 .current_inline_container_state()
1701 .nested_strut_block_sizes
1702 .clone();
1703 self.current_line_segment
1704 .max_block_size
1705 .max_assign(container_max_block_size);
1706 self.current_line_segment
1707 .max_block_size
1708 .max_assign(block_sizes_of_content);
1709
1710 self.current_line_segment.inline_size += inline_size;
1711
1712 self.current_inline_container_state().has_content.set(true);
1714 self.propagate_current_nesting_level_white_space_style();
1715 }
1716
1717 fn process_line_break(&mut self, forced_line_break: bool) {
1718 self.current_line_segment.trim_leading_whitespace();
1719 self.finish_current_line_and_reset(forced_line_break);
1720 }
1721
1722 fn potential_line_size(&self) -> LogicalVec2<Au> {
1723 LogicalVec2 {
1724 inline: self.current_line.inline_position + self.current_line_segment.inline_size,
1725 block: self
1726 .current_line_max_block_size_including_nested_containers()
1727 .max(&self.current_line_segment.max_block_size)
1728 .resolve(),
1729 }
1730 }
1731
1732 fn unbreakable_segment_fits_on_line(&mut self) -> bool {
1733 let potential_line_size_without_hanging_whitespace = self.potential_line_size() -
1734 LogicalVec2 {
1735 inline: self.current_line_segment.trailing_whitespace_size,
1736 block: Au::zero(),
1737 };
1738 !self.new_potential_line_size_causes_line_break(
1739 &potential_line_size_without_hanging_whitespace,
1740 )
1741 }
1742
1743 fn process_soft_wrap_opportunity(&mut self) {
1747 if self.current_line_segment.line_items.is_empty() {
1748 return;
1749 }
1750 if self.text_wrap_mode == TextWrapMode::Nowrap {
1751 return;
1752 }
1753 if !self.unbreakable_segment_fits_on_line() {
1754 self.process_line_break(false );
1755 }
1756 self.commit_current_segment_to_line();
1757 }
1758
1759 fn commit_current_segment_to_line(&mut self) {
1762 if self.current_line_segment.line_items.is_empty() && !self.current_line_segment.has_content
1765 {
1766 return;
1767 }
1768
1769 if !self.current_line.has_content {
1770 self.current_line_segment.trim_leading_whitespace();
1771 }
1772
1773 self.current_line.inline_position += self.current_line_segment.inline_size;
1774 self.current_line.max_block_size = self
1775 .current_line_max_block_size_including_nested_containers()
1776 .max(&self.current_line_segment.max_block_size);
1777 let line_inline_size_without_trailing_whitespace =
1778 self.current_line.inline_position - self.current_line_segment.trailing_whitespace_size;
1779
1780 let mut segment_items = mem::take(&mut self.current_line_segment.line_items);
1782 for item in segment_items.iter_mut() {
1783 if let LineItem::Float(_, float_item) = item {
1784 self.place_float_line_item_for_commit_to_line(
1785 float_item,
1786 line_inline_size_without_trailing_whitespace,
1787 );
1788 }
1789 }
1790
1791 if self.current_line.line_items.is_empty() {
1796 let will_break = self.new_potential_line_size_causes_line_break(&LogicalVec2 {
1797 inline: line_inline_size_without_trailing_whitespace,
1798 block: self.current_line_segment.max_block_size.resolve(),
1799 });
1800 assert!(!will_break);
1801 }
1802
1803 self.current_line.line_items.extend(segment_items);
1804 self.current_line.has_content |= self.current_line_segment.has_content;
1805 self.current_line.has_inline_pbm |= self.current_line_segment.has_inline_pbm;
1806
1807 self.current_line_segment.reset();
1808 }
1809
1810 #[inline]
1811 fn containing_block(&self) -> &ContainingBlock<'_> {
1812 self.placement_state.containing_block
1813 }
1814}
1815
1816bitflags! {
1817 struct SegmentContentFlags: u8 {
1818 const COLLAPSIBLE_WHITESPACE = 0b00000001;
1819 const WRAPPABLE_AND_HANGABLE_WHITESPACE = 0b00000010;
1820 }
1821}
1822
1823impl SegmentContentFlags {
1824 fn is_collapsible_whitespace(&self) -> bool {
1825 self.contains(Self::COLLAPSIBLE_WHITESPACE)
1826 }
1827
1828 fn is_wrappable_and_hangable(&self) -> bool {
1829 self.contains(Self::WRAPPABLE_AND_HANGABLE_WHITESPACE)
1830 }
1831}
1832
1833impl From<&InheritedText> for SegmentContentFlags {
1834 fn from(style_text: &InheritedText) -> Self {
1835 let mut flags = Self::empty();
1836
1837 if !matches!(
1840 style_text.white_space_collapse,
1841 WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
1842 ) {
1843 flags.insert(Self::COLLAPSIBLE_WHITESPACE);
1844 }
1845
1846 if style_text.text_wrap_mode == TextWrapMode::Wrap &&
1849 style_text.white_space_collapse != WhiteSpaceCollapse::BreakSpaces
1850 {
1851 flags.insert(Self::WRAPPABLE_AND_HANGABLE_WHITESPACE);
1852 }
1853 flags
1854 }
1855}
1856
1857impl InlineFormattingContext {
1858 #[servo_tracing::instrument(name = "InlineFormattingContext::new_with_builder", skip_all)]
1859 fn new_with_builder(
1860 mut builder: InlineFormattingContextBuilder,
1861 layout_context: &LayoutContext,
1862 has_first_formatted_line: bool,
1863 is_single_line_text_input: bool,
1864 starting_bidi_level: Level,
1865 ) -> Self {
1866 let text_content: String = builder.text_segments.into_iter().collect();
1868
1869 let bidi_levels = BidiLevels {
1870 info: builder
1871 .has_right_to_left_content
1872 .then(|| BidiInfo::new(&text_content, Some(starting_bidi_level))),
1873 };
1874
1875 let shared_inline_styles = builder
1876 .shared_inline_styles_stack
1877 .last()
1878 .expect("Should have at least one SharedInlineStyle for the root of an IFC")
1879 .clone();
1880 let (word_break, line_break, lang) = {
1881 let styles = shared_inline_styles.style.borrow();
1882 let text_style = styles.get_inherited_text();
1883 (
1884 text_style.word_break,
1885 text_style.line_break,
1886 styles.get_font()._x_lang.clone(),
1887 )
1888 };
1889
1890 let mut options = LineBreakOptions::default();
1891
1892 options.strictness = match line_break {
1893 LineBreak::Loose => LineBreakStrictness::Loose,
1894 LineBreak::Normal => LineBreakStrictness::Normal,
1895 LineBreak::Strict => LineBreakStrictness::Strict,
1896 LineBreak::Anywhere => LineBreakStrictness::Anywhere,
1897 LineBreak::Auto => LineBreakStrictness::Normal,
1900 };
1901 options.word_option = match word_break {
1902 WordBreak::Normal => LineBreakWordOption::Normal,
1903 WordBreak::BreakAll => LineBreakWordOption::BreakAll,
1904 WordBreak::KeepAll => LineBreakWordOption::KeepAll,
1905 };
1906 options.ja_zh = {
1909 lang.0.parse::<LanguageIdentifier>().is_ok_and(|lang_id| {
1910 const JA: Language = language!("ja");
1911 const ZH: Language = language!("zh");
1912 matches!(lang_id.language, JA | ZH)
1913 })
1914 };
1915
1916 let mut new_linebreaker = LineBreaker::new(text_content.as_str(), options);
1917 for item in &mut builder.inline_items {
1918 match item {
1919 InlineItem::TextRun(text_run) => {
1920 text_run.borrow_mut().segment_and_shape(
1921 &text_content,
1922 layout_context,
1923 &mut new_linebreaker,
1924 &bidi_levels,
1925 );
1926 },
1927 InlineItem::StartInlineBox(inline_box) => {
1928 let inline_box = &mut *inline_box.borrow_mut();
1929 if let Some(font) = get_font_for_first_font_for_style(
1930 &inline_box.base.style,
1931 &layout_context.font_context,
1932 ) {
1933 inline_box.default_font = Some(font);
1934 }
1935 },
1936 InlineItem::Atomic(_, index_in_text, bidi_level) => {
1937 *bidi_level = bidi_levels.level(*index_in_text);
1938 },
1939 InlineItem::OutOfFlowAbsolutelyPositionedBox(..) |
1940 InlineItem::OutOfFlowFloatBox(_) |
1941 InlineItem::EndInlineBox |
1942 InlineItem::BlockLevel { .. } => {},
1943 }
1944 }
1945
1946 let default_font = get_font_for_first_font_for_style(
1947 &shared_inline_styles.style.borrow(),
1948 &layout_context.font_context,
1949 );
1950
1951 let has_right_to_left_content = bidi_levels.info.as_ref().is_some_and(BidiInfo::has_rtl);
1952 InlineFormattingContext {
1953 text_content,
1954 inline_items: builder.inline_items,
1955 inline_boxes: builder.inline_boxes,
1956 shared_inline_styles,
1957 default_font,
1958 has_first_formatted_line,
1959 contains_floats: builder.contains_floats,
1960 is_single_line_text_input,
1961 has_right_to_left_content,
1962 shared_selection: builder.shared_selection,
1963 tab_size_multiplier: Default::default(),
1964 }
1965 }
1966
1967 pub(crate) fn repair_style(
1968 &self,
1969 context: &SharedStyleContext,
1970 node: &ServoLayoutNode,
1971 new_style: &ServoArc<ComputedValues>,
1972 ) {
1973 *self.shared_inline_styles.style.borrow_mut() = new_style.clone();
1974 *self.shared_inline_styles.selected.borrow_mut() = node.selected_style(context);
1975 }
1976
1977 fn inline_start_for_first_line(&self, containing_block: IndefiniteContainingBlock) -> Au {
1978 if !self.has_first_formatted_line {
1979 return Au::zero();
1980 }
1981 containing_block
1982 .style
1983 .get_inherited_text()
1984 .text_indent
1985 .length
1986 .to_used_value(containing_block.size.inline.unwrap_or_default())
1987 }
1988
1989 pub(super) fn layout(
1990 &self,
1991 layout_context: &LayoutContext,
1992 positioning_context: &mut PositioningContext,
1993 containing_block: &ContainingBlock,
1994 sequential_layout_state: Option<&mut SequentialLayoutState>,
1995 collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
1996 ) -> IndependentFormattingContextLayoutResult {
1997 for inline_box in self.inline_boxes.iter() {
1999 inline_box.borrow().base.clear_fragments();
2000 }
2001
2002 let style = containing_block.style;
2003
2004 let style_text = containing_block.style.get_inherited_text();
2005 let mut inline_container_state_flags = InlineContainerStateFlags::empty();
2006 if inline_container_needs_strut(style, layout_context, None) {
2007 inline_container_state_flags.insert(InlineContainerStateFlags::CREATE_STRUT);
2008 }
2009 if self.is_single_line_text_input {
2010 inline_container_state_flags
2011 .insert(InlineContainerStateFlags::IS_SINGLE_LINE_TEXT_INPUT);
2012 }
2013 let placement_state =
2014 PlacementState::new(collapsible_with_parent_start_margin, containing_block);
2015
2016 let mut layout = InlineFormattingContextLayout {
2017 positioning_context,
2018 placement_state,
2019 sequential_layout_state,
2020 layout_context,
2021 ifc: self,
2022 fragments: Vec::new(),
2023 current_line: LineUnderConstruction::new(LogicalVec2 {
2024 inline: self.inline_start_for_first_line(containing_block.into()),
2025 block: Au::zero(),
2026 }),
2027 root_nesting_level: InlineContainerState::new(
2028 style.to_arc(),
2029 inline_container_state_flags,
2030 None, self.default_font.clone(),
2032 ),
2033 inline_box_state_stack: Vec::new(),
2034 inline_box_states: Vec::with_capacity(self.inline_boxes.len()),
2035 current_line_segment: UnbreakableSegmentUnderConstruction::new(),
2036 force_line_break_before_new_content: None,
2037 deferred_br_clear: Clear::None,
2038 have_deferred_soft_wrap_opportunity: false,
2039 depends_on_block_constraints: false,
2040 white_space_collapse: style_text.white_space_collapse,
2041 text_wrap_mode: style_text.text_wrap_mode,
2042 };
2043
2044 for item in self.inline_items.iter() {
2045 if !matches!(item, InlineItem::EndInlineBox) {
2047 layout.possibly_flush_deferred_forced_line_break();
2048 }
2049
2050 match item {
2051 InlineItem::StartInlineBox(inline_box) => {
2052 layout.start_inline_box(&inline_box.borrow());
2053 },
2054 InlineItem::EndInlineBox => layout.finish_inline_box(),
2055 InlineItem::TextRun(run) => run.borrow().layout_into_line_items(&mut layout),
2056 InlineItem::Atomic(atomic_formatting_context, offset_in_text, bidi_level) => {
2057 atomic_formatting_context.borrow().layout_into_line_items(
2058 &mut layout,
2059 *offset_in_text,
2060 *bidi_level,
2061 );
2062 },
2063 InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, _) => {
2064 layout.push_line_item_to_unbreakable_segment(LineItem::AbsolutelyPositioned(
2065 layout.current_inline_box_identifier(),
2066 AbsolutelyPositionedLineItem {
2067 absolutely_positioned_box: positioned_box.clone(),
2068 preceding_line_content_would_produce_phantom_line: layout
2069 .current_line
2070 .is_phantom() &&
2071 layout.current_line_segment.is_phantom(),
2072 },
2073 ));
2074 },
2075 InlineItem::OutOfFlowFloatBox(float_box) => {
2076 float_box.borrow().layout_into_line_items(&mut layout);
2077 },
2078 InlineItem::BlockLevel(block_level) => {
2079 block_level.borrow().layout_into_line_items(&mut layout);
2080 },
2081 }
2082 }
2083
2084 layout.finish_last_line();
2085 let (content_block_size, collapsible_margins_in_children, baselines) =
2086 layout.placement_state.finish();
2087
2088 IndependentFormattingContextLayoutResult {
2089 fragments: layout.fragments,
2090 content_block_size,
2091 collapsible_margins_in_children,
2092 baselines,
2093 depends_on_block_constraints: layout.depends_on_block_constraints,
2094 content_inline_size_for_table: None,
2095 specific_layout_info: None,
2096 }
2097 }
2098
2099 pub(crate) fn subtree_size(&self) -> usize {
2100 self.inline_items
2101 .iter()
2102 .map(|item| match item {
2103 InlineItem::StartInlineBox(..) => 1,
2104 InlineItem::EndInlineBox => 0,
2105 InlineItem::TextRun(..) => 1,
2106 InlineItem::OutOfFlowAbsolutelyPositionedBox(absolutely_positioned_box, _) => {
2107 absolutely_positioned_box
2108 .borrow()
2109 .context
2110 .base
2111 .subtree_size()
2112 },
2113 InlineItem::OutOfFlowFloatBox(..) => 1,
2114 InlineItem::Atomic(..) => 1,
2115 InlineItem::BlockLevel(block_level_box) => block_level_box.borrow().subtree_size(),
2116 })
2117 .sum()
2118 }
2119
2120 fn next_character_prevents_soft_wrap_opportunity(&self, index: usize) -> bool {
2121 let Some(character) = self.text_content[index..].chars().nth(1) else {
2122 return false;
2123 };
2124 char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character)
2125 }
2126
2127 fn previous_character_prevents_soft_wrap_opportunity(&self, index: usize) -> bool {
2128 let Some(character) = self.text_content[0..index].chars().next_back() else {
2129 return false;
2130 };
2131 char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character)
2132 }
2133
2134 pub(crate) fn find_block_margin_collapsing_with_parent(
2135 &self,
2136 layout_context: &LayoutContext,
2137 collected_margin: &mut CollapsedMargin,
2138 containing_block_for_children: &ContainingBlock,
2139 ) -> bool {
2140 let mut nesting_levels_from_nonzero_end_pbm: u32 = 1;
2146 let mut items_iter = self.inline_items.iter();
2147 items_iter.all(|inline_item| match inline_item {
2148 InlineItem::StartInlineBox(inline_box) => {
2149 let pbm = inline_box
2150 .borrow()
2151 .layout_style()
2152 .padding_border_margin(containing_block_for_children);
2153 if pbm.padding.inline_end.is_zero() &&
2154 pbm.border.inline_end.is_zero() &&
2155 pbm.margin.inline_end.auto_is(Au::zero).is_zero()
2156 {
2157 nesting_levels_from_nonzero_end_pbm += 1;
2158 } else {
2159 nesting_levels_from_nonzero_end_pbm = 0;
2160 }
2161 pbm.padding.inline_start.is_zero() &&
2162 pbm.border.inline_start.is_zero() &&
2163 pbm.margin.inline_start.auto_is(Au::zero).is_zero()
2164 },
2165 InlineItem::EndInlineBox => {
2166 if nesting_levels_from_nonzero_end_pbm == 0 {
2167 false
2168 } else {
2169 nesting_levels_from_nonzero_end_pbm -= 1;
2170 true
2171 }
2172 },
2173 InlineItem::TextRun(text_run) => {
2174 let text_run = &*text_run.borrow();
2175 let parent_style = text_run.inline_styles.style.borrow();
2176 text_run.items.iter().all(|item| match item {
2177 TextRunItem::LineBreak { .. } => false,
2178 TextRunItem::Tab { .. } => false,
2179 TextRunItem::TextSegment(segment) => segment.runs.iter().all(|run| {
2180 run.is_whitespace() &&
2181 !matches!(
2182 parent_style.get_inherited_text().white_space_collapse,
2183 WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
2184 )
2185 }),
2186 })
2187 },
2188 InlineItem::OutOfFlowAbsolutelyPositionedBox(..) => true,
2189 InlineItem::OutOfFlowFloatBox(..) => true,
2190 InlineItem::Atomic(..) => false,
2191 InlineItem::BlockLevel(block_level) => block_level
2192 .borrow()
2193 .find_block_margin_collapsing_with_parent(
2194 layout_context,
2195 collected_margin,
2196 containing_block_for_children,
2197 ),
2198 })
2199 }
2200
2201 pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
2202 let mut parent_box_stack = Vec::new();
2203 let current_parent_box = |parent_box_stack: &[WeakLayoutBox]| {
2204 parent_box_stack.last().unwrap_or(&layout_box).clone()
2205 };
2206 for inline_item in &self.inline_items {
2207 match inline_item {
2208 InlineItem::StartInlineBox(inline_box) => {
2209 inline_box
2210 .borrow_mut()
2211 .base
2212 .parent_box
2213 .replace(current_parent_box(&parent_box_stack));
2214 parent_box_stack.push(WeakLayoutBox::InlineLevel(
2215 WeakInlineItem::StartInlineBox(inline_box.downgrade()),
2216 ));
2217 },
2218 InlineItem::EndInlineBox => {
2219 parent_box_stack.pop();
2220 },
2221 InlineItem::TextRun(text_run) => {
2222 text_run
2223 .borrow_mut()
2224 .parent_box
2225 .replace(current_parent_box(&parent_box_stack));
2226 },
2227 _ => inline_item.with_base_mut(|base| {
2228 base.parent_box
2229 .replace(current_parent_box(&parent_box_stack));
2230 }),
2231 }
2232 }
2233 }
2234
2235 pub(crate) fn next_tab_stop_after_inline_advance(
2236 &self,
2237 style: &ServoArc<ComputedValues>,
2238 current_inline_advance: Au,
2239 ) -> Au {
2240 let Some(font) = self.default_font.as_ref() else {
2241 return Au::zero();
2242 };
2243
2244 let tab_size_multiplier = *self.tab_size_multiplier.get_or_init(|| {
2245 let root_style = self.shared_inline_styles.style.borrow();
2246 let inherited_text_style = root_style.get_inherited_text();
2247 let font_size = root_style.get_font().font_size.computed_size().into();
2248 let letter_spacing = inherited_text_style
2249 .letter_spacing
2250 .0
2251 .to_used_value(font_size);
2252 let word_spacing = inherited_text_style.word_spacing.to_used_value(font_size);
2253
2254 font.metrics.space_advance + word_spacing + letter_spacing
2257 });
2258
2259 let tab_stop_advance = match style.get_inherited_text().tab_size {
2260 style::values::generics::length::LengthOrNumber::Number(number_of_spaces) => {
2261 tab_size_multiplier.scale_by(number_of_spaces.0)
2262 },
2263 style::values::generics::length::LengthOrNumber::Length(length) => length.into(),
2265 };
2266
2267 if tab_stop_advance.is_zero() {
2268 return Au::zero();
2269 }
2270
2271 let half_ch_advance = font
2277 .metrics
2278 .zero_horizontal_advance
2279 .unwrap_or(font.metrics.em_size.scale_by(0.5))
2280 .scale_by(0.5);
2281 let number_of_tab_stops =
2282 (current_inline_advance + half_ch_advance).to_f32_px() / tab_stop_advance.to_f32_px();
2283 let number_of_tab_stops = number_of_tab_stops.ceil();
2284 tab_stop_advance.scale_by(number_of_tab_stops) - current_inline_advance
2285 }
2286}
2287
2288impl InlineContainerState {
2289 fn new(
2290 style: ServoArc<ComputedValues>,
2291 flags: InlineContainerStateFlags,
2292 parent_container: Option<&InlineContainerState>,
2293 default_font: Option<FontRef>,
2294 ) -> Self {
2295 let font_metrics = default_font
2296 .as_ref()
2297 .map(|font| font.metrics.clone())
2298 .unwrap_or_else(FontMetrics::empty);
2299 let mut baseline_offset = Au::zero();
2300 let mut strut_block_sizes = {
2301 Self::get_block_sizes_with_style(
2302 effective_baseline_shift(&style, parent_container),
2303 &style,
2304 &font_metrics,
2305 &font_metrics,
2306 &flags,
2307 )
2308 };
2309
2310 if let Some(parent_container) = parent_container {
2311 baseline_offset = parent_container.get_cumulative_baseline_offset_for_child(
2314 style.clone_alignment_baseline(),
2315 style.clone_baseline_shift(),
2316 &strut_block_sizes,
2317 );
2318 strut_block_sizes.adjust_for_baseline_offset(baseline_offset);
2319 }
2320
2321 let mut nested_block_sizes = parent_container
2322 .map(|container| container.nested_strut_block_sizes.clone())
2323 .unwrap_or_else(LineBlockSizes::zero);
2324 if flags.contains(InlineContainerStateFlags::CREATE_STRUT) {
2325 nested_block_sizes.max_assign(&strut_block_sizes);
2326 }
2327
2328 Self {
2329 style,
2330 flags,
2331 has_content: Cell::new(false),
2332 nested_strut_block_sizes: nested_block_sizes,
2333 strut_block_sizes,
2334 baseline_offset,
2335 default_font,
2336 font_metrics,
2337 }
2338 }
2339
2340 fn get_block_sizes_with_style(
2341 baseline_shift: BaselineShift,
2342 style: &ComputedValues,
2343 font_metrics: &FontMetrics,
2344 font_metrics_of_first_font: &FontMetrics,
2345 flags: &InlineContainerStateFlags,
2346 ) -> LineBlockSizes {
2347 let line_height = line_height(style, font_metrics, flags);
2348
2349 if !is_baseline_relative(baseline_shift) {
2350 return LineBlockSizes {
2351 line_height,
2352 baseline_relative_size_for_line_height: None,
2353 size_for_baseline_positioning: BaselineRelativeSize::zero(),
2354 };
2355 }
2356
2357 let mut ascent = font_metrics.ascent;
2366 let mut descent = font_metrics.descent;
2367 if style.get_font().line_height == LineHeight::Normal {
2368 let half_leading_from_line_gap =
2369 (font_metrics.line_gap - descent - ascent).scale_by(0.5);
2370 ascent += half_leading_from_line_gap;
2371 descent += half_leading_from_line_gap;
2372 }
2373
2374 let size_for_baseline_positioning = BaselineRelativeSize { ascent, descent };
2378
2379 if style.get_font().line_height != LineHeight::Normal {
2395 ascent = font_metrics_of_first_font.ascent;
2396 descent = font_metrics_of_first_font.descent;
2397 let half_leading = (line_height - (ascent + descent)).scale_by(0.5);
2398 ascent += half_leading;
2403 descent = line_height - ascent;
2404 }
2405
2406 LineBlockSizes {
2407 line_height,
2408 baseline_relative_size_for_line_height: Some(BaselineRelativeSize { ascent, descent }),
2409 size_for_baseline_positioning,
2410 }
2411 }
2412
2413 fn get_block_size_contribution(
2414 &self,
2415 baseline_shift: BaselineShift,
2416 font_metrics: &FontMetrics,
2417 font_metrics_of_first_font: &FontMetrics,
2418 ) -> LineBlockSizes {
2419 Self::get_block_sizes_with_style(
2420 baseline_shift,
2421 &self.style,
2422 font_metrics,
2423 font_metrics_of_first_font,
2424 &self.flags,
2425 )
2426 }
2427
2428 fn get_cumulative_baseline_offset_for_child(
2429 &self,
2430 child_alignment_baseline: AlignmentBaseline,
2431 child_baseline_shift: BaselineShift,
2432 child_block_size: &LineBlockSizes,
2433 ) -> Au {
2434 let block_size = self.get_block_size_contribution(
2435 child_baseline_shift.clone(),
2436 &self.font_metrics,
2437 &self.font_metrics,
2438 );
2439 self.baseline_offset +
2440 match child_alignment_baseline {
2441 AlignmentBaseline::Baseline => Au::zero(),
2442 AlignmentBaseline::TextTop => {
2443 child_block_size.size_for_baseline_positioning.ascent - self.font_metrics.ascent
2444 },
2445 AlignmentBaseline::Middle => {
2446 (child_block_size.size_for_baseline_positioning.ascent -
2449 child_block_size.size_for_baseline_positioning.descent -
2450 self.font_metrics.x_height)
2451 .scale_by(0.5)
2452 },
2453 AlignmentBaseline::TextBottom => {
2454 self.font_metrics.descent -
2455 child_block_size.size_for_baseline_positioning.descent
2456 },
2457 } +
2458 match child_baseline_shift {
2459 BaselineShift::Keyword(
2464 BaselineShiftKeyword::Top |
2465 BaselineShiftKeyword::Bottom |
2466 BaselineShiftKeyword::Center,
2467 ) => Au::zero(),
2468 BaselineShift::Keyword(BaselineShiftKeyword::Sub) => {
2469 block_size.resolve().scale_by(FONT_SUBSCRIPT_OFFSET_RATIO)
2470 },
2471 BaselineShift::Keyword(BaselineShiftKeyword::Super) => {
2472 -block_size.resolve().scale_by(FONT_SUPERSCRIPT_OFFSET_RATIO)
2473 },
2474 BaselineShift::Length(length_percentage) => {
2475 -length_percentage.to_used_value(child_block_size.line_height)
2476 },
2477 }
2478 }
2479}
2480
2481impl IndependentFormattingContext {
2482 fn layout_into_line_items(
2483 &self,
2484 layout: &mut InlineFormattingContextLayout,
2485 offset_in_text: usize,
2486 bidi_level: Level,
2487 ) {
2488 let mut child_positioning_context = PositioningContext::default();
2490 let IndependentFloatOrAtomicLayoutResult {
2491 mut fragment,
2492 baselines,
2493 pbm_sums,
2494 } = self.layout_float_or_atomic_inline(
2495 layout.layout_context,
2496 &mut child_positioning_context,
2497 layout.containing_block(),
2498 );
2499
2500 layout.depends_on_block_constraints |= fragment.base.flags.contains(
2503 FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
2504 );
2505
2506 let container_writing_mode = layout.containing_block().style.writing_mode;
2508 let pbm_physical_offset = pbm_sums
2509 .start_offset()
2510 .to_physical_size(container_writing_mode);
2511 fragment.base.translate_rect(pbm_physical_offset);
2512
2513 fragment = fragment.with_baselines(baselines);
2515
2516 let positioning_context = if self.is_replaced() {
2519 None
2520 } else {
2521 if fragment
2522 .style()
2523 .establishes_containing_block_for_absolute_descendants(fragment.base.flags)
2524 {
2525 child_positioning_context
2526 .layout_collected_children(layout.layout_context, &mut fragment);
2527 }
2528 Some(child_positioning_context)
2529 };
2530
2531 if layout.text_wrap_mode == TextWrapMode::Wrap &&
2532 !layout
2533 .ifc
2534 .previous_character_prevents_soft_wrap_opportunity(offset_in_text)
2535 {
2536 layout.process_soft_wrap_opportunity();
2537 }
2538
2539 let size = pbm_sums.sum() + fragment.base.rect().size.to_logical(container_writing_mode);
2540 let baseline_offset = self
2541 .pick_baseline(&fragment.baselines(container_writing_mode))
2542 .map(|baseline| pbm_sums.block_start + baseline)
2543 .unwrap_or(size.block);
2544
2545 let (block_sizes, baseline_offset_in_parent) =
2546 self.get_block_sizes_and_baseline_offset(layout, size.block, baseline_offset);
2547 layout.update_unbreakable_segment_for_new_content(
2548 &block_sizes,
2549 size.inline,
2550 SegmentContentFlags::empty(),
2551 );
2552
2553 let fragment = Arc::new(fragment);
2554 self.base.set_fragment(Fragment::Box(fragment.clone()));
2555
2556 layout.push_line_item_to_unbreakable_segment(LineItem::Atomic(
2557 layout.current_inline_box_identifier(),
2558 AtomicLineItem {
2559 fragment,
2560 size,
2561 positioning_context,
2562 baseline_offset_in_parent,
2563 baseline_offset_in_item: baseline_offset,
2564 bidi_level,
2565 },
2566 ));
2567
2568 if !layout
2571 .ifc
2572 .next_character_prevents_soft_wrap_opportunity(offset_in_text)
2573 {
2574 layout.have_deferred_soft_wrap_opportunity = true;
2575 }
2576 }
2577
2578 fn pick_baseline(&self, baselines: &Baselines) -> Option<Au> {
2582 match self.style().clone_baseline_source() {
2583 BaselineSource::First => baselines.first,
2584 BaselineSource::Last => baselines.last,
2585 BaselineSource::Auto if self.is_block_container() => baselines.last,
2586 BaselineSource::Auto => baselines.first,
2587 }
2588 }
2589
2590 fn get_block_sizes_and_baseline_offset(
2591 &self,
2592 ifc: &InlineFormattingContextLayout,
2593 block_size: Au,
2594 baseline_offset_in_content_area: Au,
2595 ) -> (LineBlockSizes, Au) {
2596 let mut contribution = if !is_baseline_relative(self.style().clone_baseline_shift()) {
2597 LineBlockSizes {
2598 line_height: block_size,
2599 baseline_relative_size_for_line_height: None,
2600 size_for_baseline_positioning: BaselineRelativeSize::zero(),
2601 }
2602 } else {
2603 let baseline_relative_size = BaselineRelativeSize {
2604 ascent: baseline_offset_in_content_area,
2605 descent: block_size - baseline_offset_in_content_area,
2606 };
2607 LineBlockSizes {
2608 line_height: block_size,
2609 baseline_relative_size_for_line_height: Some(baseline_relative_size.clone()),
2610 size_for_baseline_positioning: baseline_relative_size,
2611 }
2612 };
2613
2614 let style = self.style();
2615 let baseline_offset = ifc
2616 .current_inline_container_state()
2617 .get_cumulative_baseline_offset_for_child(
2618 style.clone_alignment_baseline(),
2619 style.clone_baseline_shift(),
2620 &contribution,
2621 );
2622 contribution.adjust_for_baseline_offset(baseline_offset);
2623
2624 (contribution, baseline_offset)
2625 }
2626}
2627
2628impl FloatBox {
2629 fn layout_into_line_items(&self, layout: &mut InlineFormattingContextLayout) {
2630 let fragment = Arc::new(self.layout(
2631 layout.layout_context,
2632 layout.positioning_context,
2633 layout.placement_state.containing_block,
2634 ));
2635
2636 self.contents
2637 .base
2638 .set_fragment(Fragment::Box(fragment.clone()));
2639 layout.push_line_item_to_unbreakable_segment(LineItem::Float(
2640 layout.current_inline_box_identifier(),
2641 FloatLineItem {
2642 fragment,
2643 needs_placement: true,
2644 },
2645 ));
2646 }
2647}
2648
2649fn place_pending_floats(ifc: &mut InlineFormattingContextLayout, line_items: &[LineItem]) {
2650 for item in line_items.iter() {
2651 if let LineItem::Float(_, float_line_item) = item &&
2652 float_line_item.needs_placement
2653 {
2654 ifc.place_float_fragment(&float_line_item.fragment);
2655 }
2656 }
2657}
2658
2659fn line_height(
2660 parent_style: &ComputedValues,
2661 font_metrics: &FontMetrics,
2662 flags: &InlineContainerStateFlags,
2663) -> Au {
2664 let font = parent_style.get_font();
2665 let font_size = font.font_size.computed_size();
2666 let mut line_height = match font.line_height {
2667 LineHeight::Normal => font_metrics.line_gap,
2668 LineHeight::Number(number) => (font_size * number.0).into(),
2669 LineHeight::Length(length) => length.0.into(),
2670 };
2671
2672 if flags.contains(InlineContainerStateFlags::IS_SINGLE_LINE_TEXT_INPUT) {
2676 line_height.max_assign(font_metrics.line_gap);
2677 }
2678
2679 line_height
2680}
2681
2682fn effective_baseline_shift(
2683 style: &ComputedValues,
2684 container: Option<&InlineContainerState>,
2685) -> BaselineShift {
2686 if container.is_none() {
2687 BaselineShift::zero()
2691 } else {
2692 style.clone_baseline_shift()
2693 }
2694}
2695
2696fn is_baseline_relative(baseline_shift: BaselineShift) -> bool {
2697 !matches!(
2698 baseline_shift,
2699 BaselineShift::Keyword(
2700 BaselineShiftKeyword::Top | BaselineShiftKeyword::Bottom | BaselineShiftKeyword::Center
2701 )
2702 )
2703}
2704
2705fn inline_container_needs_strut(
2731 style: &ComputedValues,
2732 layout_context: &LayoutContext,
2733 pbm: Option<&PaddingBorderMargin>,
2734) -> bool {
2735 if layout_context.style_context.quirks_mode() == QuirksMode::NoQuirks {
2736 return true;
2737 }
2738
2739 if style.get_box().display.is_list_item() {
2742 return true;
2743 }
2744
2745 pbm.is_some_and(|pbm| !pbm.padding_border_sums.inline.is_zero())
2746}
2747
2748impl ComputeInlineContentSizes for InlineFormattingContext {
2749 fn compute_inline_content_sizes(
2753 &self,
2754 layout_context: &LayoutContext,
2755 constraint_space: &ConstraintSpace,
2756 ) -> InlineContentSizesResult {
2757 ContentSizesComputation::compute(self, layout_context, constraint_space)
2758 }
2759}
2760
2761struct ContentSizesComputation<'layout_data> {
2763 layout_context: &'layout_data LayoutContext<'layout_data>,
2764 constraint_space: &'layout_data ConstraintSpace<'layout_data>,
2765 paragraph: ContentSizes,
2766 current_line: ContentSizes,
2767 pending_whitespace: ContentSizes,
2769 uncleared_floats: LogicalSides1D<ContentSizes>,
2771 cleared_floats: LogicalSides1D<ContentSizes>,
2773 had_content_yet_for_min_content: bool,
2776 had_content_yet_for_max_content: bool,
2779 ending_inline_pbm_stack: Vec<Au>,
2782 depends_on_block_constraints: bool,
2784}
2785
2786impl<'layout_data> ContentSizesComputation<'layout_data> {
2787 fn traverse(
2788 mut self,
2789 inline_formatting_context: &InlineFormattingContext,
2790 ) -> InlineContentSizesResult {
2791 self.add_inline_size(
2792 inline_formatting_context.inline_start_for_first_line(self.constraint_space.into()),
2793 );
2794 for inline_item in &inline_formatting_context.inline_items {
2795 self.process_item(inline_item, inline_formatting_context);
2796 }
2797 self.forced_line_break();
2798 self.flush_floats();
2799
2800 InlineContentSizesResult {
2801 sizes: self.paragraph,
2802 depends_on_block_constraints: self.depends_on_block_constraints,
2803 }
2804 }
2805
2806 fn process_item(
2807 &mut self,
2808 inline_item: &InlineItem,
2809 inline_formatting_context: &InlineFormattingContext,
2810 ) {
2811 match inline_item {
2812 InlineItem::StartInlineBox(inline_box) => {
2813 let inline_box = inline_box.borrow();
2817 let zero = Au::zero();
2818 let writing_mode = self.constraint_space.style.writing_mode;
2819 let layout_style = inline_box.layout_style();
2820 let padding = layout_style
2821 .padding(writing_mode)
2822 .percentages_relative_to(zero);
2823 let border = layout_style.border_width(writing_mode);
2824 let margin = inline_box
2825 .base
2826 .style
2827 .margin(writing_mode)
2828 .percentages_relative_to(zero)
2829 .auto_is(Au::zero);
2830
2831 let pbm = margin + padding + border;
2832 self.add_inline_size(pbm.inline_start);
2833 self.ending_inline_pbm_stack.push(pbm.inline_end);
2834 },
2835 InlineItem::EndInlineBox => {
2836 let length = self.ending_inline_pbm_stack.pop().unwrap_or_else(Au::zero);
2837 self.add_inline_size(length);
2838 },
2839 InlineItem::TextRun(text_run) => {
2840 let text_run = &*text_run.borrow();
2841 let parent_style = text_run.inline_styles.style.borrow();
2842 for item in text_run.items.iter() {
2843 match item {
2844 TextRunItem::LineBreak { .. } => {
2845 self.forced_line_break();
2848 },
2849 TextRunItem::Tab { .. } => {
2850 self.process_preserved_tab(&parent_style, inline_formatting_context)
2851 },
2852 TextRunItem::TextSegment(segment) => {
2853 self.process_text_segment(&parent_style, segment)
2854 },
2855 }
2856 }
2857 },
2858 InlineItem::Atomic(atomic, offset_in_text, _level) => {
2859 if self.had_content_yet_for_min_content &&
2861 !inline_formatting_context
2862 .previous_character_prevents_soft_wrap_opportunity(*offset_in_text)
2863 {
2864 self.line_break_opportunity();
2865 }
2866
2867 self.commit_pending_whitespace();
2868 let outer = self.outer_inline_content_sizes_of_float_or_atomic(&atomic.borrow());
2869 self.current_line += outer;
2870
2871 if !inline_formatting_context
2873 .next_character_prevents_soft_wrap_opportunity(*offset_in_text)
2874 {
2875 self.line_break_opportunity();
2876 }
2877 },
2878 InlineItem::OutOfFlowFloatBox(float_box) => {
2879 let float_box = float_box.borrow();
2880 let sizes = self.outer_inline_content_sizes_of_float_or_atomic(&float_box.contents);
2881 let style = &float_box.contents.style();
2882 let container_writing_mode = self.constraint_space.style.writing_mode;
2883 let clear =
2884 Clear::from_style_and_container_writing_mode(style, container_writing_mode);
2885 self.clear_floats(clear);
2886 let float_side =
2887 FloatSide::from_style_and_container_writing_mode(style, container_writing_mode);
2888 match float_side.expect("A float box needs to float to some side") {
2889 FloatSide::InlineStart => self.uncleared_floats.start.union_assign(&sizes),
2890 FloatSide::InlineEnd => self.uncleared_floats.end.union_assign(&sizes),
2891 }
2892 },
2893 InlineItem::BlockLevel(block_level) => {
2894 self.forced_line_break();
2895 self.flush_floats();
2896 let inline_content_sizes_result =
2897 compute_inline_content_sizes_for_block_level_boxes(
2898 std::slice::from_ref(block_level),
2899 self.layout_context,
2900 &self.constraint_space.into(),
2901 );
2902 self.depends_on_block_constraints |=
2903 inline_content_sizes_result.depends_on_block_constraints;
2904 self.current_line = inline_content_sizes_result.sizes;
2905 self.forced_line_break();
2906 },
2907 InlineItem::OutOfFlowAbsolutelyPositionedBox(..) => {},
2908 }
2909 }
2910
2911 fn process_text_segment(
2912 &mut self,
2913 parent_style: &AtomicRef<'_, ServoArc<ComputedValues>>,
2914 segment: &TextRunSegment,
2915 ) {
2916 let style_text = parent_style.get_inherited_text();
2917 let can_wrap = style_text.text_wrap_mode == TextWrapMode::Wrap;
2918
2919 let break_at_start = segment.break_at_start && self.had_content_yet_for_min_content;
2922
2923 for (run_index, run) in segment.runs.iter().enumerate() {
2924 if can_wrap && (run_index != 0 || break_at_start) {
2927 self.line_break_opportunity();
2928 }
2929
2930 let advance = run.total_advance();
2931 if run.is_whitespace() {
2932 if !matches!(
2933 style_text.white_space_collapse,
2934 WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
2935 ) {
2936 if self.had_content_yet_for_min_content {
2937 if can_wrap {
2938 self.line_break_opportunity();
2939 } else {
2940 self.pending_whitespace.min_content += advance;
2941 }
2942 }
2943 if self.had_content_yet_for_max_content {
2944 self.pending_whitespace.max_content += advance;
2945 }
2946 continue;
2947 }
2948 if can_wrap {
2949 self.pending_whitespace.max_content += advance;
2950 self.commit_pending_whitespace();
2951 self.line_break_opportunity();
2952 continue;
2953 }
2954 }
2955
2956 self.commit_pending_whitespace();
2957 self.add_inline_size(advance);
2958
2959 if can_wrap && run.ends_with_whitespace() {
2964 self.line_break_opportunity();
2965 }
2966 }
2967 }
2968
2969 fn process_preserved_tab(
2970 &mut self,
2971 parent_style: &AtomicRef<'_, ServoArc<ComputedValues>>,
2972 inline_formatting_context: &InlineFormattingContext,
2973 ) {
2974 self.commit_pending_whitespace();
2976
2977 self.current_line.min_content += inline_formatting_context
2978 .next_tab_stop_after_inline_advance(parent_style, self.current_line.min_content);
2979 self.current_line.max_content += inline_formatting_context
2980 .next_tab_stop_after_inline_advance(parent_style, self.current_line.max_content);
2981 if parent_style.get_inherited_text().text_wrap_mode == TextWrapMode::Wrap {
2982 self.line_break_opportunity();
2983 }
2984 }
2985
2986 fn add_inline_size(&mut self, l: Au) {
2987 self.current_line.min_content += l;
2988 self.current_line.max_content += l;
2989 }
2990
2991 fn line_break_opportunity(&mut self) {
2992 self.pending_whitespace.min_content = Au::zero();
2996 let current_min_content = mem::take(&mut self.current_line.min_content);
2997 self.paragraph.min_content.max_assign(current_min_content);
2998 self.had_content_yet_for_min_content = false;
2999 }
3000
3001 fn forced_line_break(&mut self) {
3002 self.line_break_opportunity();
3004
3005 self.pending_whitespace.max_content = Au::zero();
3007 let current_max_content = mem::take(&mut self.current_line.max_content);
3008 self.paragraph.max_content.max_assign(current_max_content);
3009 self.had_content_yet_for_max_content = false;
3010 }
3011
3012 fn commit_pending_whitespace(&mut self) {
3013 self.current_line += mem::take(&mut self.pending_whitespace);
3014 self.had_content_yet_for_min_content = true;
3015 self.had_content_yet_for_max_content = true;
3016 }
3017
3018 fn outer_inline_content_sizes_of_float_or_atomic(
3019 &mut self,
3020 context: &IndependentFormattingContext,
3021 ) -> ContentSizes {
3022 let result = context.outer_inline_content_sizes(
3023 self.layout_context,
3024 &self.constraint_space.into(),
3025 &LogicalVec2::zero(),
3026 false, );
3028 self.depends_on_block_constraints |= result.depends_on_block_constraints;
3029 result.sizes
3030 }
3031
3032 fn clear_floats(&mut self, clear: Clear) {
3033 match clear {
3034 Clear::InlineStart => {
3035 let start_floats = mem::take(&mut self.uncleared_floats.start);
3036 self.cleared_floats.start.max_assign(start_floats);
3037 },
3038 Clear::InlineEnd => {
3039 let end_floats = mem::take(&mut self.uncleared_floats.end);
3040 self.cleared_floats.end.max_assign(end_floats);
3041 },
3042 Clear::Both => {
3043 let start_floats = mem::take(&mut self.uncleared_floats.start);
3044 let end_floats = mem::take(&mut self.uncleared_floats.end);
3045 self.cleared_floats.start.max_assign(start_floats);
3046 self.cleared_floats.end.max_assign(end_floats);
3047 },
3048 Clear::None => {},
3049 }
3050 }
3051
3052 fn flush_floats(&mut self) {
3053 self.clear_floats(Clear::Both);
3054 let start_floats = mem::take(&mut self.cleared_floats.start);
3055 let end_floats = mem::take(&mut self.cleared_floats.end);
3056 self.paragraph.union_assign(&start_floats);
3057 self.paragraph.union_assign(&end_floats);
3058 }
3059
3060 fn compute(
3062 inline_formatting_context: &InlineFormattingContext,
3063 layout_context: &'layout_data LayoutContext,
3064 constraint_space: &'layout_data ConstraintSpace,
3065 ) -> InlineContentSizesResult {
3066 Self {
3067 layout_context,
3068 constraint_space,
3069 paragraph: ContentSizes::zero(),
3070 current_line: ContentSizes::zero(),
3071 pending_whitespace: ContentSizes::zero(),
3072 uncleared_floats: LogicalSides1D::default(),
3073 cleared_floats: LogicalSides1D::default(),
3074 had_content_yet_for_min_content: false,
3075 had_content_yet_for_max_content: false,
3076 ending_inline_pbm_stack: Vec::new(),
3077 depends_on_block_constraints: false,
3078 }
3079 .traverse(inline_formatting_context)
3080 }
3081}
3082
3083pub(crate) struct BidiLevels<'a> {
3084 info: Option<BidiInfo<'a>>,
3085}
3086
3087impl BidiLevels<'_> {
3088 fn level(&self, byte_offset_in_ifc_text: usize) -> Level {
3089 self.info
3090 .as_ref()
3091 .map_or_else(Level::ltr, |info| info.levels[byte_offset_in_ifc_text])
3092 }
3093}
3094
3095fn char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character: char) -> bool {
3107 if character == '\u{00A0}' {
3108 return false;
3109 }
3110 matches!(
3111 icu_properties::maps::line_break().get(character),
3112 ICULineBreak::Glue | ICULineBreak::WordJoiner | ICULineBreak::ZWJ
3113 )
3114}