1pub 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
150static 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 inline_items: Vec<InlineItem>,
161
162 inline_boxes: InlineBoxes,
165
166 #[conditional_malloc_size_of]
168 text_content: Arc<OnceLock<String>>,
169
170 shared_inline_styles: SharedInlineStyles,
173
174 default_font: Option<FontRef>,
178
179 has_first_formatted_line: bool,
182
183 pub(super) contains_floats: bool,
185
186 is_single_line_text_input: bool,
189
190 has_right_to_left_content: bool,
193
194 tab_size_multiplier: OnceLock<Au>,
199}
200
201#[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, true, );
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, );
242
243 let Some(fragment) = fragment.retrieve_box_fragment() else {
244 unreachable!("The fragment should be a Fragment::Box()");
245 };
246
247 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, false, );
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, ),
275 OutOfFlowFloatBox(ArcRefCell<FloatBox>),
276 Atomic(
277 ArcRefCell<IndependentFormattingContext>,
278 Utf8CodeUnits, Level, ),
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 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 },
360 Self::TextRun(_) => {
361 },
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, ),
407 OutOfFlowFloatBox(WeakRefCell<FloatBox>),
408 Atomic(
409 WeakRefCell<IndependentFormattingContext>,
410 Utf8CodeUnits, Level, ),
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
439struct LineUnderConstruction {
446 start_position: LogicalVec2<Au>,
449
450 inline_position: Au,
453
454 max_block_size: LineBlockSizes,
458
459 has_content: bool,
462
463 has_floats_waiting_to_be_placed: bool,
467
468 placement_among_floats: OnceCell<LogicalRect<Au>>,
473
474 line_items: Vec<LineItem>,
477
478 for_block_level: bool,
480
481 caret_placeholder: Option<CaretPlaceholder>,
484
485 cloneable_inline_box_pbm_size: LogicalSides1D<Au>,
489
490 trailing_hangable_white_space: Au,
492
493 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 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 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 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 !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 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#[derive(Clone, Debug)]
683struct BaselineRelativeSize {
684 ascent: Au,
688
689 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 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 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 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
804struct UnbreakableSegmentUnderConstruction {
808 inline_size: Au,
810
811 max_block_size: LineBlockSizes,
814
815 line_items: Vec<LineItem>,
817
818 has_content: bool,
822
823 incorporates_trailing_white_space: bool,
826
827 trailing_hangable_white_space: Au,
829
830 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 fn reset(&mut self) {
853 assert!(self.line_items.is_empty()); 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 fn push_line_item(&mut self, line_item: LineItem) {
864 self.line_items.push(line_item);
865 }
866
867 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 !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 fn is_phantom(&self) -> bool {
899 LineUnderConstruction::is_phantom_inner(self.has_content, &self.line_items)
900 }
901
902 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 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 style: ServoArc<ComputedValues>,
941
942 flags: InlineContainerStateFlags,
944
945 has_content: Cell<bool>,
948
949 strut_block_sizes: LineBlockSizes,
954
955 nested_strut_block_sizes: LineBlockSizes,
959
960 pub baseline_offset: Au,
966
967 default_font: Option<FontRef>,
970
971 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 ifc: &'layout_data InlineFormattingContext,
983
984 root_nesting_level: InlineContainerState,
994
995 inline_box_state_stack: Vec<Rc<InlineBoxContainerState>>,
999
1000 cloneable_inline_box_pbm_size: LogicalSides1D<Au>,
1004
1005 inline_box_states: Vec<Rc<InlineBoxContainerState>>,
1010
1011 fragments: Vec<Fragment>,
1015
1016 current_line: LineUnderConstruction,
1018
1019 current_line_segment: UnbreakableSegmentUnderConstruction,
1021
1022 force_line_break_before_new_content: bool,
1043
1044 caret_placeholder: Option<CaretPlaceholder>,
1047
1048 deferred_br_clear: Clear,
1052
1053 pub have_deferred_soft_wrap_opportunity: bool,
1057
1058 depends_on_block_constraints: bool,
1061
1062 white_space_collapse: WhiteSpaceCollapse,
1067
1068 text_wrap_mode: TextWrapMode,
1073
1074 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 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 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 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 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, };
1193
1194 self.current_line_segment
1195 .max_block_size
1196 .max_assign(&inline_box_state.base.nested_strut_block_sizes);
1197
1198 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 self.possibly_flush_deferred_forced_line_break();
1222
1223 self.process_soft_wrap_opportunity();
1229
1230 self.commit_current_segment_to_line();
1233
1234 self.finish_current_line_and_reset(
1237 true, false, );
1240 }
1241
1242 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 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 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 let increment = block_end_position - self.current_line.start_position.block;
1307 sequential_layout_state.advance_block_position(increment);
1308
1309 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 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 self.current_line.cloneable_inline_box_pbm_size =
1335 line_to_layout.cloneable_inline_box_pbm_size;
1336 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 fragments.is_empty() &&
1381 self.positioning_context.len() == start_positioning_context_length
1382 {
1383 return;
1384 }
1385
1386 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, )));
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 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 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 let text_justify = containing_block.style.get_text_justify();
1507 let justification_adjustment = match (text_align_keyword, text_justify) {
1508 (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 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 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 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 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 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 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 let can_break = self.current_line.has_content;
1671
1672 if !can_break {
1678 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 potential_line_size.inline > containing_block.inline_size() {
1694 return true;
1695 }
1696
1697 if block_would_overflow {
1701 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 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 !self.unbreakable_segment_fits_on_line() {
1728 self.rewind_trailing_inline_box_starts();
1729 self.process_line_break(
1730 false, false, );
1733 }
1734
1735 self.force_line_break_before_new_content = true;
1737 self.caret_placeholder = caret_placeholder.clone();
1738
1739 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, false, );
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 block_contribution.max_assign(¤t_inline_container_state.strut_block_sizes);
1798 }
1799
1800 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 let baseline_shift = effective_baseline_shift(
1810 ¤t_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 ¤t_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 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 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 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 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 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 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 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, false, );
2032 }
2033 self.commit_current_segment_to_line();
2034 }
2035
2036 fn commit_current_segment_to_line(&mut self) {
2039 self.current_line.cloneable_inline_box_pbm_size = self.cloneable_inline_box_pbm_size;
2042
2043 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 !self.current_line_segment.incorporates_trailing_white_space {
2066 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 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 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 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 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 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 LineBreak::Auto => LineBreakStrictness::Normal,
2175 });
2176 options.word_option = Some(match word_break {
2177 WordBreak::Normal | WordBreak::KeepAll => LineBreakWordOption::Normal,
2178 WordBreak::BreakWord => LineBreakWordOption::Normal,
2180 WordBreak::BreakAll => LineBreakWordOption::BreakAll,
2181 });
2182
2183 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 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, 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 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 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 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 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 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 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 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 let size_for_baseline_positioning = BaselineRelativeSize { ascent, descent };
2684
2685 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 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 (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 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 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 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 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 fragment = fragment.with_baselines(baselines);
2821
2822 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 !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 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 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 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
3018fn 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 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 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
3074struct 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 pending_whitespace: ContentSizes,
3082 pending_opening_pbm_for_inline_boxes: Au,
3085 uncleared_floats: LogicalSides1D<ContentSizes>,
3087 cleared_floats: LogicalSides1D<ContentSizes>,
3089 had_content_yet_for_min_content: bool,
3092 had_content_yet_for_max_content: bool,
3095 ending_inline_pbm_stack: Vec<Au>,
3098 text_wrap_mode_stack: Vec<TextWrapMode>,
3100 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 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 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 let break_at_start = segment.break_at_start && self.had_content_yet_for_min_content;
3250
3251 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 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 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 self.commit_pending_opening_pbm_for_inline_boxes();
3354
3355 self.line_break_opportunity();
3357
3358 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, 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 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
3462fn 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}