Skip to main content

layout/
layout_box_base.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 std::fmt::{Debug, Formatter};
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
8
9use app_units::Au;
10use atomic_refcell::{AtomicRef, AtomicRefCell};
11use euclid::Point2D;
12use layout_api::LayoutDamage;
13use malloc_size_of_derive::MallocSizeOf;
14use servo_arc::Arc as ServoArc;
15use style::computed_values::position::T as Position;
16use style::logical_geometry::WritingMode;
17use style::properties::ComputedValues;
18use style::values::specified::align::AlignFlags;
19use style_traits::CSSPixel;
20
21use crate::containing_block::{
22    ConstraintSpace, ContainingBlock, ContainingBlockSize, HasQuirkyBlockSize,
23};
24use crate::context::LayoutContext;
25use crate::dom::{LayoutBox, WeakLayoutBox};
26use crate::flow::CollapsibleWithParentStartMargin;
27use crate::formatting_contexts::Baselines;
28use crate::fragment_tree::{
29    BaseFragmentInfo, BoxFragment, CollapsedBlockMargins, Fragment, FragmentChildren,
30    FragmentStatus, SpecificLayoutInfo,
31};
32use crate::geom::LogicalSides1D;
33use crate::positioned::{PositioningContext, relative_adjustement};
34use crate::sizing::{ComputeInlineContentSizes, InlineContentSizesResult, SizeConstraint};
35use crate::traversal::ElementDamageSet;
36
37/// A box tree node that handles containing information about style and the original DOM
38/// node or pseudo-element that it is based on. This also handles caching of layout values
39/// such as the inline content sizes to avoid recalculating these values during layout
40/// passes.
41///
42/// In the future, this will hold layout results to support incremental layout.
43#[derive(MallocSizeOf)]
44pub(crate) struct LayoutBoxBase {
45    pub base_fragment_info: BaseFragmentInfo,
46    pub style: ServoArc<ComputedValues>,
47    pub cached_inline_content_size:
48        AtomicRefCell<Option<Box<(SizeConstraint, HasQuirkyBlockSize, InlineContentSizesResult)>>>,
49    pub outer_inline_content_sizes_depend_on_content: AtomicBool,
50
51    /// The cached layout results for this [`LayoutBoxBase`]. These are either cached
52    /// independent formatting context results or a cached block layout for use within
53    /// a block flow.
54    cached_layout_result: AtomicRefCell<Option<LayoutResultAndInputs>>,
55
56    /// Whether or not the cached layout result for this [`LayoutBoxBase`] is dirty.
57    /// This flag is used to preserve the cache when it can be used to do a faster
58    /// layout, but cannot be reused directly.
59    cached_layout_result_dirty: AtomicBool,
60
61    /// A count of the number of boxes are in this box's subtree (including itself).
62    /// This is used as a heuristic to know when to perform parallel layout.
63    subtree_size: AtomicUsize,
64
65    pub fragments: AtomicRefCell<Vec<Fragment>>,
66    pub parent_box: Option<WeakLayoutBox>,
67}
68
69impl LayoutBoxBase {
70    pub(crate) fn new(
71        base_fragment_info: BaseFragmentInfo,
72        style: ServoArc<ComputedValues>,
73    ) -> Self {
74        Self {
75            base_fragment_info,
76            style,
77            cached_inline_content_size: AtomicRefCell::default(),
78            outer_inline_content_sizes_depend_on_content: AtomicBool::new(true),
79            cached_layout_result: AtomicRefCell::default(),
80            cached_layout_result_dirty: AtomicBool::default(),
81            subtree_size: AtomicUsize::default(),
82            fragments: AtomicRefCell::default(),
83            parent_box: None,
84        }
85    }
86
87    /// Set the subtree size on this [`LayoutBoxBase`]. This should be done once
88    /// box construction knows how many boxes are in this box's subtree.
89    pub(crate) fn set_subtree_size(&self, size: usize) {
90        self.subtree_size.store(size, Ordering::Relaxed);
91    }
92
93    pub(crate) fn subtree_size(&self) -> usize {
94        self.subtree_size.load(Ordering::Relaxed)
95    }
96
97    /// Get the inline content sizes of a box tree node that extends this [`LayoutBoxBase`], fetch
98    /// the result from a cache when possible.
99    pub(crate) fn inline_content_sizes(
100        &self,
101        layout_context: &LayoutContext,
102        constraint_space: &ConstraintSpace,
103        layout_box: &impl ComputeInlineContentSizes,
104    ) -> InlineContentSizesResult {
105        let mut cache = self.cached_inline_content_size.borrow_mut();
106        if let Some(cached_inline_content_size) = cache.as_ref() {
107            let (previous_cb_maybe_quirky_block_size, had_quirky_block_size, result) =
108                **cached_inline_content_size;
109            if !result.depends_on_block_constraints ||
110                (previous_cb_maybe_quirky_block_size == constraint_space.maybe_quirky_block_size &&
111                    had_quirky_block_size == constraint_space.has_quirky_block_size)
112            {
113                return result;
114            }
115            // TODO: Should we keep multiple caches for various block sizes?
116        }
117
118        let result =
119            layout_box.compute_inline_content_sizes_with_fixup(layout_context, constraint_space);
120        *cache = Some(Box::new((
121            constraint_space.maybe_quirky_block_size,
122            constraint_space.has_quirky_block_size,
123            result,
124        )));
125        result
126    }
127
128    pub(crate) fn fragments(&self) -> AtomicRef<'_, Vec<Fragment>> {
129        self.fragments.borrow()
130    }
131
132    pub(crate) fn add_fragment(&self, fragment: Fragment) {
133        self.fragments.borrow_mut().push(fragment);
134    }
135
136    pub(crate) fn set_fragment(&self, fragment: Fragment) {
137        *self.fragments.borrow_mut() = vec![fragment];
138    }
139
140    pub(crate) fn clear_fragments(&self) {
141        self.fragments.borrow_mut().clear();
142    }
143
144    /// Clear all resulting fragments and dirty and fragment caches. Resulting fragments are
145    /// used for layout queries and fragment caches are used for incremental layout.
146    pub(crate) fn clear_fragments_and_dirty_fragment_cache(&self) {
147        self.clear_fragments();
148        self.cached_layout_result_dirty
149            .store(true, Ordering::Relaxed);
150    }
151
152    pub(crate) fn repair_style(&mut self, new_style: &ServoArc<ComputedValues>) {
153        self.style = new_style.clone();
154        for fragment in self.fragments.borrow().iter() {
155            fragment.repair_style(new_style);
156        }
157    }
158
159    pub(crate) fn parent_box(&self) -> Option<LayoutBox> {
160        self.parent_box.as_ref().and_then(WeakLayoutBox::upgrade)
161    }
162
163    /// Clear fragment layout caches on this base, depending on upward flowing damage, but
164    /// *do not* clear its resulting fragment. The layout cache itself is always cleared,
165    /// but the inline content size cache is cleared conditionally.
166    ///
167    /// Returns true is this [`LayoutBoxBase`] propagates `RecomputeInlineContentSizes`
168    /// and false otherwise.
169    pub(crate) fn invalidate_caches(&self, damage_set: &ElementDamageSet) -> bool {
170        self.cached_layout_result_dirty
171            .store(true, Ordering::Relaxed);
172        if !damage_set.on_element.is_empty() ||
173            damage_set
174                .from_children
175                .contains(LayoutDamage::RecomputeInlineContentSizes)
176        {
177            *self.cached_inline_content_size.borrow_mut() = None;
178        }
179
180        // When a block container has a mix of inline-level and block-level contents, the
181        // inline-level ones are wrapped inside an anonymous block associated with the
182        // block container. The anonymous block has an `auto` size, so its intrinsic
183        // contribution depends on content, but it can't affect the intrinsic size of
184        // ancestors if the block container is sized extrinsically.
185        //
186        // If the intrinsic contributions of this node depend on content, we will need to
187        // clear the cached intrinsic sizes of the parent. But if the contributions are
188        // purely extrinsic, then the intrinsic sizes of the ancestors won't be affected,
189        // and we can keep the cache.
190        !self.base_fragment_info.is_anonymous() &&
191            self.outer_inline_content_sizes_depend_on_content
192                .load(Ordering::Relaxed)
193    }
194
195    /// Clear fragment layout caches on this base, depending on upward flowing damage, and
196    /// also clear its resulting fragment. The layout cache itself is always cleared, but
197    /// the inline content size cache is cleared conditionally.
198    ///
199    /// Returns true is this [`LayoutBoxBase`] propagates `RecomputeInlineContentSizes`
200    /// and false otherwise.
201    pub(crate) fn invalidate_caches_for_fragment_tree_layout(
202        &self,
203        damage_set: &ElementDamageSet,
204    ) -> bool {
205        self.clear_fragments();
206        self.invalidate_caches(damage_set)
207    }
208
209    pub(crate) fn cached_content_block_size_under_default_constraint_if_applicable(
210        &self,
211        inline_size: Au,
212    ) -> Option<Au> {
213        if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
214            return None;
215        }
216
217        let cache = self.cached_layout_result.borrow();
218        let Some(LayoutResultAndInputs::IndependentFormattingContext(cache)) = &*cache else {
219            return None;
220        };
221
222        let cache = &**cache;
223        if !cache.applicable_for_inline_size(inline_size) {
224            return None;
225        }
226
227        cache.content_block_size_under_default_constraint
228    }
229
230    /// Attempts to retrieve the cached layout results. In case of error (the cache is empty,
231    /// dirty, or the value isn't suitable) it provides the cached content block size that
232    /// we would get under a default constraint, if applicable.
233    pub(crate) fn cached_independent_formatting_context_layout_if_applicable(
234        &self,
235        positioning_context: &mut PositioningContext,
236        containing_block_for_children: &ContainingBlock<'_>,
237    ) -> Result<IndependentFormattingContextLayoutResult, Option<Au>> {
238        if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
239            return Err(None);
240        }
241
242        let cache = self.cached_layout_result.borrow();
243        let Some(LayoutResultAndInputs::IndependentFormattingContext(cache)) = &*cache else {
244            return Err(None);
245        };
246
247        let cache = &**cache;
248        if !cache.applicable_for_inline_size(containing_block_for_children.inline_size()) {
249            return Err(None);
250        }
251        if !cache.applicable_for_block_size(
252            containing_block_for_children.maybe_quirky_block_size(),
253            containing_block_for_children.size.has_quirky_block_size,
254        ) {
255            return Err(cache.content_block_size_under_default_constraint);
256        }
257
258        positioning_context.append(cache.positioning_context.clone());
259        Ok(cache.result.clone())
260    }
261
262    pub(crate) fn cache_independent_formatting_context_layout(
263        &self,
264        containing_block_for_children: &ContainingBlock<'_>,
265        child_positioning_context: &PositioningContext,
266        content_block_size_under_default_constraint: Option<Au>,
267        result: &IndependentFormattingContextLayoutResult,
268    ) {
269        self.cached_layout_result_dirty
270            .store(false, Ordering::Relaxed);
271        let mut result_and_inputs = IndependentFormattingContextLayoutResultAndInputs {
272            result: result.clone(),
273            positioning_context: child_positioning_context.clone(),
274            containing_block_for_children_size: containing_block_for_children.size.clone(),
275            content_block_size_under_default_constraint,
276        };
277        if content_block_size_under_default_constraint.is_none() &&
278            result_and_inputs.applicable_for_block_size(
279                SizeConstraint::default(),
280                HasQuirkyBlockSize::default(),
281            )
282        {
283            result_and_inputs.content_block_size_under_default_constraint =
284                Some(result.content_block_size);
285        }
286        *self.cached_layout_result.borrow_mut() = Some(
287            LayoutResultAndInputs::IndependentFormattingContext(Box::new(result_and_inputs)),
288        );
289    }
290
291    pub(crate) fn cached_same_formatting_context_block_if_applicable(
292        &self,
293        containing_block: &ContainingBlock,
294        collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
295        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
296        has_inline_parent: bool,
297    ) -> Option<Arc<BoxFragment>> {
298        if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
299            return None;
300        }
301
302        let mut cached_layout_result = self.cached_layout_result.borrow_mut();
303        let Some(LayoutResultAndInputs::SameFormattingContextBlock(result)) =
304            &mut *cached_layout_result
305        else {
306            return None;
307        };
308
309        if result.containing_block_size != containing_block.size ||
310            result.containing_block_writing_mode != containing_block.style.writing_mode ||
311            result.containing_block_justify_items !=
312                containing_block.style.get_justify_items().computed.0.0 ||
313            result.collapsible_with_parent_start_margin != collapsible_with_parent_start_margin ||
314            result.ignore_block_margins_for_stretch != ignore_block_margins_for_stretch ||
315            result.has_inline_parent != has_inline_parent
316        {
317            return None;
318        }
319
320        let fragment = result.result.fragment.clone();
321        {
322            let mut origin = result.result.original_offset;
323            if self.style.get_box().position == Position::Relative {
324                origin += relative_adjustement(&self.style, containing_block)
325                    .to_physical_offset(containing_block.style.writing_mode)
326            }
327            fragment.base.set_rect_origin(origin);
328        }
329
330        Some(fragment)
331    }
332
333    pub(crate) fn cache_same_formatting_context_block_layout(
334        &self,
335        containing_block: &ContainingBlock,
336        collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
337        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
338        has_inline_parent: bool,
339        fragment: Arc<BoxFragment>,
340    ) {
341        let mut original_offset;
342        {
343            original_offset = fragment.content_rect().origin;
344            if self.style.get_box().position == Position::Relative {
345                original_offset -= relative_adjustement(&self.style, containing_block)
346                    .to_physical_offset(containing_block.style.writing_mode)
347            }
348        }
349
350        self.cached_layout_result_dirty
351            .store(false, Ordering::Relaxed);
352        *self.cached_layout_result.borrow_mut() =
353            Some(LayoutResultAndInputs::SameFormattingContextBlock(Box::new(
354                SameFormattingContextBlockLayoutResultAndInputs {
355                    result: SameFormattingContextBlockLayoutResult {
356                        fragment,
357                        original_offset,
358                    },
359                    containing_block_size: containing_block.size.clone(),
360                    containing_block_writing_mode: containing_block.style.writing_mode,
361                    containing_block_justify_items: containing_block
362                        .style
363                        .get_justify_items()
364                        .computed
365                        .0
366                        .0,
367                    collapsible_with_parent_start_margin,
368                    ignore_block_margins_for_stretch,
369                    has_inline_parent,
370                },
371            )));
372    }
373
374    pub(crate) fn clear_scrollable_overflow_all_on_fragments(&self) {
375        for fragment in self.fragments.borrow().iter() {
376            fragment.clear_scrollable_overflow();
377        }
378    }
379
380    pub(crate) fn mark_fragments_as_descendants_changed(&self) {
381        for fragment in self.fragments.borrow().iter() {
382            if let Some(base) = fragment.base() {
383                base.set_status(FragmentStatus::OnlyDescendantsChanged);
384            }
385        }
386    }
387}
388
389impl Debug for LayoutBoxBase {
390    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
391        f.debug_struct("LayoutBoxBase").finish()
392    }
393}
394
395#[derive(MallocSizeOf)]
396pub(crate) enum LayoutResultAndInputs {
397    IndependentFormattingContext(Box<IndependentFormattingContextLayoutResultAndInputs>),
398    SameFormattingContextBlock(Box<SameFormattingContextBlockLayoutResultAndInputs>),
399}
400
401#[derive(Clone, MallocSizeOf)]
402pub(crate) struct IndependentFormattingContextLayoutResult {
403    pub fragments: FragmentChildren,
404
405    /// <https://drafts.csswg.org/css2/visudet.html#root-height>
406    pub content_block_size: Au,
407
408    /// If this layout is for a block container, this tracks the collapsable size
409    /// of start and end margins and whether or not the block container collapsed through.
410    pub collapsible_margins_in_children: CollapsedBlockMargins,
411
412    /// The contents of a table may force it to become wider than what we would expect
413    /// from 'width' and 'min-width'. This is the resulting inline content size,
414    /// or None for non-table layouts.
415    pub content_inline_size_for_table: Option<Au>,
416
417    /// The offset of the last inflow baseline of this layout in the content area, if
418    /// there was one. This is used to propagate baselines to the ancestors of `display:
419    /// inline-block`.
420    pub baselines: Baselines,
421
422    /// Whether or not this layout depends on the containing block size.
423    pub depends_on_block_constraints: bool,
424
425    /// Additional information of this layout that could be used by Javascripts and devtools.
426    pub specific_layout_info: Option<SpecificLayoutInfo>,
427}
428
429/// A collection of layout inputs and a cached layout result for an IndependentFormattingContext for
430/// use in [`LayoutBoxBase`].
431#[derive(MallocSizeOf)]
432pub(crate) struct IndependentFormattingContextLayoutResultAndInputs {
433    /// The [`IndependentFormattingContextLayoutResult`] for this layout.
434    pub result: IndependentFormattingContextLayoutResult,
435
436    /// The [`ContainingBlockSize`] to use for this box's contents, but not
437    /// for the box itself.
438    pub containing_block_for_children_size: ContainingBlockSize,
439
440    /// A [`PositioningContext`] holding absolutely-positioned descendants
441    /// collected during the layout of this box.
442    pub positioning_context: PositioningContext,
443
444    /// The [`IndependentFormattingContextLayoutResult::content_block_size`]
445    /// that we would get if [`Self::containing_block_for_children_size`] had
446    /// a block size of [`SizeConstraint::default()`], if we know that.
447    /// This is not an input, but we don't always need it, so it's not a
448    /// direct output either. Also note it's not necessarily computed from
449    /// the current inputs, can be reused from previous compatible ones.
450    content_block_size_under_default_constraint: Option<Au>,
451}
452
453impl IndependentFormattingContextLayoutResultAndInputs {
454    #[inline]
455    fn applicable_for_inline_size(&self, inline_size: Au) -> bool {
456        self.containing_block_for_children_size.inline_size == inline_size
457    }
458
459    #[inline]
460    fn applicable_for_block_size(
461        &self,
462        maybe_quirky_block_size: SizeConstraint,
463        has_quirky_block_size: HasQuirkyBlockSize,
464    ) -> bool {
465        !self.result.depends_on_block_constraints ||
466            (self
467                .containing_block_for_children_size
468                .maybe_quirky_block_size ==
469                maybe_quirky_block_size &&
470                self.containing_block_for_children_size
471                    .has_quirky_block_size ==
472                    has_quirky_block_size)
473    }
474}
475
476#[derive(Clone, MallocSizeOf)]
477pub(crate) struct SameFormattingContextBlockLayoutResult {
478    #[conditional_malloc_size_of]
479    pub fragment: Arc<BoxFragment>,
480    original_offset: Point2D<Au, CSSPixel>,
481}
482
483/// A collection of layout inputs and a cached layout result for a SameFormattingContextBlock for
484/// use in [`LayoutBoxBase`].
485#[derive(MallocSizeOf)]
486pub(crate) struct SameFormattingContextBlockLayoutResultAndInputs {
487    pub result: SameFormattingContextBlockLayoutResult,
488    /// The [`ContainingBlockSize`] used when this block was laid out.
489    pub containing_block_size: ContainingBlockSize,
490    /// The containing block's [`WritingMode`]  used when this block was laid out.
491    pub containing_block_writing_mode: WritingMode,
492    /// The containing block's `justify-items` [`AlignFlags`] used when this block was laid out.
493    pub containing_block_justify_items: AlignFlags,
494    /// Whether or not the margin in this block was collapsible with the parent's start margin
495    /// when this block was laid out.
496    collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
497    /// Whether or not block margins were ignored for stretch when this block was laid out.
498    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
499    /// Whether or not this block had an inline parent.
500    has_inline_parent: bool,
501}