Skip to main content

layout/fragment_tree/
box_fragment.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::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use app_units::{Au, MAX_AU, MIN_AU};
9use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
10use euclid::Rect;
11use malloc_size_of_derive::MallocSizeOf;
12use once_cell::race::OnceBox;
13use servo_arc::Arc as ServoArc;
14use servo_base::id::{AtomicOptionScrollTreeNodeId, ScrollTreeNodeId};
15use servo_base::print_tree::PrintTree;
16use servo_geometry::f32_rect_to_au_rect;
17use style::Zero;
18use style::computed_values::border_collapse::T as BorderCollapse;
19use style::computed_values::overflow_x::T as ComputedOverflow;
20use style::logical_geometry::WritingMode;
21use style::properties::ComputedValues;
22
23use super::{BaseFragment, BaseFragmentInfo, CollapsedBlockMargins, Fragment, FragmentFlags};
24use crate::SharedStyle;
25use crate::display_list::{ClipId, ToWebRender};
26use crate::formatting_contexts::Baselines;
27use crate::fragment_tree::{CumulativeContentRectCalculation, FragmentChildren};
28use crate::geom::{
29    AuOrAuto, LogicalSides, LogicalVec2, PhysicalPoint, PhysicalRect, PhysicalSides,
30    SyncPhysicalRectAu,
31};
32use crate::style_ext::ComputedValuesExt;
33use crate::table::SpecificTableGridInfo;
34use crate::taffy::SpecificTaffyGridInfo;
35
36/// Describes how a [`BoxFragment`] paints its background.
37#[derive(Clone, MallocSizeOf)]
38pub(crate) enum BackgroundMode {
39    /// Draw the normal [`BoxFragment`] background as well as the extra backgrounds
40    /// based on the style and positioning rectangles in this data structure.
41    Extra(Vec<ExtraBackground>),
42    /// Do not draw a background for this Fragment. This is used for elements like
43    /// table tracks and table track groups, which rely on cells to paint their
44    /// backgrounds.
45    None,
46    /// Draw the background normally, getting information from the Fragment style.
47    Normal,
48}
49
50#[derive(Clone, MallocSizeOf)]
51pub(crate) struct ExtraBackground {
52    pub style: SharedStyle,
53    pub rect: PhysicalRect<Au>,
54}
55
56#[derive(Clone, Debug, MallocSizeOf)]
57pub(crate) enum SpecificLayoutInfo {
58    Grid(Box<SpecificTaffyGridInfo>),
59    TableCellWithCollapsedBorders,
60    TableGridWithCollapsedBorders(Box<SpecificTableGridInfo>),
61    TableWrapper,
62}
63
64#[derive(Clone, MallocSizeOf)]
65pub(crate) struct BlockLevelLayoutInfo {
66    /// When the `clear` property is not set to `none`, it may introduce clearance.
67    /// Clearance is some extra spacing that is added above the top margin,
68    /// so that the element doesn't overlap earlier floats in the same BFC.
69    /// The presence of clearance prevents the top margin from collapsing with
70    /// earlier margins or with the bottom margin of the parent block.
71    /// <https://drafts.csswg.org/css2/#clearance>
72    pub clearance: Option<Au>,
73
74    pub block_margins_collapsed_with_children: CollapsedBlockMargins,
75}
76
77#[derive(Clone, Default, MallocSizeOf)]
78pub(crate) struct BoxFragmentRareData {
79    /// The resolved box insets if this box is `position: sticky`. These are calculated
80    /// during `StackingContextTree` construction because they rely on the size of the
81    /// scroll container.
82    pub(crate) resolved_sticky_insets: Option<Box<PhysicalSides<AuOrAuto>>>,
83
84    /// Information that is specific to a layout system (e.g., grid, table, etc.).
85    pub specific_layout_info: Option<SpecificLayoutInfo>,
86
87    /// If the associated [`BoxFragment`] establishes a clip via CSS this holds the
88    /// [`ClipId`] for the generated clip set during stacking context tree construction.
89    pub generated_clip_id: Option<ClipId>,
90
91    /// If the associated [`BoxFragment`] establishes a spatial node via CSS this holds the
92    /// [`ScrollTreeNodeId`] for the generated node set during stacking context tree construction.
93    pub generated_scroll_tree_node_id: Option<ScrollTreeNodeId>,
94}
95
96impl BoxFragmentRareData {
97    /// Create a new rare data based on information given to the fragment. Ideally, We should
98    /// avoid creating rare data as much as possible to reduce the memory cost.
99    fn new(specific_layout_info: Option<SpecificLayoutInfo>) -> OnceBox<AtomicRefCell<Self>> {
100        specific_layout_info
101            .map(|info| {
102                OnceBox::with_value(Box::new(AtomicRefCell::new(BoxFragmentRareData {
103                    resolved_sticky_insets: None,
104                    specific_layout_info: Some(info),
105                    generated_clip_id: None,
106                    generated_scroll_tree_node_id: None,
107                })))
108            })
109            .unwrap_or_default()
110    }
111}
112
113#[derive(MallocSizeOf)]
114pub(crate) struct BoxFragment {
115    pub base: BaseFragment,
116
117    /// The style for this [`BoxFragment`].
118    pub style: SharedStyle,
119
120    pub children: Vec<Fragment>,
121
122    /// The cumulative content rect of this [`BoxFragment`]'s parent in coordinates
123    /// relative to the initial containing block, but not taking into account any
124    /// transforms.
125    pub cumulative_parent_content_rect: SyncPhysicalRectAu,
126
127    pub padding: PhysicalSides<Au>,
128    pub border: PhysicalSides<Au>,
129    pub margin: PhysicalSides<Au>,
130
131    /// When this [`BoxFragment`] is for content that has a baseline, this tracks
132    /// the first and last baselines of that content. This is used to propagate baselines
133    /// to things such as tables and inline formatting contexts.
134    baselines: Baselines,
135
136    /// The scrollable overflow of this box fragment in the same coordiante system as
137    /// [`Self::content_rect`] ie a rectangle within the parent fragment's content
138    /// rectangle. This does not take into account any transforms this fragment applies.
139    /// This is handled when calling [`Self::scrollable_overflow_for_parent`].
140    scrollable_overflow: SyncPhysicalRectAu,
141    scrollable_overflow_is_up_to_date: AtomicBool,
142
143    pub background_mode: BackgroundMode,
144
145    /// Rare data that not all kinds of [`BoxFragment`] would have.
146    pub rare_data: OnceBox<AtomicRefCell<BoxFragmentRareData>>,
147
148    /// Additional information for block-level boxes.
149    pub block_level_layout_info: Option<Box<BlockLevelLayoutInfo>>,
150
151    /// The containing spatial tree node of this [`BoxFragment`]. This is assigned during
152    /// `StackingContextTree` construction, so isn't available before that time. This is
153    /// used to for determining final viewport size and position of this node and will
154    /// also be used in the future for hit testing.
155    pub spatial_tree_node: AtomicOptionScrollTreeNodeId,
156}
157
158impl BoxFragment {
159    #[expect(clippy::too_many_arguments)]
160    pub(crate) fn new(
161        base_fragment_info: BaseFragmentInfo,
162        style: ServoArc<ComputedValues>,
163        children: FragmentChildren,
164        content_rect: PhysicalRect<Au>,
165        padding: PhysicalSides<Au>,
166        border: PhysicalSides<Au>,
167        margin: PhysicalSides<Au>,
168        specific_layout_info: Option<SpecificLayoutInfo>,
169    ) -> Self {
170        let rare_data = BoxFragmentRareData::new(specific_layout_info);
171        let children = children.into_physical_fragments(
172            style.writing_mode,
173            LogicalVec2::from_physical_size(&content_rect.size, style.writing_mode),
174        );
175
176        Self {
177            base: BaseFragment::new(base_fragment_info, content_rect),
178            style: style.into(),
179            children,
180            cumulative_parent_content_rect: Default::default(),
181            padding,
182            border,
183            margin,
184            baselines: Baselines::default(),
185            scrollable_overflow: Default::default(),
186            scrollable_overflow_is_up_to_date: AtomicBool::new(false),
187            background_mode: BackgroundMode::Normal,
188            rare_data,
189            block_level_layout_info: None,
190            spatial_tree_node: Default::default(),
191        }
192    }
193
194    pub(crate) fn with_baselines(mut self, baselines: Baselines) -> Self {
195        self.baselines = baselines;
196        self
197    }
198
199    pub(crate) fn style<'a>(&'a self) -> AtomicRef<'a, ServoArc<ComputedValues>> {
200        self.style.borrow()
201    }
202
203    pub(crate) fn with_style(self: &Arc<Self>) -> BoxFragmentWithStyle<'_> {
204        BoxFragmentWithStyle {
205            box_fragment: self,
206            style: self.style(),
207        }
208    }
209
210    /// Get the baselines for this [`BoxFragment`] if they are compatible with the given [`WritingMode`].
211    /// If they are not compatible, [`Baselines::default()`] is returned.
212    pub(crate) fn baselines(&self, writing_mode: WritingMode) -> Baselines {
213        let style = self.style();
214        let mut baselines = if writing_mode.is_horizontal() == style.writing_mode.is_horizontal() {
215            self.baselines
216        } else {
217            // If the writing mode of the container requesting baselines is not
218            // compatible, ensure that the baselines established by this fragment are
219            // not used.
220            Baselines::default()
221        };
222
223        // From the https://drafts.csswg.org/css-align-3/#baseline-export section on "block containers":
224        // > However, for legacy reasons if its baseline-source is auto (the initial
225        // > value) a block-level or inline-level block container that is a scroll container
226        // > always has a last baseline set, whose baselines all correspond to its block-end
227        // > margin edge.
228        //
229        // This applies even if there is no baseline set, so we unconditionally set the value here
230        // and ignore anything that is set via [`Self::with_baselines`].
231        if style.establishes_scroll_container(self.base.flags) {
232            let content_rect_size =
233                LogicalVec2::from_physical_size(&self.content_rect().size, writing_mode);
234            let padding = LogicalSides::from_physical(&self.padding, writing_mode);
235            let border = LogicalSides::from_physical(&self.border, writing_mode);
236            let margin = LogicalSides::from_physical(&self.margin, writing_mode);
237            baselines.last = Some(
238                content_rect_size.block + padding.block_end + border.block_end + margin.block_end,
239            )
240        }
241        baselines
242    }
243
244    pub(crate) fn add_extra_background(&mut self, extra_background: ExtraBackground) {
245        match self.background_mode {
246            BackgroundMode::Extra(ref mut backgrounds) => backgrounds.push(extra_background),
247            _ => self.background_mode = BackgroundMode::Extra(vec![extra_background]),
248        }
249    }
250
251    pub(crate) fn set_does_not_paint_background(&mut self) {
252        self.background_mode = BackgroundMode::None;
253    }
254
255    pub(crate) fn ensure_rare_data(&self) -> AtomicRefMut<'_, BoxFragmentRareData> {
256        self.rare_data.get_or_init(Default::default).borrow_mut()
257    }
258
259    pub(crate) fn specific_layout_info(&self) -> Option<AtomicRef<'_, SpecificLayoutInfo>> {
260        let rare_data = self.rare_data.get()?.borrow();
261
262        AtomicRef::filter_map(rare_data, |rare_data| {
263            rare_data.specific_layout_info.as_ref()
264        })
265    }
266
267    pub(crate) fn clear_stacking_context_tree_traversal_data(&self) {
268        if let Some(rare_data) = self.rare_data.get() {
269            let mut rare_data = rare_data.borrow_mut();
270            rare_data.generated_clip_id = None;
271            rare_data.generated_scroll_tree_node_id = None;
272            rare_data.resolved_sticky_insets = None;
273        }
274    }
275
276    pub(crate) fn resolved_sticky_insets(
277        &self,
278    ) -> Option<AtomicRef<'_, Box<PhysicalSides<AuOrAuto>>>> {
279        let rare_data = self.rare_data.get()?.borrow();
280
281        AtomicRef::filter_map(rare_data, |rare_data| {
282            rare_data.resolved_sticky_insets.as_ref()
283        })
284    }
285
286    pub(crate) fn set_resolved_sticky_insets(&self, sticky_insets: PhysicalSides<AuOrAuto>) {
287        self.ensure_rare_data().resolved_sticky_insets = Some(sticky_insets.into());
288    }
289
290    pub(crate) fn generated_clip_id(&self) -> Option<ClipId> {
291        self.rare_data.get()?.borrow().generated_clip_id
292    }
293
294    pub(crate) fn set_generated_clip_id(&self, generated_clip_id: ClipId) {
295        self.ensure_rare_data().generated_clip_id = Some(generated_clip_id);
296    }
297
298    pub(crate) fn generated_scroll_tree_node_id(&self) -> Option<ScrollTreeNodeId> {
299        self.rare_data.get()?.borrow().generated_scroll_tree_node_id
300    }
301
302    pub(crate) fn set_generated_scroll_tree_node_id(
303        &self,
304        generated_scroll_tree_node_id: ScrollTreeNodeId,
305    ) {
306        self.ensure_rare_data().generated_scroll_tree_node_id = Some(generated_scroll_tree_node_id);
307    }
308
309    pub(crate) fn with_block_level_layout_info(
310        mut self,
311        block_margins_collapsed_with_children: CollapsedBlockMargins,
312        clearance: Option<Au>,
313    ) -> Self {
314        self.block_level_layout_info = Some(Box::new(BlockLevelLayoutInfo {
315            block_margins_collapsed_with_children,
316            clearance,
317        }));
318        self
319    }
320
321    /// Clear the scrollable overflow on this [`BoxFragment`]. This is called
322    /// during damage propagation when a fragment is preserved, itself or one of its
323    /// descendants has scrollable overflow damage.
324    pub(crate) fn clear_scrollable_overflow(&self) {
325        self.scrollable_overflow_is_up_to_date
326            .store(false, Ordering::Release);
327    }
328
329    #[inline]
330    pub(crate) fn set_cumulative_content_rect(&self, content_rect: &PhysicalRect<Au>) {
331        self.cumulative_parent_content_rect.set(*content_rect);
332    }
333
334    pub(crate) fn offset_by_cumulative_content_offset(
335        &self,
336        rect: &PhysicalRect<Au>,
337        cumulative_content_rect_calculation: CumulativeContentRectCalculation<'_>,
338    ) -> PhysicalRect<Au> {
339        cumulative_content_rect_calculation.ensure();
340        rect.translate(self.cumulative_parent_content_rect.origin().to_vector())
341    }
342
343    pub(crate) fn cumulative_content_box_rect(
344        &self,
345        cumulative_content_rect_calculation: CumulativeContentRectCalculation<'_>,
346    ) -> PhysicalRect<Au> {
347        self.offset_by_cumulative_content_offset(
348            &self.base.rect(),
349            cumulative_content_rect_calculation,
350        )
351    }
352
353    pub(crate) fn cumulative_padding_box_rect(
354        &self,
355        cumulative_content_rect_calculation: CumulativeContentRectCalculation<'_>,
356    ) -> PhysicalRect<Au> {
357        self.offset_by_cumulative_content_offset(
358            &self.padding_rect(),
359            cumulative_content_rect_calculation,
360        )
361    }
362
363    pub(crate) fn cumulative_border_box_rect(
364        &self,
365        cumulative_content_rect_calculation: CumulativeContentRectCalculation<'_>,
366    ) -> PhysicalRect<Au> {
367        self.offset_by_cumulative_content_offset(
368            &self.border_rect(),
369            cumulative_content_rect_calculation,
370        )
371    }
372
373    pub(crate) fn content_rect(&self) -> PhysicalRect<Au> {
374        self.base.rect()
375    }
376
377    pub(crate) fn padding_rect(&self) -> PhysicalRect<Au> {
378        self.content_rect().outer_rect(self.padding)
379    }
380
381    pub(crate) fn border_rect(&self) -> PhysicalRect<Au> {
382        self.padding_rect().outer_rect(self.border)
383    }
384
385    pub(crate) fn margin_rect(&self) -> PhysicalRect<Au> {
386        self.border_rect().outer_rect(self.margin)
387    }
388
389    pub(crate) fn padding_border_margin(&self) -> PhysicalSides<Au> {
390        self.margin + self.border + self.padding
391    }
392
393    pub(crate) fn is_root_element(&self) -> bool {
394        self.base.flags.intersects(FragmentFlags::IS_ROOT_ELEMENT)
395    }
396
397    pub(crate) fn is_body_element_of_html_element_root(&self) -> bool {
398        self.base
399            .flags
400            .intersects(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT)
401    }
402
403    pub(crate) fn print(self: &Arc<Self>, tree: &mut PrintTree) {
404        let with_style = self.with_style();
405        tree.new_level(format!(
406            "Box\
407                \nbase={:?}\
408                \ncontent={:?}\
409                \npadding rect={:?}\
410                \nborder rect={:?}\
411                \nmargin={:?}\
412                \nscrollable_overflow={:?}\
413                \nbaselines={:?}\
414                \noverflow={:?}",
415            self.base,
416            self.content_rect(),
417            self.padding_rect(),
418            self.border_rect(),
419            self.margin,
420            with_style.scrollable_overflow(),
421            self.baselines,
422            with_style.style().effective_overflow(self.base.flags),
423        ));
424
425        for child in &self.children {
426            child.print(tree);
427        }
428        tree.end_level();
429    }
430
431    /// Whether or this is a flex or grid item.
432    pub(crate) fn is_flex_or_grid_item(&self) -> bool {
433        self.base
434            .flags
435            .contains(FragmentFlags::IS_FLEX_OR_GRID_ITEM)
436    }
437
438    /// Whether or this box is for replaced content.
439    pub(crate) fn is_replaced(&self) -> bool {
440        self.base.flags.contains(FragmentFlags::IS_REPLACED)
441    }
442
443    /// Whether this is a table wrapper box.
444    /// <https://www.w3.org/TR/css-tables-3/#table-wrapper-box>
445    pub(crate) fn is_table_wrapper(&self) -> bool {
446        matches!(
447            self.specific_layout_info().as_deref(),
448            Some(SpecificLayoutInfo::TableWrapper)
449        )
450    }
451
452    /// Whether or not this is the [`BoxFragment`] for a table grid with collapsed borders.
453    pub(crate) fn is_table_grid_with_collapsed_borders(&self) -> bool {
454        matches!(
455            self.specific_layout_info().as_deref(),
456            Some(SpecificLayoutInfo::TableGridWithCollapsedBorders(_))
457        )
458    }
459
460    pub(crate) fn spatial_tree_node(&self) -> Option<ScrollTreeNodeId> {
461        self.spatial_tree_node.get()
462    }
463
464    /// Compute a physical containing block rectangle relative to the content box of this
465    /// fragment for absolutely positioned boxes for which this fragment establishes a
466    /// containing block.
467    ///
468    /// - For grid containers: the grid area rectangle.
469    /// - For everything else: the padding box of the box that establishes the containing block.
470    pub(crate) fn containing_block_rect_for_absolute(
471        &self,
472        item_style: &ComputedValues,
473    ) -> PhysicalRect<Au> {
474        self.grid_info()
475            .map(|grid_info| {
476                // Resolve the hoisted node's grid area from its own grid position styles
477                // into a rectangle in `Au` units relative to the container's content box.
478                grid_info.resolve_grid_area(self, item_style)
479            })
480            .unwrap_or_else(|| {
481                // Get the padding box of this fragment relative to the content box.
482                let mut padding_rect = self.padding_rect();
483                padding_rect.origin -= self.content_rect().origin.to_vector();
484                padding_rect
485            })
486    }
487
488    pub(crate) fn grid_info(&self) -> Option<AtomicRef<'_, SpecificTaffyGridInfo>> {
489        let rare_data = self.rare_data.get().map(|ref_cell| ref_cell.borrow());
490        rare_data.and_then(|rare_data| {
491            AtomicRef::filter_map(rare_data, |rare_data| {
492                match rare_data.specific_layout_info.as_ref() {
493                    Some(SpecificLayoutInfo::Grid(grid_info)) => Some(&**grid_info),
494                    _ => None,
495                }
496            })
497        })
498    }
499}
500
501/// Contains `&Arc<BoxFragment>` and dereferences to it so it can mostly
502/// be used in the same ways, except the `.style()` method is shadowed to use an existing
503/// `atomic_refcell::AtomicRef` that lives as long as `BoxFragmentWithStyle`.
504///
505/// Compared to calling `BoxFragment::style()` repeatedly, this reduce the number of atomic
506/// increments and decrements on `ArcRefCell`’s borrow counter.
507pub(crate) struct BoxFragmentWithStyle<'a> {
508    pub(crate) box_fragment: &'a Arc<BoxFragment>,
509    pub(crate) style: AtomicRef<'a, ServoArc<ComputedValues>>,
510}
511
512impl std::ops::Deref for BoxFragmentWithStyle<'_> {
513    type Target = Arc<BoxFragment>;
514
515    fn deref(&self) -> &Self::Target {
516        self.box_fragment
517    }
518}
519
520impl<'a> BoxFragmentWithStyle<'a> {
521    pub(crate) fn style(&self) -> &ServoArc<ComputedValues> {
522        &self.style
523    }
524
525    /// Return the clipped scrollable overflow based on its scroll origin, determined by
526    /// overflow direction. Return [`None`] if the scrollable overflow from child is wholly
527    /// unreachable. For an element, the clip rect is the padding rect and for viewport,
528    /// it is the initial containing block.
529    pub(crate) fn clip_wholly_unreachable_scrollable_overflow(
530        &self,
531        scrollable_overflow_from_child: PhysicalRect<Au>,
532        clipping_rect: PhysicalRect<Au>,
533    ) -> PhysicalRect<Au> {
534        // From <https://drafts.csswg.org/css-overflow/#unreachable-scrollable-overflow-region>:
535        // > Unless otherwise adjusted (e.g. by content alignment [css-align-3]), the area
536        // > beyond the scroll origin in either axis is considered the unreachable scrollable
537        // > overflow region: content rendered here is not accessible to the reader, see § 2.2
538        // > Scrollable Overflow. A scroll container is said to be scrolled to its scroll
539        // > origin when its scroll origin coincides with the corresponding corner of its
540        // > scrollport. This scroll position, the scroll origin position, usually, but not
541        // > always, coincides with the initial scroll position.
542        let scrolling_direction = self.style().overflow_direction();
543        let mut clipping_box = clipping_rect.to_box2d();
544        if scrolling_direction.rightward {
545            clipping_box.max.x = MAX_AU;
546        } else {
547            clipping_box.min.x = MIN_AU;
548        }
549
550        if scrolling_direction.downward {
551            clipping_box.max.y = MAX_AU;
552        } else {
553            clipping_box.min.y = MIN_AU;
554        }
555
556        let scrollable_overflow_box = scrollable_overflow_from_child
557            .to_box2d()
558            .intersection_unchecked(&clipping_box);
559
560        match scrollable_overflow_box.is_negative() {
561            false => scrollable_overflow_box.to_rect(),
562            true => Rect::zero(),
563        }
564    }
565
566    pub(crate) fn scrollable_overflow_for_parent(&self) -> PhysicalRect<Au> {
567        let style = self.style();
568        let mut overflow = self.border_rect();
569        if !style.establishes_scroll_container(self.base.flags) {
570            // https://www.w3.org/TR/css-overflow-3/#scrollable
571            // Only include the scrollable overflow of a child box if it has overflow: visible.
572            let scrollable_overflow = self.scrollable_overflow();
573            let bottom_right = PhysicalPoint::new(
574                overflow.max_x().max(scrollable_overflow.max_x()),
575                overflow.max_y().max(scrollable_overflow.max_y()),
576            );
577
578            let overflow_style = style.effective_overflow(self.base.flags);
579            if overflow_style.y == ComputedOverflow::Visible {
580                overflow.origin.y = overflow.origin.y.min(scrollable_overflow.origin.y);
581                overflow.size.height = bottom_right.y - overflow.origin.y;
582            }
583
584            if overflow_style.x == ComputedOverflow::Visible {
585                overflow.origin.x = overflow.origin.x.min(scrollable_overflow.origin.x);
586                overflow.size.width = bottom_right.x - overflow.origin.x;
587            }
588        }
589
590        if !style.has_effective_transform_or_perspective(self.base.flags) {
591            return overflow;
592        }
593
594        // <https://drafts.csswg.org/css-overflow-3/#scrollable-overflow-region>
595        // > ...accounting for transforms by projecting each box onto the plane of
596        // > the element that establishes its 3D rendering context. [CSS3-TRANSFORMS]
597        // Both boxes and its scrollable overflow (if it is included) should be transformed accordingly.
598        //
599        // TODO(stevennovaryo): We are supposed to handle perspective transform and 3d
600        // contexts, but it is yet to happen.
601        self.calculate_transform_matrix(&self.border_rect())
602            .and_then(|transform| {
603                transform.outer_transformed_rect(&overflow.to_webrender().to_rect())
604            })
605            .map(|transformed_rect| f32_rect_to_au_rect(transformed_rect).cast_unit())
606            .unwrap_or(overflow)
607    }
608
609    /// Get the scrollable overflow for this [`BoxFragment`] relative to its containing
610    /// block, recalculating scrollable overflow when necessary, for instance after a
611    /// style change.
612    pub(crate) fn scrollable_overflow(&self) -> PhysicalRect<Au> {
613        if self
614            .scrollable_overflow_is_up_to_date
615            .load(Ordering::Acquire)
616        {
617            self.scrollable_overflow.get()
618        } else {
619            let rect = self.calculate_scrollable_overflow();
620            self.scrollable_overflow.set(rect);
621            self.scrollable_overflow_is_up_to_date
622                .store(true, Ordering::Release);
623            rect
624        }
625    }
626    /// This is an implementation of:
627    /// - <https://drafts.csswg.org/css-overflow-3/#scrollable>.
628    /// - <https://drafts.csswg.org/cssom-view/#scrolling-area>
629    fn calculate_scrollable_overflow(&self) -> PhysicalRect<Au> {
630        // Fragments with `IS_COLLAPSED` (currently only table cells that are part of
631        // table tracks with `visibility: collapse`) should not contribute to scrollable
632        // overflow. This behavior matches Chrome, but not Firefox.
633        // See https://github.com/w3c/csswg-drafts/issues/12689
634        if self.base.flags.contains(FragmentFlags::IS_COLLAPSED) {
635            return Rect::zero();
636        }
637
638        let physical_padding_rect = self.padding_rect();
639        let content_origin = self.base.rect().origin.to_vector();
640
641        // > The scrollable overflow area is the union of:
642        // > * The scroll container’s own padding box.
643        // > * All line boxes directly contained by the scroll container.
644        // > * The border boxes of all boxes for which it is the containing block and
645        // >   whose border boxes are positioned not wholly in the unreachable
646        // >   scrollable overflow region, accounting for transforms by projecting
647        // >   each box onto the plane of the element that establishes its 3D
648        // >   rendering context.
649        // > * The margin areas of grid item and flex item boxes for which the box
650        // >   establishes a containing block.
651        // > * The scrollable overflow areas of all of the above boxes (including zero-area
652        // >   boxes and accounting for transforms as described above), provided they
653        // >   themselves have overflow: visible (i.e. do not themselves trap the overflow)
654        // >   and that scrollable overflow is not already clipped (e.g. by the clip property
655        // >   or the contain property).
656        // > * Additional padding added to the scrollable overflow rectangle as necessary
657        //     to enable scroll positions that satisfy the requirements of both place-content:
658        //     start and place-content: end alignment.
659        //
660        // TODO(mrobinson): Below we are handling the border box and the scrollable
661        // overflow together, but from the specification it seems that if the border
662        // box of an item is in the "wholly unreachable scrollable overflow region", but
663        // its scrollable overflow is not, it should also be excluded.
664        let mut scrollable_overflow =
665            self.children
666                .iter()
667                .fold(physical_padding_rect, |acc, child| {
668                    let scrollable_overflow_from_child = child
669                        .scrollable_overflow_for_parent()
670                        .translate(content_origin);
671
672                    // Note that this doesn't just exclude the wholly unreachable
673                    // scrollable overflow area from the rectangle, but also clips it.
674                    // This makes the resulting value more like the "scroll area" rather
675                    // than the "scrollable overflow."
676                    let scrollable_overflow_from_child = self
677                        .clip_wholly_unreachable_scrollable_overflow(
678                            scrollable_overflow_from_child,
679                            physical_padding_rect,
680                        );
681
682                    acc.union(&scrollable_overflow_from_child)
683                });
684
685        // From <https://drafts.csswg.org/css-overflow-3/#scrollable>:
686        // > Additional padding added to the scrollable overflow rectangle as necessary to
687        // > enable scroll positions that satisfy the requirements of both place-content:
688        // > start and place-content: end alignment.
689        //
690        // Whether we should include additional padding to the scrollable overflow to satisfy
691        // the requirements of `place-content: start` and `place-content: end` for boxes that
692        // establish scroll containers. Note: This padding is different from the CSS concept
693        // of padding. See <https://github.com/w3c/csswg-drafts/issues/129>.
694        //
695        // TODO: For input elements, we also disable the padding in the inline direction, as we
696        // do not have a way to scroll the textual input element in inline direction yet.
697        let should_include_additional_padding =
698            self.style().establishes_scroll_container(self.base.flags) &&
699                !self.base.flags.intersects(FragmentFlags::IS_INPUT_ELEMENT);
700
701        if should_include_additional_padding {
702            scrollable_overflow = self
703                .children
704                .iter()
705                .fold(scrollable_overflow, |acc, child| {
706                    let Some(padding_contribution) =
707                        child.scrollable_overflow_padding_contribution_for_parent()
708                    else {
709                        return acc;
710                    };
711
712                    let padding_contribution = padding_contribution
713                        .translate(content_origin)
714                        .outer_rect(self.padding);
715
716                    // Applying padding could also cause the rectangle to overflow to
717                    // the wholly unreachable scrollable overflow, clipping the overflow
718                    // here prevents this.
719                    let padding_contribution = self.clip_wholly_unreachable_scrollable_overflow(
720                        padding_contribution,
721                        physical_padding_rect,
722                    );
723
724                    acc.union(&padding_contribution)
725                });
726        }
727        scrollable_overflow
728    }
729
730    /// Whether this is a non-replaced inline-level box whose inner display type is `flow`.
731    /// <https://drafts.csswg.org/css-display-3/#inline-box>
732    pub(crate) fn is_inline_box(&self) -> bool {
733        self.style().is_inline_box(self.base.flags)
734    }
735
736    /// Whether this is an atomic inline-level box.
737    /// <https://drafts.csswg.org/css-display-3/#atomic-inline>
738    pub(crate) fn is_atomic_inline_level(&self) -> bool {
739        self.style().is_atomic_inline_level(self.base.flags)
740    }
741
742    pub(crate) fn has_collapsed_borders(&self) -> bool {
743        match self.specific_layout_info().as_deref() {
744            Some(SpecificLayoutInfo::TableCellWithCollapsedBorders) => true,
745            Some(SpecificLayoutInfo::TableGridWithCollapsedBorders(_)) => true,
746            Some(SpecificLayoutInfo::TableWrapper) => {
747                self.style().get_inherited_table().border_collapse == BorderCollapse::Collapse
748            },
749            _ => false,
750        }
751    }
752
753    /// Whether or not this [`BoxFragment`] has outlines.
754    pub(crate) fn has_outline(&self) -> bool {
755        let style = self.style();
756        let outline = style.get_outline();
757        !outline.outline_style.none_or_hidden() && !outline.outline_width.0.is_zero()
758    }
759}