Skip to main content

layout/flow/
construct.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use layout_api::LayoutNode;
6use rayon::iter::{IntoParallelIterator, ParallelIterator};
7use script::layout_dom::ServoLayoutNode;
8use servo_arc::Arc;
9use style::properties::ComputedValues;
10use style::properties::longhands::list_style_position::computed_value::T as ListStylePosition;
11use style::selector_parser::PseudoElement;
12use style::str::char_is_whitespace;
13use style::values::specified::box_::DisplayOutside as StyloDisplayOutside;
14
15use super::OutsideMarker;
16use super::inline::construct::InlineFormattingContextBuilder;
17use super::inline::inline_box::InlineBox;
18use super::inline::{InlineFormattingContext, SharedInlineStyles};
19use crate::PropagatedBoxTreeData;
20use crate::cell::ArcRefCell;
21use crate::context::LayoutContext;
22use crate::dom::{BoxSlot, LayoutBox, NodeExt};
23use crate::dom_traversal::{
24    BoxTreeString, Contents, NodeAndStyleInfo, NonReplacedContents, PseudoElementContentItem,
25    TraversalHandler,
26};
27use crate::flow::float::FloatBox;
28use crate::flow::same_formatting_context_block::SameFormattingContextBlock;
29use crate::flow::{BlockContainer, BlockFormattingContext, BlockLevelBox, TextareaSize};
30use crate::formatting_contexts::{
31    IndependentFormattingContext, IndependentFormattingContextContents,
32};
33use crate::fragment_tree::FragmentFlags;
34use crate::layout_box_base::LayoutBoxBase;
35use crate::positioned::AbsolutelyPositionedBox;
36use crate::style_ext::{ComputedValuesExt, DisplayGeneratingBox, DisplayInside, DisplayOutside};
37use crate::table::{AnonymousTableContent, AnonymousTableContentElement, Table};
38
39impl BlockFormattingContext {
40    pub(crate) fn construct(
41        context: &LayoutContext,
42        info: &NodeAndStyleInfo<'_>,
43        contents: NonReplacedContents,
44        propagated_data: PropagatedBoxTreeData,
45        is_list_item: bool,
46        is_table_cell: bool,
47    ) -> Self {
48        Self::from_block_container(
49            BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
50            is_table_cell,
51            Self::textarea_size(&info.node),
52        )
53    }
54
55    /// Calculates the content size for textareas that are instead dictated by
56    /// their rows.
57    fn textarea_size(node: &ServoLayoutNode) -> Option<TextareaSize> {
58        node.textarea_rows().map(|rows| TextareaSize { rows })
59    }
60
61    pub(crate) fn from_block_container(
62        contents: BlockContainer,
63        is_table_cell: bool,
64        textarea_size: Option<TextareaSize>,
65    ) -> Self {
66        let contains_floats = contents.contains_floats();
67        Self {
68            contents,
69            contains_floats,
70            is_table_cell,
71            textarea_size,
72        }
73    }
74}
75
76struct BlockLevelJob<'dom> {
77    info: NodeAndStyleInfo<'dom>,
78    box_slot: BoxSlot<'dom>,
79    propagated_data: PropagatedBoxTreeData,
80    kind: BlockLevelCreator,
81}
82
83pub(crate) enum BlockLevelCreator {
84    SameFormattingContextBlock(IntermediateBlockContainer),
85    Independent {
86        display_inside: DisplayInside,
87        contents: Contents,
88    },
89    OutOfFlowAbsolutelyPositionedBox {
90        display_inside: DisplayInside,
91        contents: Contents,
92    },
93    OutOfFlowFloatBox {
94        display_inside: DisplayInside,
95        contents: Contents,
96    },
97    OutsideMarker {
98        list_item_style: Arc<ComputedValues>,
99        contents: Vec<PseudoElementContentItem>,
100    },
101    AnonymousTable {
102        table_block: ArcRefCell<BlockLevelBox>,
103    },
104}
105
106impl BlockLevelCreator {
107    pub(crate) fn new_for_inflow_block_level_element<'dom>(
108        info: &NodeAndStyleInfo<'dom>,
109        display_inside: DisplayInside,
110        contents: Contents,
111        propagated_data: PropagatedBoxTreeData,
112    ) -> Self {
113        match contents {
114            Contents::NonReplaced(contents) => match display_inside {
115                DisplayInside::Flow { is_list_item }
116                    // Fragment flags are just used to indicate whether the element is replaced or a widget,
117                    // and whether it's a body or root propagating its `overflow` to the viewport. We have
118                    // already checked that the former is not the case.
119                    // TODO(#39932): empty flags are wrong when propagating `overflow` to the viewport.
120                    if !info.style.establishes_block_formatting_context(
121                        FragmentFlags::empty()
122                    ) =>
123                {
124                    Self::SameFormattingContextBlock(
125                        IntermediateBlockContainer::Deferred {
126                            contents,
127                            propagated_data,
128                            is_list_item,
129                        },
130                    )
131                },
132                _ => Self::Independent {
133                    display_inside,
134                    contents: Contents::NonReplaced(contents),
135                },
136            },
137            Contents::Replaced(_) | Contents::Widget(_) => Self::Independent {
138                display_inside,
139                contents,
140            },
141        }
142    }
143}
144
145/// A block container that may still have to be constructed.
146///
147/// Represents either the inline formatting context of an anonymous block
148/// box or the yet-to-be-computed block container generated from the children
149/// of a given element.
150///
151/// Deferring allows using rayon’s `into_par_iter`.
152pub(crate) enum IntermediateBlockContainer {
153    InlineFormattingContext(BlockContainer),
154    Deferred {
155        contents: NonReplacedContents,
156        propagated_data: PropagatedBoxTreeData,
157        is_list_item: bool,
158    },
159}
160
161/// A builder for a block container.
162///
163/// This builder starts from the first child of a given DOM node
164/// and does a preorder traversal of all of its inclusive siblings.
165pub(crate) struct BlockContainerBuilder<'dom, 'style> {
166    context: &'style LayoutContext<'style>,
167
168    /// This NodeAndStyleInfo contains the root node, the corresponding pseudo
169    /// content designator, and the block container style.
170    info: &'style NodeAndStyleInfo<'dom>,
171
172    /// The list of block-level boxes to be built for the final block container.
173    ///
174    /// Contains all the block-level jobs we found traversing the tree
175    /// so far, if this is empty at the end of the traversal and the ongoing
176    /// inline formatting context is not empty, the block container establishes
177    /// an inline formatting context (see end of `build`).
178    ///
179    /// DOM nodes which represent block-level boxes are immediately pushed
180    /// to this list with their style without ever being traversed at this
181    /// point, instead we just move to their next sibling. If the DOM node
182    /// doesn't have a next sibling, we either reached the end of the container
183    /// root or there are ongoing inline-level boxes
184    /// (see `handle_block_level_element`).
185    block_level_boxes: Vec<BlockLevelJob<'dom>>,
186
187    /// Whether or not this builder has yet produced an inline formatting context
188    /// with the first formatted line:
189    /// <https://www.w3.org/TR/css-pseudo-4/#first-formatted-line>.
190    /// This is used for `text-indent` and `::first-letter`.
191    have_already_seen_first_formatted_line: bool,
192
193    /// The propagated data to use for BoxTree construction.
194    propagated_data: PropagatedBoxTreeData,
195
196    /// The [`InlineFormattingContextBuilder`] if we have encountered any inline items,
197    /// otherwise None.
198    ///
199    /// TODO: This can be `OnceCell` once `OnceCell::get_mut_or_init` is stabilized.
200    inline_formatting_context_builder: Option<InlineFormattingContextBuilder>,
201
202    /// The [`NodeAndStyleInfo`] to use for anonymous block boxes pushed to the list of
203    /// block-level boxes, lazily initialized.
204    anonymous_box_info: Option<NodeAndStyleInfo<'dom>>,
205
206    /// A collection of content that is being added to an anonymous table. This is
207    /// composed of any sequence of internal table elements or table captions that
208    /// are found outside of a table.
209    anonymous_table_content: Vec<AnonymousTableContent<'dom>>,
210
211    /// Any [`InlineFormattingContexts`] created need to know about the ongoing `display: contents`
212    /// ancestors that have been processed. This `Vec` allows passing those into new
213    /// [`InlineFormattingContext`]s that we create.
214    display_contents_shared_styles: Vec<SharedInlineStyles>,
215}
216
217impl BlockContainer {
218    pub fn construct(
219        context: &LayoutContext,
220        info: &NodeAndStyleInfo<'_>,
221        contents: NonReplacedContents,
222        propagated_data: PropagatedBoxTreeData,
223        is_list_item: bool,
224    ) -> BlockContainer {
225        let mut builder = BlockContainerBuilder::new(context, info, propagated_data);
226
227        if is_list_item &&
228            let Some((marker_info, marker_contents)) = crate::lists::make_marker(context, info)
229        {
230            match marker_info.style.get_list_style_position() {
231                ListStylePosition::Inside => {
232                    builder.handle_list_item_marker_inside(&marker_info, marker_contents)
233                },
234                ListStylePosition::Outside => builder.handle_list_item_marker_outside(
235                    &marker_info,
236                    marker_contents,
237                    info.style.clone(),
238                ),
239            }
240        }
241
242        contents.traverse(context, info, &mut builder);
243        builder.finish()
244    }
245}
246
247impl<'dom, 'style> BlockContainerBuilder<'dom, 'style> {
248    pub(crate) fn new(
249        context: &'style LayoutContext,
250        info: &'style NodeAndStyleInfo<'dom>,
251        propagated_data: PropagatedBoxTreeData,
252    ) -> Self {
253        BlockContainerBuilder {
254            context,
255            info,
256            block_level_boxes: Vec::new(),
257            propagated_data,
258            have_already_seen_first_formatted_line: false,
259            anonymous_box_info: None,
260            anonymous_table_content: Vec::new(),
261            inline_formatting_context_builder: None,
262            display_contents_shared_styles: Vec::new(),
263        }
264    }
265
266    fn currently_processing_inline_box(&self) -> bool {
267        self.inline_formatting_context_builder
268            .as_ref()
269            .is_some_and(InlineFormattingContextBuilder::currently_processing_inline_box)
270    }
271
272    fn ensure_inline_formatting_context_builder(&mut self) -> &mut InlineFormattingContextBuilder {
273        self.inline_formatting_context_builder
274            .get_or_insert_with(|| {
275                // ::first-letter must be on the first formatted line.
276                let should_process_first_letter = !self.have_already_seen_first_formatted_line;
277                let mut builder = InlineFormattingContextBuilder::new(
278                    self.info,
279                    self.context,
280                    should_process_first_letter,
281                );
282                for shared_inline_styles in self.display_contents_shared_styles.iter() {
283                    builder.enter_display_contents(shared_inline_styles.clone());
284                }
285                builder
286            })
287    }
288
289    fn finish_ongoing_inline_formatting_context(&mut self) -> Option<InlineFormattingContext> {
290        self.inline_formatting_context_builder.take()?.finish(
291            self.context,
292            !self.have_already_seen_first_formatted_line,
293            self.info.node.is_single_line_text_input(),
294            self.info.style.to_bidi_level(),
295        )
296    }
297
298    pub(crate) fn finish(mut self) -> BlockContainer {
299        debug_assert!(!self.currently_processing_inline_box());
300
301        self.finish_anonymous_table_if_needed();
302
303        if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context() {
304            // There are two options here. This block was composed of both one or more inline formatting contexts
305            // and child blocks OR this block was a single inline formatting context. In the latter case, we
306            // just return the inline formatting context as the block itself.
307            if self.block_level_boxes.is_empty() {
308                return BlockContainer::InlineFormattingContext(inline_formatting_context);
309            }
310            self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
311        }
312
313        let context = self.context;
314        let block_level_boxes = if self
315            .context
316            .should_parallelize(self.block_level_boxes.len())
317        {
318            self.block_level_boxes
319                .into_par_iter()
320                .map(|block_level_job| block_level_job.finish(context))
321                .collect()
322        } else {
323            self.block_level_boxes
324                .into_iter()
325                .map(|block_level_job| block_level_job.finish(context))
326                .collect()
327        };
328
329        BlockContainer::BlockLevelBoxes(block_level_boxes)
330    }
331
332    fn finish_anonymous_table_if_needed(&mut self) {
333        if self.anonymous_table_content.is_empty() {
334            return;
335        }
336
337        // From https://drafts.csswg.org/css-tables/#fixup-algorithm:
338        //  > If the box’s parent is an inline, run-in, or ruby box (or any box that would perform
339        //  > inlinification of its children), then an inline-table box must be generated; otherwise
340        //  > it must be a table box.
341        //
342        // Note that text content in the inline formatting context isn't enough to force the
343        // creation of an inline table. It requires the parent to be an inline box.
344        let inline_table = self.currently_processing_inline_box();
345
346        let mut contents: Vec<AnonymousTableContent<'dom>> =
347            std::mem::take(&mut self.anonymous_table_content);
348        let last_element_index = contents
349            .iter()
350            .rposition(|content| matches!(content, AnonymousTableContent::Element { .. }))
351            .expect("Anonymous table contents should include some table-level element");
352        let trailing_contents = contents.split_off(last_element_index + 1);
353
354        let (table_info, ifc) = Table::construct_anonymous(
355            self.context,
356            self,
357            self.info,
358            contents,
359            self.propagated_data,
360        );
361
362        if inline_table {
363            self.ensure_inline_formatting_context_builder()
364                .push_atomic(|| ArcRefCell::new(ifc), None);
365        } else {
366            let table_block = ArcRefCell::new(BlockLevelBox::Independent(ifc));
367
368            if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context()
369            {
370                self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
371            }
372
373            let box_slot = table_info.node.box_slot();
374            self.block_level_boxes.push(BlockLevelJob {
375                info: table_info,
376                box_slot,
377                kind: BlockLevelCreator::AnonymousTable { table_block },
378                propagated_data: self.propagated_data,
379            });
380        }
381
382        // If the anonymous table contents end with trailing whitespace, that
383        // whitespace doesn't actually belong to the table. It should be processed outside
384        // ie become a space between the anonymous table and the rest of the block
385        // content. Anonymous tables are really only constructed around internal table
386        // elements and the whitespace between them, so this trailing whitespace should
387        // not be included.
388        //
389        // See https://drafts.csswg.org/css-tables/#fixup-algorithm sections "Remove
390        // irrelevant boxes" and "Generate missing parents."
391        for content in trailing_contents {
392            match content {
393                AnonymousTableContent::Text(info, text) => self.handle_text(&info, text),
394                AnonymousTableContent::EnterDisplayContents(styles) => {
395                    self.enter_display_contents(styles)
396                },
397                AnonymousTableContent::LeaveDisplayContents => self.leave_display_contents(),
398                AnonymousTableContent::Element { .. } => {
399                    unreachable!("All elements were placed inside the table")
400                },
401            }
402        }
403    }
404}
405
406impl<'dom> TraversalHandler<'dom> for BlockContainerBuilder<'dom, '_> {
407    fn handle_element(
408        &mut self,
409        info: &NodeAndStyleInfo<'dom>,
410        display: DisplayGeneratingBox,
411        contents: Contents,
412        box_slot: BoxSlot<'dom>,
413    ) {
414        match display {
415            DisplayGeneratingBox::OutsideInside { outside, inside } => {
416                self.finish_anonymous_table_if_needed();
417
418                match outside {
419                    DisplayOutside::Inline => {
420                        self.handle_inline_level_element(info, inside, contents, box_slot)
421                    },
422                    DisplayOutside::Block => {
423                        let box_style = info.style.get_box();
424                        // Floats and abspos cause blockification, so they only happen in this case.
425                        // https://drafts.csswg.org/css2/visuren.html#dis-pos-flo
426                        if box_style.position.is_absolutely_positioned() {
427                            self.handle_absolutely_positioned_element(
428                                info, inside, contents, box_slot,
429                            )
430                        } else if box_style.float.is_floating() {
431                            self.handle_float_element(info, inside, contents, box_slot)
432                        } else {
433                            self.handle_block_level_element(info, inside, contents, box_slot)
434                        }
435                    },
436                };
437            },
438            DisplayGeneratingBox::LayoutInternal(_) => {
439                self.anonymous_table_content
440                    .push(AnonymousTableContent::Element(Box::new(
441                        AnonymousTableContentElement {
442                            info: info.clone(),
443                            display,
444                            contents,
445                            box_slot,
446                        },
447                    )));
448            },
449        }
450    }
451
452    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: BoxTreeString<'dom>) {
453        if text.is_empty() && !info.node.text_node_needs_caret_placeholder() {
454            return;
455        }
456
457        // If we are building an anonymous table ie this text directly followed internal
458        // table elements that did not have a `<table>` ancestor, then we forward all
459        // whitespace to the table builder.
460        if !self.anonymous_table_content.is_empty() && text.chars().all(char_is_whitespace) {
461            self.anonymous_table_content
462                .push(AnonymousTableContent::Text(info.clone(), text));
463            return;
464        } else {
465            self.finish_anonymous_table_if_needed();
466        }
467
468        self.ensure_inline_formatting_context_builder();
469        self.inline_formatting_context_builder
470            .as_mut()
471            .expect("Should be guaranteed by line above")
472            .push_text_with_possible_first_letter(text, info, self.info, self.context);
473    }
474
475    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
476        if !self.anonymous_table_content.is_empty() {
477            self.anonymous_table_content
478                .push(AnonymousTableContent::EnterDisplayContents(styles));
479            return;
480        }
481        self.display_contents_shared_styles.push(styles.clone());
482        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
483            builder.enter_display_contents(styles);
484        }
485    }
486
487    fn leave_display_contents(&mut self) {
488        if !self.anonymous_table_content.is_empty() {
489            self.anonymous_table_content
490                .push(AnonymousTableContent::LeaveDisplayContents);
491            return;
492        }
493        self.display_contents_shared_styles.pop();
494        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
495            builder.leave_display_contents();
496        }
497    }
498}
499
500impl<'dom> BlockContainerBuilder<'dom, '_> {
501    fn handle_list_item_marker_inside(
502        &mut self,
503        marker_info: &NodeAndStyleInfo<'dom>,
504        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
505    ) {
506        let box_slot = marker_info.node.box_slot();
507        self.handle_inline_level_element(
508            marker_info,
509            DisplayInside::Flow {
510                is_list_item: false,
511            },
512            Contents::for_pseudo_element(contents),
513            box_slot,
514        );
515    }
516
517    fn handle_list_item_marker_outside(
518        &mut self,
519        marker_info: &NodeAndStyleInfo<'dom>,
520        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
521        list_item_style: Arc<ComputedValues>,
522    ) {
523        let box_slot = marker_info.node.box_slot();
524        self.block_level_boxes.push(BlockLevelJob {
525            info: marker_info.clone(),
526            box_slot,
527            kind: BlockLevelCreator::OutsideMarker {
528                contents,
529                list_item_style,
530            },
531            propagated_data: self.propagated_data,
532        });
533    }
534
535    fn handle_inline_level_element(
536        &mut self,
537        info: &NodeAndStyleInfo<'dom>,
538        display_inside: DisplayInside,
539        contents: Contents,
540        box_slot: BoxSlot<'dom>,
541    ) {
542        let context = self.context;
543        let old_layout_box = box_slot.take_layout_box();
544        let (is_list_item, non_replaced_contents) = match (display_inside, contents) {
545            (
546                DisplayInside::Flow { is_list_item },
547                Contents::NonReplaced(non_replaced_contents),
548            ) => (is_list_item, non_replaced_contents),
549            (_, contents) => {
550                // If this inline element is an atomic, handle it and return.
551                let propagated_data = self.propagated_data;
552
553                let construction_callback = || {
554                    ArcRefCell::new(IndependentFormattingContext::construct(
555                        context,
556                        info,
557                        display_inside,
558                        contents,
559                        propagated_data,
560                    ))
561                };
562
563                let atomic = self
564                    .ensure_inline_formatting_context_builder()
565                    .push_atomic(construction_callback, old_layout_box);
566                box_slot.set(LayoutBox::InlineLevel(atomic));
567                return;
568            },
569        };
570
571        // Otherwise, this is just a normal inline box. Whatever happened before, all we need to do
572        // before recurring is to remember this ongoing inline level box.
573        let inline_builder = self.ensure_inline_formatting_context_builder();
574        let inline_item = inline_builder.start_inline_box(
575            || ArcRefCell::new(InlineBox::new(info, context)),
576            old_layout_box,
577        );
578        box_slot.set(LayoutBox::InlineLevel(inline_item));
579
580        if info.node.is_html_wbr_element() {
581            inline_builder.push_soft_wrap_opportunity();
582        }
583
584        if is_list_item &&
585            let Some((marker_info, marker_contents)) =
586                crate::lists::make_marker(self.context, info)
587        {
588            // Ignore `list-style-position` here:
589            // “If the list item is an inline box: this value is equivalent to `inside`.”
590            // https://drafts.csswg.org/css-lists/#list-style-position-outside
591            self.handle_list_item_marker_inside(&marker_info, marker_contents)
592        }
593
594        non_replaced_contents.traverse(self.context, info, self);
595
596        self.finish_anonymous_table_if_needed();
597
598        self.inline_formatting_context_builder
599            .as_mut()
600            .expect("Should be building an InlineFormattingContext")
601            .end_inline_box();
602    }
603
604    fn handle_block_level_element(
605        &mut self,
606        info: &NodeAndStyleInfo<'dom>,
607        display_inside: DisplayInside,
608        contents: Contents,
609        box_slot: BoxSlot<'dom>,
610    ) {
611        let propagated_data = self.propagated_data;
612        let kind = BlockLevelCreator::new_for_inflow_block_level_element(
613            info,
614            display_inside,
615            contents,
616            propagated_data,
617        );
618        let job = BlockLevelJob {
619            info: info.clone(),
620            box_slot,
621            kind,
622            propagated_data,
623        };
624        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
625            if builder.currently_processing_inline_box() {
626                builder.push_block_level_box(job.finish(self.context));
627                return;
628            }
629            if let Some(context) = self.finish_ongoing_inline_formatting_context() {
630                self.push_block_level_job_for_inline_formatting_context(context);
631            }
632        }
633        self.block_level_boxes.push(job);
634
635        // Any block also counts as the first line for the purposes of text indent. Even if
636        // they don't actually indent.
637        self.have_already_seen_first_formatted_line = true;
638    }
639
640    fn handle_absolutely_positioned_element(
641        &mut self,
642        info: &NodeAndStyleInfo<'dom>,
643        display_inside: DisplayInside,
644        contents: Contents,
645        box_slot: BoxSlot<'dom>,
646    ) {
647        // If the original display was inline-level, then we need an inline formatting context
648        // in order to compute the static position correctly.
649        // If it was block-level, we don't want to break an existing inline formatting context,
650        // so push it there (`LineItemLayout::layout_absolute` can handle this well). But if
651        // there is no inline formatting context, then we can avoid creating one.
652        let needs_inline_builder =
653            info.style.get_box().original_display.outside() == StyloDisplayOutside::Inline;
654        if needs_inline_builder {
655            self.ensure_inline_formatting_context_builder();
656        }
657        let inline_builder = self
658            .inline_formatting_context_builder
659            .as_mut()
660            .filter(|builder| needs_inline_builder || !builder.is_empty);
661        if let Some(inline_builder) = inline_builder {
662            let constructor = || {
663                ArcRefCell::new(AbsolutelyPositionedBox::construct(
664                    self.context,
665                    info,
666                    display_inside,
667                    contents,
668                ))
669            };
670            let old_layout_box = box_slot.take_layout_box();
671            let inline_level_box =
672                inline_builder.push_absolutely_positioned_box(constructor, old_layout_box);
673            box_slot.set(LayoutBox::InlineLevel(inline_level_box));
674            return;
675        }
676
677        let kind = BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
678            contents,
679            display_inside,
680        };
681        self.block_level_boxes.push(BlockLevelJob {
682            info: info.clone(),
683            box_slot,
684            kind,
685            propagated_data: self.propagated_data,
686        });
687    }
688
689    fn handle_float_element(
690        &mut self,
691        info: &NodeAndStyleInfo<'dom>,
692        display_inside: DisplayInside,
693        contents: Contents,
694        box_slot: BoxSlot<'dom>,
695    ) {
696        if let Some(builder) = self.inline_formatting_context_builder.as_mut() &&
697            !builder.is_empty
698        {
699            let constructor = || {
700                ArcRefCell::new(FloatBox::construct(
701                    self.context,
702                    info,
703                    display_inside,
704                    contents,
705                    self.propagated_data,
706                ))
707            };
708            let old_layout_box = box_slot.take_layout_box();
709            let inline_level_box = builder.push_float_box(constructor, old_layout_box);
710            box_slot.set(LayoutBox::InlineLevel(inline_level_box));
711            return;
712        }
713
714        let kind = BlockLevelCreator::OutOfFlowFloatBox {
715            contents,
716            display_inside,
717        };
718        self.block_level_boxes.push(BlockLevelJob {
719            info: info.clone(),
720            box_slot,
721            kind,
722            propagated_data: self.propagated_data,
723        });
724    }
725
726    fn push_block_level_job_for_inline_formatting_context(
727        &mut self,
728        inline_formatting_context: InlineFormattingContext,
729    ) {
730        let layout_context = self.context;
731        let anonymous_info = self
732            .anonymous_box_info
733            .get_or_insert_with(|| {
734                self.info
735                    .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
736                    .expect("Should never fail to create anonymous box")
737            })
738            .clone();
739
740        let box_slot = anonymous_info.node.box_slot();
741        self.block_level_boxes.push(BlockLevelJob {
742            info: anonymous_info,
743            box_slot,
744            kind: BlockLevelCreator::SameFormattingContextBlock(
745                IntermediateBlockContainer::InlineFormattingContext(
746                    BlockContainer::InlineFormattingContext(inline_formatting_context),
747                ),
748            ),
749            propagated_data: self.propagated_data,
750        });
751
752        self.have_already_seen_first_formatted_line = true;
753    }
754}
755
756impl BlockLevelJob<'_> {
757    fn finish(self, context: &LayoutContext) -> ArcRefCell<BlockLevelBox> {
758        let info = &self.info;
759
760        // If this `BlockLevelBox` exists, it has been laid out before and is
761        // reusable.
762        if let Some(block_level_box) = match &*self.box_slot.slot.borrow() {
763            Some(LayoutBox::BlockLevel(block_level_box)) => Some(block_level_box.clone()),
764            _ => None,
765        } {
766            return block_level_box;
767        }
768
769        let block_level_box = match self.kind {
770            BlockLevelCreator::SameFormattingContextBlock(intermediate_block_container) => {
771                let contents = intermediate_block_container.finish(context, info);
772                let contains_floats = contents.contains_floats();
773
774                let base = LayoutBoxBase::new(info.into(), info.style.clone());
775                base.set_subtree_size(contents.subtree_size() + 1);
776
777                ArcRefCell::new(BlockLevelBox::SameFormattingContextBlock(
778                    SameFormattingContextBlock::new(base, contents, contains_floats),
779                ))
780            },
781            BlockLevelCreator::Independent {
782                display_inside,
783                contents,
784            } => {
785                let context = IndependentFormattingContext::construct(
786                    context,
787                    info,
788                    display_inside,
789                    contents,
790                    self.propagated_data,
791                );
792                ArcRefCell::new(BlockLevelBox::Independent(context))
793            },
794            BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
795                display_inside,
796                contents,
797            } => ArcRefCell::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
798                ArcRefCell::new(AbsolutelyPositionedBox::construct(
799                    context,
800                    info,
801                    display_inside,
802                    contents,
803                )),
804            )),
805            BlockLevelCreator::OutOfFlowFloatBox {
806                display_inside,
807                contents,
808            } => ArcRefCell::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
809                context,
810                info,
811                display_inside,
812                contents,
813                self.propagated_data,
814            ))),
815            BlockLevelCreator::OutsideMarker {
816                contents,
817                list_item_style,
818            } => {
819                let contents = NonReplacedContents::OfPseudoElement(contents);
820                let block_container = BlockContainer::construct(
821                    context,
822                    info,
823                    contents,
824                    self.propagated_data,
825                    false, /* is_list_item */
826                );
827                // An outside ::marker must establish a BFC, and can't contain floats.
828                let block_formatting_context = BlockFormattingContext {
829                    contents: block_container,
830                    contains_floats: false,
831                    is_table_cell: false,
832                    textarea_size: None,
833                };
834                ArcRefCell::new(BlockLevelBox::OutsideMarker(OutsideMarker {
835                    context: IndependentFormattingContext::new(
836                        LayoutBoxBase::new(info.into(), info.style.clone()),
837                        IndependentFormattingContextContents::Flow(block_formatting_context),
838                        self.propagated_data,
839                    ),
840                    list_item_style,
841                }))
842            },
843            BlockLevelCreator::AnonymousTable { table_block } => table_block,
844        };
845        self.box_slot
846            .set(LayoutBox::BlockLevel(block_level_box.clone()));
847        block_level_box
848    }
849}
850
851impl IntermediateBlockContainer {
852    fn finish(self, context: &LayoutContext, info: &NodeAndStyleInfo<'_>) -> BlockContainer {
853        match self {
854            IntermediateBlockContainer::Deferred {
855                contents,
856                propagated_data,
857                is_list_item,
858            } => BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
859            IntermediateBlockContainer::InlineFormattingContext(block_container) => block_container,
860        }
861    }
862}