1use std::borrow::Cow;
6
7use rayon::iter::{IntoParallelIterator, ParallelIterator};
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 Contents, NodeAndStyleInfo, NonReplacedContents, PseudoElementContentItem, TraversalHandler,
25};
26use crate::flow::float::FloatBox;
27use crate::flow::{BlockContainer, BlockFormattingContext, BlockLevelBox};
28use crate::formatting_contexts::IndependentFormattingContext;
29use crate::fragment_tree::FragmentFlags;
30use crate::layout_box_base::LayoutBoxBase;
31use crate::positioned::AbsolutelyPositionedBox;
32use crate::style_ext::{ComputedValuesExt, DisplayGeneratingBox, DisplayInside, DisplayOutside};
33use crate::table::{AnonymousTableContent, Table};
34
35impl BlockFormattingContext {
36 pub(crate) fn construct(
37 context: &LayoutContext,
38 info: &NodeAndStyleInfo<'_>,
39 contents: NonReplacedContents,
40 propagated_data: PropagatedBoxTreeData,
41 is_list_item: bool,
42 ) -> Self {
43 Self::from_block_container(BlockContainer::construct(
44 context,
45 info,
46 contents,
47 propagated_data,
48 is_list_item,
49 ))
50 }
51
52 pub(crate) fn from_block_container(contents: BlockContainer) -> Self {
53 let contains_floats = contents.contains_floats();
54 Self {
55 contents,
56 contains_floats,
57 }
58 }
59}
60
61struct BlockLevelJob<'dom> {
62 info: NodeAndStyleInfo<'dom>,
63 box_slot: BoxSlot<'dom>,
64 propagated_data: PropagatedBoxTreeData,
65 kind: BlockLevelCreator,
66}
67
68enum BlockLevelCreator {
69 SameFormattingContextBlock(IntermediateBlockContainer),
70 Independent {
71 display_inside: DisplayInside,
72 contents: Contents,
73 },
74 OutOfFlowAbsolutelyPositionedBox {
75 display_inside: DisplayInside,
76 contents: Contents,
77 },
78 OutOfFlowFloatBox {
79 display_inside: DisplayInside,
80 contents: Contents,
81 },
82 OutsideMarker {
83 list_item_style: Arc<ComputedValues>,
84 contents: Vec<PseudoElementContentItem>,
85 },
86 AnonymousTable {
87 table_block: ArcRefCell<BlockLevelBox>,
88 },
89}
90
91enum IntermediateBlockContainer {
99 InlineFormattingContext(BlockContainer),
100 Deferred {
101 contents: NonReplacedContents,
102 propagated_data: PropagatedBoxTreeData,
103 is_list_item: bool,
104 },
105}
106
107pub(crate) struct BlockContainerBuilder<'dom, 'style> {
112 context: &'style LayoutContext<'style>,
113
114 info: &'style NodeAndStyleInfo<'dom>,
117
118 block_level_boxes: Vec<BlockLevelJob<'dom>>,
132
133 have_already_seen_first_line_for_text_indent: bool,
136
137 propagated_data: PropagatedBoxTreeData,
139
140 inline_formatting_context_builder: Option<InlineFormattingContextBuilder>,
145
146 anonymous_box_info: Option<NodeAndStyleInfo<'dom>>,
149
150 anonymous_table_content: Vec<AnonymousTableContent<'dom>>,
154
155 display_contents_shared_styles: Vec<SharedInlineStyles>,
159}
160
161impl BlockContainer {
162 pub fn construct(
163 context: &LayoutContext,
164 info: &NodeAndStyleInfo<'_>,
165 contents: NonReplacedContents,
166 propagated_data: PropagatedBoxTreeData,
167 is_list_item: bool,
168 ) -> BlockContainer {
169 let mut builder = BlockContainerBuilder::new(context, info, propagated_data);
170
171 if is_list_item {
172 if let Some((marker_info, marker_contents)) = crate::lists::make_marker(context, info) {
173 match marker_info.style.clone_list_style_position() {
174 ListStylePosition::Inside => {
175 builder.handle_list_item_marker_inside(&marker_info, marker_contents)
176 },
177 ListStylePosition::Outside => builder.handle_list_item_marker_outside(
178 &marker_info,
179 marker_contents,
180 info.style.clone(),
181 ),
182 }
183 }
184 }
185
186 contents.traverse(context, info, &mut builder);
187 builder.finish()
188 }
189}
190
191impl<'dom, 'style> BlockContainerBuilder<'dom, 'style> {
192 pub(crate) fn new(
193 context: &'style LayoutContext,
194 info: &'style NodeAndStyleInfo<'dom>,
195 propagated_data: PropagatedBoxTreeData,
196 ) -> Self {
197 BlockContainerBuilder {
198 context,
199 info,
200 block_level_boxes: Vec::new(),
201 propagated_data,
202 have_already_seen_first_line_for_text_indent: false,
203 anonymous_box_info: None,
204 anonymous_table_content: Vec::new(),
205 inline_formatting_context_builder: None,
206 display_contents_shared_styles: Vec::new(),
207 }
208 }
209
210 fn currently_processing_inline_box(&self) -> bool {
211 self.inline_formatting_context_builder
212 .as_ref()
213 .is_some_and(InlineFormattingContextBuilder::currently_processing_inline_box)
214 }
215
216 fn ensure_inline_formatting_context_builder(&mut self) -> &mut InlineFormattingContextBuilder {
217 self.inline_formatting_context_builder
218 .get_or_insert_with(|| {
219 let mut builder = InlineFormattingContextBuilder::new(self.info);
220 for shared_inline_styles in self.display_contents_shared_styles.iter() {
221 builder.enter_display_contents(shared_inline_styles.clone());
222 }
223 builder
224 })
225 }
226
227 fn finish_ongoing_inline_formatting_context(&mut self) -> Option<InlineFormattingContext> {
228 self.inline_formatting_context_builder.take()?.finish(
229 self.context,
230 !self.have_already_seen_first_line_for_text_indent,
231 self.info.node.is_single_line_text_input(),
232 self.info.style.to_bidi_level(),
233 self.context.rendering_group_id,
234 )
235 }
236
237 pub(crate) fn finish(mut self) -> BlockContainer {
238 debug_assert!(!self.currently_processing_inline_box());
239
240 self.finish_anonymous_table_if_needed();
241
242 if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context() {
243 if self.block_level_boxes.is_empty() {
247 return BlockContainer::InlineFormattingContext(inline_formatting_context);
248 }
249 self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
250 }
251
252 let context = self.context;
253 let block_level_boxes = if self.context.use_rayon {
254 self.block_level_boxes
255 .into_par_iter()
256 .map(|block_level_job| block_level_job.finish(context))
257 .collect()
258 } else {
259 self.block_level_boxes
260 .into_iter()
261 .map(|block_level_job| block_level_job.finish(context))
262 .collect()
263 };
264
265 BlockContainer::BlockLevelBoxes(block_level_boxes)
266 }
267
268 fn finish_anonymous_table_if_needed(&mut self) {
269 if self.anonymous_table_content.is_empty() {
270 return;
271 }
272
273 let inline_table = self.currently_processing_inline_box();
281
282 let contents: Vec<AnonymousTableContent<'dom>> =
283 self.anonymous_table_content.drain(..).collect();
284 let last_text = match contents.last() {
285 Some(AnonymousTableContent::Text(info, text)) => Some((info.clone(), text.clone())),
286 _ => None,
287 };
288
289 let (table_info, ifc) =
290 Table::construct_anonymous(self.context, self.info, contents, self.propagated_data);
291
292 if inline_table {
293 self.ensure_inline_formatting_context_builder()
294 .push_atomic(|| ArcRefCell::new(ifc), None);
295 } else {
296 let table_block = ArcRefCell::new(BlockLevelBox::Independent(ifc));
297
298 if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context()
299 {
300 self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
301 }
302
303 let box_slot = table_info.node.box_slot();
304 self.block_level_boxes.push(BlockLevelJob {
305 info: table_info,
306 box_slot,
307 kind: BlockLevelCreator::AnonymousTable { table_block },
308 propagated_data: self.propagated_data,
309 });
310 }
311
312 if let Some((info, text)) = last_text {
322 self.handle_text(&info, text);
323 }
324 }
325}
326
327impl<'dom> TraversalHandler<'dom> for BlockContainerBuilder<'dom, '_> {
328 fn handle_element(
329 &mut self,
330 info: &NodeAndStyleInfo<'dom>,
331 display: DisplayGeneratingBox,
332 contents: Contents,
333 box_slot: BoxSlot<'dom>,
334 ) {
335 match display {
336 DisplayGeneratingBox::OutsideInside { outside, inside } => {
337 self.finish_anonymous_table_if_needed();
338
339 match outside {
340 DisplayOutside::Inline => {
341 self.handle_inline_level_element(info, inside, contents, box_slot)
342 },
343 DisplayOutside::Block => {
344 let box_style = info.style.get_box();
345 if box_style.position.is_absolutely_positioned() {
348 self.handle_absolutely_positioned_element(
349 info, inside, contents, box_slot,
350 )
351 } else if box_style.float.is_floating() {
352 self.handle_float_element(info, inside, contents, box_slot)
353 } else {
354 self.handle_block_level_element(info, inside, contents, box_slot)
355 }
356 },
357 };
358 },
359 DisplayGeneratingBox::LayoutInternal(_) => {
360 self.anonymous_table_content
361 .push(AnonymousTableContent::Element {
362 info: info.clone(),
363 display,
364 contents,
365 box_slot,
366 });
367 },
368 }
369 }
370
371 fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: Cow<'dom, str>) {
372 if text.is_empty() {
373 return;
374 }
375
376 if !self.anonymous_table_content.is_empty() && text.chars().all(char_is_whitespace) {
380 self.anonymous_table_content
381 .push(AnonymousTableContent::Text(info.clone(), text));
382 return;
383 } else {
384 self.finish_anonymous_table_if_needed();
385 }
386
387 self.ensure_inline_formatting_context_builder()
388 .push_text(text, info);
389 }
390
391 fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
392 self.display_contents_shared_styles.push(styles.clone());
393 if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
394 builder.enter_display_contents(styles);
395 }
396 }
397
398 fn leave_display_contents(&mut self) {
399 self.display_contents_shared_styles.pop();
400 if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
401 builder.leave_display_contents();
402 }
403 }
404}
405
406impl<'dom> BlockContainerBuilder<'dom, '_> {
407 fn handle_list_item_marker_inside(
408 &mut self,
409 marker_info: &NodeAndStyleInfo<'dom>,
410 contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
411 ) {
412 let box_slot = marker_info.node.box_slot();
413 self.handle_inline_level_element(
414 marker_info,
415 DisplayInside::Flow {
416 is_list_item: false,
417 },
418 Contents::for_pseudo_element(contents),
419 box_slot,
420 );
421 }
422
423 fn handle_list_item_marker_outside(
424 &mut self,
425 marker_info: &NodeAndStyleInfo<'dom>,
426 contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
427 list_item_style: Arc<ComputedValues>,
428 ) {
429 let box_slot = marker_info.node.box_slot();
430 self.block_level_boxes.push(BlockLevelJob {
431 info: marker_info.clone(),
432 box_slot,
433 kind: BlockLevelCreator::OutsideMarker {
434 contents,
435 list_item_style,
436 },
437 propagated_data: self.propagated_data,
438 });
439 }
440
441 fn handle_inline_level_element(
442 &mut self,
443 info: &NodeAndStyleInfo<'dom>,
444 display_inside: DisplayInside,
445 contents: Contents,
446 box_slot: BoxSlot<'dom>,
447 ) {
448 let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
449 let (is_list_item, non_replaced_contents) = match (display_inside, contents) {
450 (
451 DisplayInside::Flow { is_list_item },
452 Contents::NonReplaced(non_replaced_contents),
453 ) => (is_list_item, non_replaced_contents),
454 (_, contents) => {
455 let context = self.context;
457 let propagated_data = self.propagated_data;
458
459 let construction_callback = || {
460 ArcRefCell::new(IndependentFormattingContext::construct(
461 context,
462 info,
463 display_inside,
464 contents,
465 propagated_data,
466 ))
467 };
468
469 let atomic = self
470 .ensure_inline_formatting_context_builder()
471 .push_atomic(construction_callback, old_layout_box);
472 box_slot.set(LayoutBox::InlineLevel(vec![atomic]));
473 return;
474 },
475 };
476
477 self.ensure_inline_formatting_context_builder()
480 .start_inline_box(|| ArcRefCell::new(InlineBox::new(info)), old_layout_box);
481
482 if is_list_item {
483 if let Some((marker_info, marker_contents)) =
484 crate::lists::make_marker(self.context, info)
485 {
486 self.handle_list_item_marker_inside(&marker_info, marker_contents)
490 }
491 }
492
493 non_replaced_contents.traverse(self.context, info, self);
495
496 self.finish_anonymous_table_if_needed();
497
498 box_slot.set(LayoutBox::InlineLevel(
504 self.inline_formatting_context_builder
505 .as_mut()
506 .expect("Should be building an InlineFormattingContext")
507 .end_inline_box(),
508 ));
509 }
510
511 fn handle_block_level_element(
512 &mut self,
513 info: &NodeAndStyleInfo<'dom>,
514 display_inside: DisplayInside,
515 contents: Contents,
516 box_slot: BoxSlot<'dom>,
517 ) {
518 if let Some(inline_formatting_context) = self
525 .inline_formatting_context_builder
526 .as_mut()
527 .and_then(|builder| {
528 builder.split_around_block_and_finish(
529 self.context,
530 !self.have_already_seen_first_line_for_text_indent,
531 self.info.style.to_bidi_level(),
532 )
533 })
534 {
535 self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
536 }
537
538 let propagated_data = self.propagated_data;
539 let kind = match contents {
540 Contents::NonReplaced(contents) => match display_inside {
541 DisplayInside::Flow { is_list_item }
542 if !info.style.establishes_block_formatting_context(
545 FragmentFlags::empty()
546 ) =>
547 {
548 BlockLevelCreator::SameFormattingContextBlock(
549 IntermediateBlockContainer::Deferred {
550 contents,
551 propagated_data,
552 is_list_item,
553 },
554 )
555 },
556 _ => BlockLevelCreator::Independent {
557 display_inside,
558 contents: Contents::NonReplaced(contents),
559 },
560 },
561 Contents::Replaced(_) | Contents::Widget(_) => BlockLevelCreator::Independent {
562 display_inside,
563 contents,
564 },
565 };
566 self.block_level_boxes.push(BlockLevelJob {
567 info: info.clone(),
568 box_slot,
569 kind,
570 propagated_data,
571 });
572
573 self.have_already_seen_first_line_for_text_indent = true;
576 }
577
578 fn handle_absolutely_positioned_element(
579 &mut self,
580 info: &NodeAndStyleInfo<'dom>,
581 display_inside: DisplayInside,
582 contents: Contents,
583 box_slot: BoxSlot<'dom>,
584 ) {
585 let needs_inline_builder =
591 info.style.get_box().original_display.outside() == StyloDisplayOutside::Inline;
592 if needs_inline_builder {
593 self.ensure_inline_formatting_context_builder();
594 }
595 let inline_builder = self
596 .inline_formatting_context_builder
597 .as_mut()
598 .filter(|builder| needs_inline_builder || !builder.is_empty);
599 if let Some(inline_builder) = inline_builder {
600 let constructor = || {
601 ArcRefCell::new(AbsolutelyPositionedBox::construct(
602 self.context,
603 info,
604 display_inside,
605 contents,
606 ))
607 };
608 let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
609 let inline_level_box =
610 inline_builder.push_absolutely_positioned_box(constructor, old_layout_box);
611 box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
612 return;
613 }
614
615 let kind = BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
616 contents,
617 display_inside,
618 };
619 self.block_level_boxes.push(BlockLevelJob {
620 info: info.clone(),
621 box_slot,
622 kind,
623 propagated_data: self.propagated_data,
624 });
625 }
626
627 fn handle_float_element(
628 &mut self,
629 info: &NodeAndStyleInfo<'dom>,
630 display_inside: DisplayInside,
631 contents: Contents,
632 box_slot: BoxSlot<'dom>,
633 ) {
634 if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
635 if !builder.is_empty {
636 let constructor = || {
637 ArcRefCell::new(FloatBox::construct(
638 self.context,
639 info,
640 display_inside,
641 contents,
642 self.propagated_data,
643 ))
644 };
645 let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
646 let inline_level_box = builder.push_float_box(constructor, old_layout_box);
647 box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
648 return;
649 }
650 }
651
652 let kind = BlockLevelCreator::OutOfFlowFloatBox {
653 contents,
654 display_inside,
655 };
656 self.block_level_boxes.push(BlockLevelJob {
657 info: info.clone(),
658 box_slot,
659 kind,
660 propagated_data: self.propagated_data,
661 });
662 }
663
664 fn push_block_level_job_for_inline_formatting_context(
665 &mut self,
666 inline_formatting_context: InlineFormattingContext,
667 ) {
668 let layout_context = self.context;
669 let anonymous_info = self
670 .anonymous_box_info
671 .get_or_insert_with(|| {
672 self.info
673 .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
674 .expect("Should never fail to create anonymous box")
675 })
676 .clone();
677
678 let box_slot = anonymous_info.node.box_slot();
679 self.block_level_boxes.push(BlockLevelJob {
680 info: anonymous_info,
681 box_slot,
682 kind: BlockLevelCreator::SameFormattingContextBlock(
683 IntermediateBlockContainer::InlineFormattingContext(
684 BlockContainer::InlineFormattingContext(inline_formatting_context),
685 ),
686 ),
687 propagated_data: self.propagated_data,
688 });
689
690 self.have_already_seen_first_line_for_text_indent = true;
691 }
692}
693
694impl BlockLevelJob<'_> {
695 fn finish(self, context: &LayoutContext) -> ArcRefCell<BlockLevelBox> {
696 let info = &self.info;
697
698 if !info.damage.has_box_damage() {
701 if let Some(block_level_box) = match self.box_slot.slot.as_ref() {
702 Some(box_slot) => match &*box_slot.borrow() {
703 Some(LayoutBox::BlockLevel(block_level_box)) => Some(block_level_box.clone()),
704 _ => None,
705 },
706 None => None,
707 } {
708 return block_level_box;
709 }
710 }
711
712 let block_level_box = match self.kind {
713 BlockLevelCreator::SameFormattingContextBlock(intermediate_block_container) => {
714 let contents = intermediate_block_container.finish(context, info);
715 let contains_floats = contents.contains_floats();
716 ArcRefCell::new(BlockLevelBox::SameFormattingContextBlock {
717 base: LayoutBoxBase::new(info.into(), info.style.clone()),
718 contents,
719 contains_floats,
720 })
721 },
722 BlockLevelCreator::Independent {
723 display_inside,
724 contents,
725 } => {
726 let context = IndependentFormattingContext::construct(
727 context,
728 info,
729 display_inside,
730 contents,
731 self.propagated_data,
732 );
733 ArcRefCell::new(BlockLevelBox::Independent(context))
734 },
735 BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
736 display_inside,
737 contents,
738 } => ArcRefCell::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
739 ArcRefCell::new(AbsolutelyPositionedBox::construct(
740 context,
741 info,
742 display_inside,
743 contents,
744 )),
745 )),
746 BlockLevelCreator::OutOfFlowFloatBox {
747 display_inside,
748 contents,
749 } => ArcRefCell::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
750 context,
751 info,
752 display_inside,
753 contents,
754 self.propagated_data,
755 ))),
756 BlockLevelCreator::OutsideMarker {
757 contents,
758 list_item_style,
759 } => {
760 let contents = NonReplacedContents::OfPseudoElement(contents);
761 let block_container = BlockContainer::construct(
762 context,
763 info,
764 contents,
765 self.propagated_data,
766 false, );
768 let block_formatting_context = BlockFormattingContext {
770 contents: block_container,
771 contains_floats: false,
772 };
773 ArcRefCell::new(BlockLevelBox::OutsideMarker(OutsideMarker {
774 base: LayoutBoxBase::new(info.into(), info.style.clone()),
775 block_formatting_context,
776 list_item_style,
777 }))
778 },
779 BlockLevelCreator::AnonymousTable { table_block } => table_block,
780 };
781 self.box_slot
782 .set(LayoutBox::BlockLevel(block_level_box.clone()));
783 block_level_box
784 }
785}
786
787impl IntermediateBlockContainer {
788 fn finish(self, context: &LayoutContext, info: &NodeAndStyleInfo<'_>) -> BlockContainer {
789 match self {
790 IntermediateBlockContainer::Deferred {
791 contents,
792 propagated_data,
793 is_list_item,
794 } => BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
795 IntermediateBlockContainer::InlineFormattingContext(block_container) => block_container,
796 }
797 }
798}