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