1use app_units::Au;
6use atomic_refcell::AtomicRefCell;
7use layout_api::LayoutNode;
8use malloc_size_of_derive::MallocSizeOf;
9use script::layout_dom::{ServoDangerousStyleElement, ServoLayoutNode};
10use servo_arc::Arc;
11use style::context::SharedStyleContext;
12use style::logical_geometry::LogicalAxis;
13use style::properties::ComputedValues;
14use style::selector_parser::PseudoElement;
15
16use crate::containing_block::{
17 ConstraintSpace, ContainingBlock, ContainingBlockSize, IndefiniteContainingBlock,
18};
19use crate::context::LayoutContext;
20use crate::dom::{LayoutBox, NodeExt, WeakLayoutBox};
21use crate::dom_traversal::{Contents, NodeAndStyleInfo, NonReplacedContents};
22use crate::flexbox::FlexContainer;
23use crate::flow::inline::InlineFormattingContext;
24use crate::flow::{BlockFormattingContext, ContentAlignment};
25use crate::fragment_tree::{BaseFragmentInfo, FragmentFlags};
26use crate::geom::LogicalVec2;
27use crate::layout_box_base::{IndependentFormattingContextLayoutResult, LayoutBoxBase};
28use crate::positioned::{LayoutRootLayoutInputs, PositioningContext};
29use crate::replaced::ReplacedContents;
30use crate::sizing::{
31 self, ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult, LazySize,
32 SizeConstraint,
33};
34use crate::style_ext::{AspectRatio, Display, DisplayInside, LayoutStyle};
35use crate::table::Table;
36use crate::taffy::TaffyContainer;
37use crate::{ArcRefCell, PropagatedBoxTreeData};
38
39#[derive(Debug, MallocSizeOf)]
41pub(crate) struct IndependentFormattingContext {
42 pub base: LayoutBoxBase,
43 contents: IndependentFormattingContextContents,
46 pub propagated_data: PropagatedBoxTreeData,
49 pub layout_root_layout_inputs: AtomicRefCell<Option<Box<LayoutRootLayoutInputs>>>,
52}
53
54#[derive(Debug, MallocSizeOf)]
55pub(crate) enum IndependentFormattingContextContents {
56 Replaced(
58 ReplacedContents,
59 Option<ArcRefCell<IndependentFormattingContext>>,
60 ),
61 Flow(BlockFormattingContext),
62 Flex(FlexContainer),
63 Grid(TaffyContainer),
64 Table(Table),
65 }
67
68impl IndependentFormattingContextContents {
69 fn subtree_size(&self) -> usize {
70 match self {
71 IndependentFormattingContextContents::Replaced(_, widget) => widget
72 .as_ref()
73 .map_or(0, |widget| widget.borrow().subtree_size()),
74 IndependentFormattingContextContents::Flow(block_formatting_context) => {
75 block_formatting_context.contents.subtree_size()
76 },
77 IndependentFormattingContextContents::Flex(flex_container) => {
78 flex_container.subtree_size()
79 },
80 IndependentFormattingContextContents::Grid(taffy_container) => {
81 taffy_container.subtree_size()
82 },
83 IndependentFormattingContextContents::Table(table) => table.subtree_size(),
84 }
85 }
86}
87
88#[derive(Clone, Copy, Debug, Default, MallocSizeOf)]
91pub(crate) struct Baselines {
92 pub first: Option<Au>,
93 pub last: Option<Au>,
94}
95
96impl Baselines {
97 pub(crate) fn offset(&self, block_offset: Au) -> Baselines {
98 Self {
99 first: self.first.map(|first| first + block_offset),
100 last: self.last.map(|last| last + block_offset),
101 }
102 }
103}
104
105impl IndependentFormattingContext {
106 pub(crate) fn new(
107 base: LayoutBoxBase,
108 contents: IndependentFormattingContextContents,
109 propagated_data: PropagatedBoxTreeData,
110 ) -> Self {
111 base.set_subtree_size(contents.subtree_size() + 1);
112 Self {
113 base,
114 contents,
115 propagated_data,
116 layout_root_layout_inputs: None.into(),
117 }
118 }
119
120 pub(crate) fn rebuild(
121 &mut self,
122 layout_context: &LayoutContext,
123 node_and_style_info: &NodeAndStyleInfo,
124 ) {
125 let contents = Contents::for_element(node_and_style_info.node, layout_context);
126 let display = match Display::from(node_and_style_info.style.get_box().display) {
127 Display::None | Display::Contents => {
128 unreachable!("Should never try to rebuild IndependentFormattingContext with no box")
129 },
130 Display::GeneratingBox(display) => {
131 display.used_value_for_contents(&contents, node_and_style_info)
132 },
133 };
134
135 self.base.base_fragment_info = node_and_style_info.into();
138
139 self.contents = Self::construct_contents(
140 layout_context,
141 node_and_style_info,
142 &mut self.base.base_fragment_info,
143 display.display_inside(),
144 contents,
145 self.propagated_data,
146 );
147
148 self.base.clear_fragments_and_dirty_fragment_cache();
149 *self.base.cached_inline_content_size.borrow_mut() = None;
150 self.base.repair_style(&node_and_style_info.style);
151 }
152
153 pub(crate) fn construct(
154 context: &LayoutContext,
155 node_and_style_info: &NodeAndStyleInfo,
156 display_inside: DisplayInside,
157 contents: Contents,
158 propagated_data: PropagatedBoxTreeData,
159 ) -> Self {
160 let mut base_fragment_info: BaseFragmentInfo = node_and_style_info.into();
161 let contents = Self::construct_contents(
162 context,
163 node_and_style_info,
164 &mut base_fragment_info,
165 display_inside,
166 contents,
167 propagated_data,
168 );
169
170 let base = LayoutBoxBase::new(base_fragment_info, node_and_style_info.style.clone());
171 base.set_subtree_size(contents.subtree_size() + 1);
172
173 Self {
174 base,
175 contents,
176 propagated_data,
177 layout_root_layout_inputs: None.into(),
178 }
179 }
180
181 fn construct_contents(
182 context: &LayoutContext,
183 node_and_style_info: &NodeAndStyleInfo,
184 base_fragment_info: &mut BaseFragmentInfo,
185 display_inside: DisplayInside,
186 contents: Contents,
187 propagated_data: PropagatedBoxTreeData,
188 ) -> IndependentFormattingContextContents {
189 let non_replaced_contents = match contents {
190 Contents::Replaced(contents) => {
191 base_fragment_info.flags.insert(FragmentFlags::IS_REPLACED);
192
193 let node = node_and_style_info.node;
195 let should_make_widget = node.pseudo_element_chain().is_empty() &&
196 node.is_root_of_user_agent_widget() &&
197 !contents.is_content_replacement;
198 let widget = should_make_widget.then(|| {
199 Self::construct_for_widget(context, node_and_style_info, propagated_data)
200 });
201
202 return IndependentFormattingContextContents::Replaced(contents, widget);
203 },
204 Contents::Widget(non_replaced_contents) => {
205 base_fragment_info.flags.insert(FragmentFlags::IS_WIDGET);
206 non_replaced_contents
207 },
208 Contents::NonReplaced(non_replaced_contents) => non_replaced_contents,
209 };
210
211 match display_inside {
212 DisplayInside::Flow { is_list_item } | DisplayInside::FlowRoot { is_list_item } => {
213 IndependentFormattingContextContents::Flow(BlockFormattingContext::construct(
214 context,
215 node_and_style_info,
216 non_replaced_contents,
217 propagated_data,
218 is_list_item,
219 false, ))
221 },
222 DisplayInside::Grid => {
223 IndependentFormattingContextContents::Grid(TaffyContainer::construct(
224 context,
225 node_and_style_info,
226 non_replaced_contents,
227 propagated_data,
228 base_fragment_info.flags,
229 ))
230 },
231 DisplayInside::Flex => {
232 IndependentFormattingContextContents::Flex(FlexContainer::construct(
233 context,
234 node_and_style_info,
235 non_replaced_contents,
236 propagated_data,
237 ))
238 },
239 DisplayInside::Table => {
240 let table_grid_style = context
241 .style_context
242 .stylist
243 .style_for_anonymous::<ServoDangerousStyleElement>(
244 &context.style_context.guards,
245 &PseudoElement::ServoTableGrid,
246 &node_and_style_info.style,
247 );
248 base_fragment_info.flags.insert(FragmentFlags::DO_NOT_PAINT);
249 IndependentFormattingContextContents::Table(Table::construct(
250 context,
251 node_and_style_info,
252 table_grid_style,
253 non_replaced_contents,
254 propagated_data,
255 ))
256 },
257 }
258 }
259
260 fn construct_for_widget(
261 context: &LayoutContext,
262 node_and_style_info: &NodeAndStyleInfo,
263 propagated_data: PropagatedBoxTreeData,
264 ) -> ArcRefCell<IndependentFormattingContext> {
265 let widget_info = node_and_style_info
266 .with_pseudo_element(context, PseudoElement::ServoAnonymousBox)
267 .expect("Should always be able to construct info for anonymous boxes.");
268 let widget_contents =
270 IndependentFormattingContextContents::Flow(BlockFormattingContext::construct(
271 context,
272 &widget_info,
273 NonReplacedContents::OfElement,
274 propagated_data,
275 false, false, ));
278
279 let box_slot = widget_info.node.box_slot();
280 let widget_base = LayoutBoxBase::new((&widget_info).into(), widget_info.style);
281 let widget = ArcRefCell::new(Self::new(widget_base, widget_contents, propagated_data));
282 box_slot.set(LayoutBox::Widget(widget.clone()));
283 widget
284 }
285
286 #[inline]
287 pub fn style(&self) -> &Arc<ComputedValues> {
288 &self.base.style
289 }
290
291 #[inline]
292 pub fn base_fragment_info(&self) -> BaseFragmentInfo {
293 self.base.base_fragment_info
294 }
295
296 pub(crate) fn inline_content_sizes(
297 &self,
298 layout_context: &LayoutContext,
299 constraint_space: &ConstraintSpace,
300 ) -> InlineContentSizesResult {
301 self.base
302 .inline_content_sizes(layout_context, constraint_space, &self.contents)
303 }
304
305 pub(crate) fn tentative_block_content_size(
316 &self,
317 preferred_aspect_ratio: Option<AspectRatio>,
318 inline_stretch_size: Option<Au>,
319 ) -> Option<ContentSizes> {
320 let result = self.tentative_block_content_size_with_dependency(
321 preferred_aspect_ratio,
322 inline_stretch_size,
323 );
324 Some(result?.0)
325 }
326
327 pub(crate) fn tentative_block_content_size_with_dependency(
331 &self,
332 preferred_aspect_ratio: Option<AspectRatio>,
333 inline_stretch_size: Option<Au>,
334 ) -> Option<(ContentSizes, bool)> {
335 match &self.contents {
338 IndependentFormattingContextContents::Replaced(contents, _) => {
339 let ratio = preferred_aspect_ratio?;
341 let writing_mode = self.style().writing_mode;
342 let natural_sizes = contents.logical_natural_sizes(writing_mode);
343 let (block_size, depends_on_inline_stretch_size) =
344 match (natural_sizes.block, natural_sizes.inline) {
345 (Some(block_size), None) => (block_size, false),
346 (_, Some(inline_size)) => (
347 ratio.compute_dependent_size(LogicalAxis::Block, inline_size),
348 false,
349 ),
350 (None, None) => (
351 ratio.compute_dependent_size(
352 LogicalAxis::Block,
353 inline_stretch_size.unwrap_or_default(),
354 ),
355 true,
356 ),
357 };
358 Some((block_size.into(), depends_on_inline_stretch_size))
359 },
360 _ => None,
361 }
362 }
363
364 pub(crate) fn outer_inline_content_sizes(
365 &self,
366 layout_context: &LayoutContext,
367 containing_block: &IndefiniteContainingBlock,
368 auto_minimum: &LogicalVec2<Au>,
369 auto_block_size_stretches_to_containing_block: bool,
370 skippable_for_block_percentage_quirk: bool,
371 ) -> InlineContentSizesResult {
372 sizing::outer_inline(
373 &self.base,
374 &self.layout_style(),
375 containing_block,
376 auto_minimum,
377 auto_block_size_stretches_to_containing_block,
378 self.is_replaced(),
379 true, skippable_for_block_percentage_quirk,
381 |padding_border_sums| self.preferred_aspect_ratio(padding_border_sums),
382 |constraint_space| self.inline_content_sizes(layout_context, constraint_space),
383 |preferred_aspect_ratio| {
384 self.tentative_block_content_size(preferred_aspect_ratio, None)
385 },
386 )
387 }
388
389 pub(crate) fn repair_style(
390 &mut self,
391 context: &SharedStyleContext,
392 node: &ServoLayoutNode,
393 new_style: &Arc<ComputedValues>,
394 ) {
395 self.base.repair_style(new_style);
396 match &mut self.contents {
397 IndependentFormattingContextContents::Replaced(replaced, ..) => {
398 *replaced.selected_style.borrow_mut() = node.selected_style(context);
399 },
400 IndependentFormattingContextContents::Flow(block_formatting_context) => {
401 block_formatting_context.repair_style(context, node, new_style);
402 },
403 IndependentFormattingContextContents::Flex(flex_container) => {
404 flex_container.repair_style(new_style)
405 },
406 IndependentFormattingContextContents::Grid(taffy_container) => {
407 taffy_container.repair_style(new_style)
408 },
409 IndependentFormattingContextContents::Table(table) => {
410 table.repair_style(context, new_style, &self.base)
411 },
412 }
413 }
414
415 #[inline]
416 pub(crate) fn is_block_container(&self) -> bool {
417 matches!(self.contents, IndependentFormattingContextContents::Flow(_))
418 }
419
420 #[inline]
421 pub(crate) fn is_replaced(&self) -> bool {
422 matches!(
423 self.contents,
424 IndependentFormattingContextContents::Replaced(_, _)
425 )
426 }
427
428 #[inline]
429 pub(crate) fn is_table(&self) -> bool {
430 matches!(
431 &self.contents,
432 IndependentFormattingContextContents::Table(_)
433 )
434 }
435
436 #[inline]
437 pub(crate) fn is_grid(&self) -> bool {
438 matches!(
439 &self.contents,
440 IndependentFormattingContextContents::Grid(_)
441 )
442 }
443
444 #[servo_tracing::instrument(
445 name = "IndependentFormattingContext::layout_without_caching",
446 skip_all
447 )]
448 fn layout_without_caching(
449 &self,
450 layout_context: &LayoutContext,
451 positioning_context: &mut PositioningContext,
452 containing_block_for_children: &ContainingBlock,
453 containing_block: &ContainingBlock,
454 preferred_aspect_ratio: Option<AspectRatio>,
455 lazy_block_size: &LazySize,
456 ) -> IndependentFormattingContextLayoutResult {
457 match &self.contents {
458 IndependentFormattingContextContents::Replaced(replaced, widget) => {
459 let mut replaced_layout = replaced.layout(
460 layout_context,
461 containing_block_for_children,
462 preferred_aspect_ratio,
463 &self.base,
464 lazy_block_size,
465 );
466 let resolved_block_size =
468 lazy_block_size.resolve(|| replaced_layout.content_block_size);
469 let widget_size = LogicalVec2 {
470 inline: containing_block_for_children.inline_size(),
471 block: resolved_block_size,
472 };
473 let widget_containing_block = ContainingBlock {
474 size: ContainingBlockSize::new(
475 containing_block_for_children.inline_size(),
476 SizeConstraint::Definite(resolved_block_size),
477 ),
478 style: &self.base.style,
479 };
480 if let Some(widget) = widget {
481 let widget_layout = widget.borrow().layout(
482 layout_context,
483 positioning_context,
484 &widget_containing_block,
485 &widget_containing_block,
486 None,
487 &LazySize::intrinsic(),
488 );
489
490 replaced_layout.fragments.append(
491 widget_layout.fragments,
492 self.base.style.writing_mode,
493 widget_size,
494 );
495 }
496 replaced_layout
497 },
498 IndependentFormattingContextContents::Flow(bfc) => bfc.layout(
499 layout_context,
500 positioning_context,
501 containing_block_for_children,
502 lazy_block_size,
503 Some(&self.base),
504 ),
505 IndependentFormattingContextContents::Flex(fc) => fc.layout(
506 layout_context,
507 positioning_context,
508 containing_block_for_children,
509 lazy_block_size,
510 ),
511 IndependentFormattingContextContents::Grid(fc) => fc.layout(
512 layout_context,
513 positioning_context,
514 containing_block_for_children,
515 containing_block,
516 ),
517 IndependentFormattingContextContents::Table(table) => table.layout(
518 layout_context,
519 positioning_context,
520 containing_block_for_children,
521 containing_block,
522 ),
523 }
524 }
525
526 pub(crate) fn layout_and_is_cached(
527 &self,
528 layout_context: &LayoutContext,
529 positioning_context: &mut PositioningContext,
530 containing_block_for_children: &ContainingBlock,
531 containing_block: &ContainingBlock,
532 preferred_aspect_ratio: Option<AspectRatio>,
533 lazy_block_size: &LazySize,
534 ) -> (IndependentFormattingContextLayoutResult, bool) {
535 let content_block_size_under_default_constraint = match self
536 .base
537 .cached_independent_formatting_context_layout_if_applicable(
538 positioning_context,
539 containing_block_for_children,
540 ) {
541 Ok(cached_layout_result) => return (cached_layout_result, true),
542 Err(v) => v,
543 };
544
545 #[cfg(feature = "tracing")]
546 tracing::debug!(
547 name: "IndependentFormattingContext::layout cache miss",
548 required = ?containing_block_for_children.size,
549 );
550 let mut child_positioning_context = PositioningContext::default();
551 let result = self.layout_without_caching(
552 layout_context,
553 &mut child_positioning_context,
554 containing_block_for_children,
555 containing_block,
556 preferred_aspect_ratio,
557 lazy_block_size,
558 );
559 self.base.cache_independent_formatting_context_layout(
560 containing_block_for_children,
561 &child_positioning_context,
562 content_block_size_under_default_constraint,
563 &result,
564 );
565 positioning_context.append(child_positioning_context);
566 (result, false)
567 }
568
569 pub(crate) fn layout(
570 &self,
571 layout_context: &LayoutContext,
572 positioning_context: &mut PositioningContext,
573 containing_block_for_children: &ContainingBlock,
574 containing_block: &ContainingBlock,
575 preferred_aspect_ratio: Option<AspectRatio>,
576 lazy_block_size: &LazySize,
577 ) -> IndependentFormattingContextLayoutResult {
578 self.layout_and_is_cached(
579 layout_context,
580 positioning_context,
581 containing_block_for_children,
582 containing_block,
583 preferred_aspect_ratio,
584 lazy_block_size,
585 )
586 .0
587 }
588
589 pub(crate) fn content_block_size_under_default_constraint(
590 &self,
591 layout_context: &LayoutContext,
592 positioning_context: &mut PositioningContext,
593 inline_size: Au,
594 containing_block: &ContainingBlock,
595 preferred_aspect_ratio: Option<AspectRatio>,
596 lazy_block_size: &LazySize,
597 ) -> Au {
598 if let Some(content_block_size) = self
599 .base
600 .cached_content_block_size_under_default_constraint_if_applicable(inline_size)
601 {
602 return content_block_size;
603 }
604 self.layout(
605 layout_context,
606 positioning_context,
607 &ContainingBlock {
608 size: ContainingBlockSize::new(
609 inline_size,
610 SizeConstraint::default(), ),
612 style: self.style(),
613 },
614 containing_block,
615 preferred_aspect_ratio,
616 lazy_block_size,
617 )
618 .content_block_size
619 }
620
621 #[inline]
622 pub(crate) fn layout_style(&self) -> LayoutStyle<'_> {
623 match &self.contents {
624 IndependentFormattingContextContents::Replaced(replaced, _) => {
625 replaced.layout_style(&self.base)
626 },
627 IndependentFormattingContextContents::Flow(fc) => fc.layout_style(&self.base),
628 IndependentFormattingContextContents::Flex(fc) => fc.layout_style(),
629 IndependentFormattingContextContents::Grid(fc) => fc.layout_style(),
630 IndependentFormattingContextContents::Table(fc) => fc.layout_style(None),
631 }
632 }
633
634 #[inline]
635 pub(crate) fn preferred_aspect_ratio(
636 &self,
637 padding_border_sums: &LogicalVec2<Au>,
638 ) -> Option<AspectRatio> {
639 match &self.contents {
640 IndependentFormattingContextContents::Replaced(replaced, _) => {
641 replaced.preferred_aspect_ratio(self.style(), padding_border_sums)
642 },
643 _ => None,
645 }
646 }
647
648 pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
649 match &self.contents {
650 IndependentFormattingContextContents::Replaced(_, widget) => {
651 if let Some(widget) = widget {
652 widget.borrow_mut().base.parent_box.replace(layout_box);
653 }
654 },
655 IndependentFormattingContextContents::Flow(contents) => {
656 contents.attached_to_tree(layout_box)
657 },
658 IndependentFormattingContextContents::Flex(contents) => {
659 contents.attached_to_tree(layout_box)
660 },
661 IndependentFormattingContextContents::Grid(contents) => {
662 contents.attached_to_tree(layout_box)
663 },
664 IndependentFormattingContextContents::Table(contents) => {
665 contents.attached_to_tree(layout_box)
666 },
667 }
668 }
669
670 pub(crate) fn subtree_size(&self) -> usize {
671 self.base.subtree_size()
672 }
673
674 pub(crate) fn set_selection(&self, selected: bool) -> bool {
677 match &self.contents {
678 IndependentFormattingContextContents::Replaced(replaced_contents, ..) => {
679 replaced_contents.set_selection(selected)
680 },
681 _ => false,
682 }
683 }
684
685 pub(crate) fn inline_formatting_context(&self) -> Option<&InlineFormattingContext> {
686 match &self.contents {
687 IndependentFormattingContextContents::Flow(block_formatting_context) => {
688 block_formatting_context.inline_formatting_context()
689 },
690 _ => None,
691 }
692 }
693
694 pub(crate) fn content_alignment_for_block_formatting_context(&self) -> ContentAlignment {
695 match &self.contents {
696 IndependentFormattingContextContents::Flow(block_formatting_context) => {
697 block_formatting_context.content_alignment(&self.base)
698 },
699 _ => panic!("Not a block formattign context"),
700 }
701 }
702}
703
704impl ComputeInlineContentSizes for IndependentFormattingContextContents {
705 fn compute_inline_content_sizes(
706 &self,
707 layout_context: &LayoutContext,
708 constraint_space: &ConstraintSpace,
709 ) -> InlineContentSizesResult {
710 match self {
711 Self::Replaced(inner, _) => {
712 inner.compute_inline_content_sizes(layout_context, constraint_space)
713 },
714 Self::Flow(inner) => inner
715 .contents
716 .compute_inline_content_sizes(layout_context, constraint_space),
717 Self::Flex(inner) => {
718 inner.compute_inline_content_sizes(layout_context, constraint_space)
719 },
720 Self::Grid(inner) => {
721 inner.compute_inline_content_sizes(layout_context, constraint_space)
722 },
723 Self::Table(inner) => {
724 inner.compute_inline_content_sizes(layout_context, constraint_space)
725 },
726 }
727 }
728}