Skip to main content

layout/display_list/
stacking_context.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::Cell;
6use std::rc::Rc;
7use std::sync::Arc;
8
9use app_units::Au;
10use embedder_traits::ViewportDetails;
11use euclid::{Point2D, Rect, SideOffsets2D, Size2D};
12use malloc_size_of_derive::MallocSizeOf;
13use paint_api::display_list::{
14    AxesScrollSensitivity, PaintDisplayListInfo, ReferenceFrameNodeInfo, ScrollType,
15    ScrollableNodeInfo, SpatialTreeNodeInfo, StickyNodeInfo, TouchAction,
16};
17use servo_base::id::ScrollTreeNodeId;
18use servo_base::print_tree::PrintTree;
19use servo_config::opts::{DiagnosticsLogging, DiagnosticsLoggingOption};
20use servo_geometry::MaxRect;
21use style::Zero;
22use style::color::AbsoluteColor;
23use style::computed_values::overflow_x::T as ComputedOverflow;
24use style::computed_values::position::T as ComputedPosition;
25use style::computed_values::text_decoration_style::T as TextDecorationStyle;
26use style::computed_values::text_decoration_thickness::T as TextDecorationThickness;
27use style::properties::ComputedValues;
28use style::values::computed::angle::Angle;
29use style::values::computed::{ClipRectOrAuto, Length, TextDecorationLine};
30use style::values::generics::box_::{OverflowClipMarginBox, Perspective};
31use style::values::generics::transform::{
32    self, GenericRotate, GenericScale, GenericTranslate, get_normalized_vector_and_angle,
33};
34use style_traits::CSSPixel;
35use webrender_api::units::{LayoutPoint, LayoutRect, LayoutTransform, LayoutVector2D};
36use webrender_api::{self as wr, BorderRadius};
37use wr::StickyOffsetBounds;
38use wr::units::{LayoutPixel, LayoutSize};
39
40use super::ClipId;
41use super::clip::StackingContextTreeClipStore;
42use crate::display_list::conversions::ToWebRender;
43use crate::display_list::{
44    BuilderForBoxFragment, ContainerTimingRootChain, ContainerTimingRoots, offset_radii,
45};
46use crate::fragment_tree::{
47    BoxFragment, BoxFragmentWithStyle, ContainingBlockManager, CumulativeContentRectCalculation,
48    Fragment, FragmentFlags, FragmentTree, PositioningFragment,
49};
50use crate::geom::{
51    AuOrAuto, LengthPercentageOrAuto, PhysicalPoint, PhysicalRect, PhysicalSides, PhysicalSize,
52    PhysicalVec,
53};
54use crate::style_ext::{ComputedValuesExt, TransformExt};
55
56#[derive(Clone)]
57pub(crate) struct ContainingBlock {
58    /// The SpatialId of the spatial node that contains the children
59    /// of this containing block.
60    scroll_node_id: ScrollTreeNodeId,
61
62    /// The size of the parent scroll frame of this containing block, used for resolving
63    /// sticky margins. If this is None, then this is a direct descendant of a reference
64    /// frame and sticky positioning isn't taken into account.
65    scroll_frame_size: Option<LayoutSize>,
66
67    /// The [`ClipId`] to use for the children of this containing block.
68    clip_id: ClipId,
69
70    /// The physical rect of this containing block.
71    rect: PhysicalRect<Au>,
72
73    /// Normally containing block offsets and display list items are positioned relative
74    /// to their parent reference frame, but cumulative containing block boundaries on
75    /// fragments need to disregard reference frames entirely. This value tracks the
76    /// accumulated offset from the origin of the parent reference frame of this
77    /// containing block.
78    accumulated_reference_frame_offset: PhysicalVec<Au>,
79
80    /// Whether current containing block established a scroll frame.
81    established_scroll_frame: bool,
82}
83
84impl ContainingBlock {
85    pub(crate) fn new(
86        rect: PhysicalRect<Au>,
87        scroll_node_id: ScrollTreeNodeId,
88        scroll_frame_size: Option<LayoutSize>,
89        clip_id: ClipId,
90        accumulated_reference_frame_offset: PhysicalVec<Au>,
91        established_scroll_frame: bool,
92    ) -> Self {
93        ContainingBlock {
94            scroll_node_id,
95            scroll_frame_size,
96            clip_id,
97            rect,
98            accumulated_reference_frame_offset,
99            established_scroll_frame,
100        }
101    }
102
103    pub(crate) fn new_replacing_rect(&self, rect: &PhysicalRect<Au>) -> Self {
104        ContainingBlock {
105            rect: *rect,
106            ..*self
107        }
108    }
109}
110
111pub(crate) type ContainingBlockInfo<'a> = ContainingBlockManager<'a, ContainingBlock>;
112
113/// Information that is passed down during stacking context tree construction
114/// that does not apply per-containing block, but per-box.
115#[derive(Clone, Default)]
116pub(crate) struct StackingContextParentInfo {
117    /// The inherited [`FragmentTextDecoration`]s passed down by the parent.
118    text_decorations: Rc<Vec<FragmentTextDecoration>>,
119    /// Whether or not the parent participates in a 3D rendering context. This is used
120    /// to determine if its children do as well.
121    participates_in_a_3d_rendering_context: bool,
122    /// If the parent establishes a perspective node, this is its [`ScrollTreeNodeId`].
123    perspective_node: Option<ScrollTreeNodeId>,
124    /// The [`ContainerTimingRoots`] established by the parent box.
125    container_timing_roots: ContainerTimingRoots,
126}
127
128impl StackingContextParentInfo {
129    fn without_text_decorations(&self) -> Self {
130        Self {
131            text_decorations: Default::default(),
132            ..self.clone()
133        }
134    }
135
136    /// Determine the [`StackingContextParentInfo`] to use for a [`BoxFragment`]'s children, given
137    /// the fragment and the id of a perspective spatial node it created, if any.
138    fn for_children(
139        &self,
140        fragment: &BoxFragmentWithStyle,
141        perspective_node: Option<ScrollTreeNodeId>,
142    ) -> Self {
143        let style = fragment.style();
144
145        // Text decorations are not propagated to atomic inline-level descendants.
146        // From https://drafts.csswg.org/css2/#lining-striking-props:
147        // > Note that text decorations are not propagated to floating and absolutely
148        // > positioned descendants, nor to the contents of atomic inline-level descendants
149        // > such as inline blocks and inline tables.
150        let inherited_text_decorations = if fragment.is_atomic_inline_level() ||
151            fragment
152                .base
153                .flags
154                .contains(FragmentFlags::IS_OUTSIDE_LIST_ITEM_MARKER)
155        {
156            Default::default()
157        } else {
158            self.text_decorations.clone()
159        };
160
161        let text_decorations = match style.get_text_decoration_line() {
162            &TextDecorationLine::NONE => inherited_text_decorations,
163            line => {
164                let mut new_vector = (*inherited_text_decorations).clone();
165                new_vector.push(FragmentTextDecoration {
166                    line: *line,
167                    color: style.resolve_color(style.get_text_decoration_color()),
168                    style: style.slow_clone_text_decoration_style(),
169                    thickness: style.slow_clone_text_decoration_thickness(),
170                    underline_offset: resolve_underline_offset(style),
171                });
172                Rc::new(new_vector)
173            },
174        };
175
176        let participates_in_a_3d_rendering_context = if fragment.base.is_anonymous() {
177            self.participates_in_a_3d_rendering_context
178        } else {
179            style.establishes_or_extends_3d_rendering_context(fragment.base.flags)
180        };
181
182        // A new perspective node always overrides any perspective nodes from ancestors.
183        // If there is no new perspective node, the ancestor's node may be inherited when
184        // the fragment is anonymous or it extends the 3D rendering context. It *isn't*
185        // inherited when this fragment creates its own transform reference frame because
186        // the perspective gets baked into the spatial node hierarchy.
187        let perspective_node = perspective_node.or_else(|| {
188            self.perspective_node.filter(|_| {
189                fragment.base.is_anonymous() ||
190                    (participates_in_a_3d_rendering_context &&
191                        !style.has_effective_transform(fragment.base.flags))
192            })
193        });
194
195        Self {
196            text_decorations,
197            participates_in_a_3d_rendering_context,
198            perspective_node,
199            container_timing_roots: ContainerTimingRootChain::for_contents_of(
200                &self.container_timing_roots,
201                &fragment.base,
202            ),
203        }
204    }
205}
206
207#[derive(MallocSizeOf)]
208pub(crate) struct StackingContextTree {
209    /// The root [`StackingContext`] of this [`StackingContextTree`].
210    pub root_stacking_context: StackingContext,
211
212    /// The information about the WebRender display list that `Paint`
213    /// consumes. This currently contains the out-of-band hit testing information
214    /// data structure that `Paint` uses to map hit tests to information
215    /// about the item hit.
216    pub paint_info: PaintDisplayListInfo,
217
218    /// All of the clips collected for this [`StackingContextTree`]. These are added
219    /// for things like `overflow`. More clips may be created later during WebRender
220    /// display list construction, but they are never added here.
221    pub clip_store: StackingContextTreeClipStore,
222}
223
224impl StackingContextTree {
225    /// Create a new [DisplayList] given the dimensions of the layout and the WebRender
226    /// pipeline id.
227    pub fn new(
228        fragment_tree: &FragmentTree,
229        viewport_details: ViewportDetails,
230        pipeline_id: wr::PipelineId,
231        first_reflow: bool,
232        debug: &DiagnosticsLogging,
233    ) -> Self {
234        let scrollable_overflow = fragment_tree.scrollable_overflow();
235        let scroll_area = scrollable_overflow.union(&fragment_tree.initial_containing_block);
236        let scroll_area = LayoutSize::from_untyped(Size2D::new(
237            scroll_area.size.width.to_f32_px(),
238            scroll_area.size.height.to_f32_px(),
239        ));
240
241        let viewport_size = viewport_details.layout_size();
242        let paint_info = PaintDisplayListInfo::new(
243            viewport_details,
244            scroll_area,
245            pipeline_id,
246            // This epoch is set when the WebRender display list is built. For now use a dummy value.
247            Default::default(),
248            fragment_tree.viewport_scroll_sensitivity,
249            first_reflow,
250        );
251
252        let root_scroll_node_id = paint_info.root_scroll_node_id;
253        let cb_for_non_fixed_descendants = ContainingBlock::new(
254            fragment_tree.initial_containing_block,
255            root_scroll_node_id,
256            Some(viewport_size),
257            ClipId::INVALID,
258            PhysicalVec::zero(),
259            true,
260        );
261        let cb_for_fixed_descendants = ContainingBlock::new(
262            fragment_tree.initial_containing_block,
263            paint_info.root_reference_frame_id,
264            None,
265            ClipId::INVALID,
266            PhysicalVec::zero(),
267            false,
268        );
269
270        // We need to specify all three containing blocks here, because absolute
271        // descendants of the root cannot share the containing block we specify
272        // for fixed descendants. In this case, they need to have the spatial
273        // id of the root scroll frame, whereas fixed descendants need the
274        // spatial id of the root reference frame so that they do not scroll with
275        // page content.
276        let containing_block_info = ContainingBlockInfo {
277            for_non_absolute_descendants: &cb_for_non_fixed_descendants,
278            for_absolute_descendants: Some(&cb_for_non_fixed_descendants),
279            for_absolute_and_fixed_descendants: &cb_for_fixed_descendants,
280        };
281
282        let mut stacking_context_tree = Self {
283            // This is just a temporary value that will be replaced once we have finished
284            // building the tree.
285            root_stacking_context: StackingContext::root(root_scroll_node_id),
286            paint_info,
287            clip_store: Default::default(),
288        };
289
290        let mut root_stacking_context = StackingContext::root(root_scroll_node_id);
291        if let Some(root_box_fragment) = fragment_tree.root_box_fragment() {
292            root_box_fragment.build_stacking_context_tree(
293                &mut stacking_context_tree,
294                &containing_block_info,
295                &mut root_stacking_context,
296                &StackingContextParentInfo::default(),
297            );
298        }
299
300        root_stacking_context.sort();
301        stacking_context_tree.root_stacking_context = root_stacking_context;
302
303        if debug.is_enabled(DiagnosticsLoggingOption::StackingContextTree) {
304            stacking_context_tree
305                .root_stacking_context
306                .print(&mut PrintTree::new("Stacking Context Tree"));
307        }
308
309        stacking_context_tree
310    }
311
312    fn push_reference_frame(
313        &mut self,
314        origin: LayoutPoint,
315        frame_origin_for_query: LayoutPoint,
316        parent_scroll_node_id: ScrollTreeNodeId,
317        transform_style: wr::TransformStyle,
318        transform: LayoutTransform,
319        kind: wr::ReferenceFrameKind,
320    ) -> ScrollTreeNodeId {
321        self.paint_info.scroll_tree.add_scroll_tree_node(
322            Some(parent_scroll_node_id),
323            SpatialTreeNodeInfo::ReferenceFrame(ReferenceFrameNodeInfo {
324                origin,
325                frame_origin_for_query,
326                transform_style,
327                transform: transform.into(),
328                kind,
329            }),
330        )
331    }
332
333    fn define_scroll_frame(
334        &mut self,
335        parent_scroll_node_id: ScrollTreeNodeId,
336        external_id: wr::ExternalScrollId,
337        content_rect: LayoutRect,
338        clip_rect: LayoutRect,
339        scroll_sensitivity: AxesScrollSensitivity,
340        touch_action: TouchAction,
341    ) -> ScrollTreeNodeId {
342        self.paint_info.scroll_tree.add_scroll_tree_node(
343            Some(parent_scroll_node_id),
344            SpatialTreeNodeInfo::Scroll(ScrollableNodeInfo {
345                external_id,
346                content_rect,
347                clip_rect,
348                scroll_sensitivity,
349                touch_action,
350                offset: LayoutVector2D::zero(),
351                offset_changed: Cell::new(false),
352            }),
353        )
354    }
355
356    fn define_sticky_frame(
357        &mut self,
358        parent_scroll_node_id: ScrollTreeNodeId,
359        frame_rect: LayoutRect,
360        margins: SideOffsets2D<Option<f32>, LayoutPixel>,
361        vertical_offset_bounds: StickyOffsetBounds,
362        horizontal_offset_bounds: StickyOffsetBounds,
363    ) -> ScrollTreeNodeId {
364        self.paint_info.scroll_tree.add_scroll_tree_node(
365            Some(parent_scroll_node_id),
366            SpatialTreeNodeInfo::Sticky(StickyNodeInfo {
367                frame_rect,
368                margins,
369                vertical_offset_bounds,
370                horizontal_offset_bounds,
371            }),
372        )
373    }
374
375    /// Given a [`Fragment`] and a point in the viewport of the page, return the point in
376    /// the [`Fragment`]'s content rectangle in its transformed coordinate system
377    /// (untransformed CSS pixels). Note that the point may be outside the [`Fragment`]'s
378    /// boundaries.
379    ///
380    /// TODO: Currently, this only works for [`BoxFragment`], but we should extend it to
381    /// other types of [`Fragment`]s in the future.
382    pub(crate) fn offset_in_fragment(
383        &self,
384        fragment: &Fragment,
385        point_in_viewport: PhysicalPoint<Au>,
386    ) -> Option<Point2D<Au, CSSPixel>> {
387        let spatial_tree_node = fragment.spatial_tree_node()?;
388        let transform = self
389            .paint_info
390            .scroll_tree
391            .cumulative_root_to_node_transform(spatial_tree_node)?;
392        let transformed_point = transform
393            .project_point2d(point_in_viewport.map(Au::to_f32_px).cast_unit())?
394            .map(Au::from_f32_px)
395            .cast_unit();
396
397        // Find the origin of the fragment relative to its reference frame in the same coordinate system.
398        let fragment = fragment.retrieve_box_fragment()?;
399        let reference_frame_origin = self
400            .paint_info
401            .scroll_tree
402            .reference_frame_offset(spatial_tree_node)
403            .map(Au::from_f32_px);
404        let fragment_origin = fragment
405            .cumulative_content_box_rect(
406                CumulativeContentRectCalculation::AlreadyDoneWithStackingContextTree,
407            )
408            .origin -
409            reference_frame_origin.cast_unit();
410
411        // Use that to find the offset from the fragment origin.
412        Some(transformed_point - fragment_origin)
413    }
414}
415
416/// The text decorations for a Fragment, collecting during [`StackingContextTree`] construction.
417#[derive(Clone, Debug, MallocSizeOf)]
418pub(crate) struct FragmentTextDecoration {
419    pub line: TextDecorationLine,
420    pub color: AbsoluteColor,
421    pub style: TextDecorationStyle,
422    pub thickness: TextDecorationThickness,
423    pub underline_offset: Au,
424}
425
426/// Resolve the `text-underline-offset` against the used font-size of the element
427///
428/// <https://drafts.csswg.org/css-text-decor-4/#underline-offset>:
429pub(crate) fn resolve_underline_offset(style: &ComputedValues) -> Au {
430    style
431        .get_text_underline_offset()
432        .map(|offset| {
433            let font_size = style.get_font().font_size.computed_size.0;
434            offset.resolve(font_size).into()
435        })
436        .auto_is(Au::zero)
437}
438
439#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
440pub(crate) enum StackingContextType {
441    StackingContext,
442    StackingContainer,
443}
444
445#[derive(MallocSizeOf)]
446pub(crate) enum StackingContextFragments {
447    Root,
448    Fragment(#[conditional_malloc_size_of] Arc<BoxFragment>),
449}
450
451#[derive(MallocSizeOf)]
452pub(crate) struct StackingContextReferenceFrameInfo {
453    pub(crate) parent_spatial_node_id: ScrollTreeNodeId,
454    pub(crate) captured_clip_id: ClipId,
455}
456
457/// Either a stacking context or a stacking container, per the definitions in
458/// <https://drafts.csswg.org/css-position-4/#painting-order>.
459///
460/// We use the term “real stacking context” in situations that call for a stacking context
461/// but not a stacking container. Only positioned stacking containers every get a
462/// `StackingContext`. The rest are handled inline during the `PaintTraversal`.
463#[derive(MallocSizeOf)]
464pub struct StackingContext {
465    /// The [`BoxFragment`] that established this stacking context. This is used to paint this
466    /// [`StackingContext`] and traverse its descendants for painting.
467    ///
468    /// This is `None` for the root stacking context.
469    pub(crate) fragment: StackingContextFragments,
470
471    /// The [`StackingContextType`] of this [`StackingContet`], which determines if it
472    /// a stacking context or a stacking container.
473    pub(crate) context_type: StackingContextType,
474
475    /// Child [`StackingContext`]s of this [`StackingContext`].
476    pub(crate) children: Vec<StackingContext>,
477
478    /// The offset of the containing block, used to properly paint child fragments of this
479    /// stacking context or stacking container.
480    pub(crate) containing_block_origin: PhysicalPoint<Au>,
481
482    /// The spatial id of this [`StackingContext`].
483    pub(crate) scroll_tree_node_id: ScrollTreeNodeId,
484
485    /// The clip id of this [`StackingContext`] if it has one.
486    pub(crate) clip_id: ClipId,
487
488    /// The z-index of this [`StackingContext`]. Note that `auto` is represented as 0.
489    pub(crate) z_index: i32,
490
491    /// The text decorations that apply to this [`StackingContext`] propagated via the box tree.
492    #[conditional_malloc_size_of]
493    pub(crate) text_decorations: Rc<Vec<FragmentTextDecoration>>,
494
495    /// The Container Timing roots that enclose this [`StackingContext`] in tree order,
496    /// not including its own root fragment. Stacking contexts are painted out of tree
497    /// order, so these are captured while building the stacking context tree.
498    #[ignore_malloc_size_of = "Small and shared with other stacking contexts"]
499    pub(crate) container_timing_roots: ContainerTimingRoots,
500
501    /// If this [`StackingContext`] also created a WebRender reference frame, this field
502    /// holds information about that reference frame.
503    pub(crate) reference_frame_info: Option<StackingContextReferenceFrameInfo>,
504
505    /// Whether or not this [`StackingContext`] participates in a 3D rendering context.
506    /// See <https://www.w3.org/TR/css-transforms-2/#3d-rendering-contexts>
507    pub(crate) participates_in_a_3d_rendering_context: bool,
508}
509
510impl StackingContext {
511    fn root(scroll_tree_node_id: ScrollTreeNodeId) -> Self {
512        Self {
513            fragment: StackingContextFragments::Root,
514            context_type: StackingContextType::StackingContext,
515            children: Default::default(),
516            containing_block_origin: Default::default(),
517            scroll_tree_node_id,
518            clip_id: ClipId::INVALID,
519            z_index: 0,
520            text_decorations: Default::default(),
521            container_timing_roots: None,
522            reference_frame_info: None,
523            participates_in_a_3d_rendering_context: false,
524        }
525    }
526
527    #[expect(clippy::too_many_arguments)]
528    fn create_descendant(
529        &self,
530        context_type: StackingContextType,
531        containing_block_offset: PhysicalPoint<Au>,
532        spatial_id: ScrollTreeNodeId,
533        clip_id: ClipId,
534        initializing_fragment: Arc<BoxFragment>,
535        reference_frame_info: Option<StackingContextReferenceFrameInfo>,
536        parent_info: &StackingContextParentInfo,
537    ) -> Self {
538        let z_index = initializing_fragment
539            .style()
540            .effective_z_index(initializing_fragment.base.flags);
541        Self {
542            fragment: StackingContextFragments::Fragment(initializing_fragment),
543            context_type,
544            containing_block_origin: containing_block_offset,
545            children: Default::default(),
546            scroll_tree_node_id: spatial_id,
547            clip_id,
548            z_index,
549            text_decorations: parent_info.text_decorations.clone(),
550            container_timing_roots: parent_info.container_timing_roots.clone(),
551            reference_frame_info,
552            participates_in_a_3d_rendering_context: parent_info
553                .participates_in_a_3d_rendering_context,
554        }
555    }
556
557    pub(crate) fn fragment(&self) -> Option<&Arc<BoxFragment>> {
558        match &self.fragment {
559            StackingContextFragments::Root => None,
560            StackingContextFragments::Fragment(box_fragment) => Some(box_fragment),
561        }
562    }
563
564    fn sort(&mut self) {
565        self.children.sort_by_key(|child| child.z_index)
566    }
567
568    fn print(&self, tree: &mut PrintTree) {
569        let fragment_string = match &self.fragment {
570            StackingContextFragments::Root => "Root".into(),
571            StackingContextFragments::Fragment(box_fragment) => format!(
572                "{:?} rect={:?}",
573                box_fragment.base.tag,
574                box_fragment.content_rect()
575            ),
576        };
577
578        tree.new_level(format!(
579            "{fragment_string} z-index={:?} spatial={:?} clip={:?}",
580            self.z_index, self.scroll_tree_node_id, self.clip_id
581        ));
582
583        for child in self.children.iter() {
584            child.print(tree);
585        }
586
587        tree.end_level();
588    }
589}
590
591impl Fragment {
592    pub(crate) fn build_stacking_context_tree(
593        &self,
594        stacking_context_tree: &mut StackingContextTree,
595        containing_block_info: &ContainingBlockInfo,
596        stacking_context: &mut StackingContext,
597        parent_info: &StackingContextParentInfo,
598    ) {
599        match self {
600            Fragment::Box(fragment) | Fragment::Float(fragment) => {
601                // Absolutely positioned elements are processed when their originating
602                // `Fragment::AbsoluteOrFixedPositionedPlaceholder` placeholder is
603                // processed.
604                if fragment
605                    .style()
606                    .get_box()
607                    .position
608                    .is_absolutely_positioned()
609                {
610                    return;
611                }
612
613                let parent_info = match self {
614                    Fragment::Float(..) => &parent_info.without_text_decorations(),
615                    _ => parent_info,
616                };
617
618                fragment.build_stacking_context_tree(
619                    stacking_context_tree,
620                    containing_block_info,
621                    stacking_context,
622                    parent_info,
623                );
624            },
625            Fragment::LayoutRoot(..) => {
626                // These fragments are processed at their originating
627                // `Fragment::AbsoluteOrFixedPositionedPlaceholder` position.
628            },
629            Fragment::AbsoluteOrFixedPositionedPlaceholder(fragment) => {
630                let shared_fragment = fragment.borrow();
631                let box_fragment = match shared_fragment.fragment.as_ref() {
632                    Some(Fragment::Box(box_fragment)) => box_fragment,
633                    _ => unreachable!("Found hoisted box with missing or non-BoxFragment."),
634                };
635
636                box_fragment.build_stacking_context_tree(
637                    stacking_context_tree,
638                    containing_block_info,
639                    stacking_context,
640                    &parent_info.without_text_decorations(),
641                );
642            },
643            Fragment::Positioning(fragment) => {
644                fragment.build_stacking_context_tree(
645                    stacking_context_tree,
646                    containing_block_info,
647                    stacking_context,
648                    parent_info,
649                );
650            },
651            Fragment::Text(_) | Fragment::Image(_) | Fragment::IFrame(_) => {},
652        }
653    }
654}
655
656struct ReferenceFrameData {
657    origin: PhysicalPoint<Au>,
658    transform: LayoutTransform,
659    kind: wr::ReferenceFrameKind,
660}
661struct ScrollFrameData {
662    scroll_tree_node_id: ScrollTreeNodeId,
663    scroll_frame_rect: LayoutRect,
664}
665
666struct OverflowFrameData {
667    clip_id: ClipId,
668    scroll_frame_data: Option<ScrollFrameData>,
669}
670
671impl BoxFragment {
672    pub(crate) fn stacking_context_type(&self) -> Option<StackingContextType> {
673        let flags = self.base.flags;
674        let style = self.style();
675        if style.establishes_stacking_context(flags) {
676            return Some(StackingContextType::StackingContext);
677        }
678
679        let box_style = &style.get_box();
680        if box_style.position != ComputedPosition::Static {
681            return Some(StackingContextType::StackingContainer);
682        }
683
684        None
685    }
686
687    fn build_stacking_context_tree(
688        self: &Arc<Self>,
689        stacking_context_tree: &mut StackingContextTree,
690        containing_block_info: &ContainingBlockInfo,
691        parent_stacking_context: &mut StackingContext,
692        parent_info: &StackingContextParentInfo,
693    ) {
694        let containing_block = containing_block_info.containing_block_for_box(self);
695        let cumulative_containing_block = containing_block
696            .rect
697            .translate(containing_block.accumulated_reference_frame_offset);
698        self.set_cumulative_content_rect(&cumulative_containing_block);
699
700        if self.base.flags.contains(FragmentFlags::IS_COLLAPSED) {
701            return;
702        }
703
704        self.clear_stacking_context_tree_traversal_data();
705        self.build_stacking_context_tree_maybe_creating_reference_frames(
706            stacking_context_tree,
707            containing_block,
708            containing_block_info,
709            parent_stacking_context,
710            parent_info,
711        );
712    }
713
714    fn build_stacking_context_tree_maybe_creating_reference_frames(
715        self: &Arc<Self>,
716        stacking_context_tree: &mut StackingContextTree,
717        containing_block: &ContainingBlock,
718        containing_block_info: &ContainingBlockInfo,
719        parent_stacking_context: &mut StackingContext,
720        parent_info: &StackingContextParentInfo,
721    ) {
722        let reference_frame_data =
723            match self.transform_reference_frame_data_if_necessary(&containing_block.rect) {
724                Some(reference_frame_data) => reference_frame_data,
725                None => {
726                    return self.build_stacking_context_tree_maybe_creating_stacking_context(
727                        stacking_context_tree,
728                        containing_block,
729                        containing_block_info,
730                        parent_stacking_context,
731                        None, /* reference_frame_info */
732                        parent_info,
733                    );
734                },
735            };
736
737        // <https://drafts.csswg.org/css-transforms/#transform-function-lists>
738        // > If a transform function causes the current transformation matrix of an object
739        // > to be non-invertible, the object and its content do not get displayed.
740        if !reference_frame_data.transform.is_invertible() {
741            self.clear_stacking_context_tree_traversal_data_recursively();
742            return;
743        }
744
745        let style = self.style();
746        let frame_origin_for_query = self
747            .cumulative_border_box_rect(
748                CumulativeContentRectCalculation::AlreadyDoneWithStackingContextTree,
749            )
750            .origin
751            .to_webrender();
752        let new_spatial_id = stacking_context_tree.push_reference_frame(
753            reference_frame_data.origin.to_webrender(),
754            frame_origin_for_query,
755            parent_info
756                .perspective_node
757                .unwrap_or(containing_block.scroll_node_id),
758            style.used_transform_style(self.base.flags).to_webrender(),
759            reference_frame_data.transform,
760            reference_frame_data.kind,
761        );
762
763        // WebRender reference frames establish a new coordinate system at their
764        // origin (the border box of the fragment). We need to ensure that any
765        // coordinates we give to WebRender in this reference frame are relative
766        // to the fragment border box. We do this by adjusting the containing
767        // block origin. Note that the `for_absolute_descendants` and
768        // `for_all_absolute_and_fixed_descendants` properties are now bogus,
769        // but all fragments that establish reference frames also establish
770        // containing blocks for absolute and fixed descendants, so those
771        // properties will be replaced before recursing into children.
772        assert!(style.establishes_containing_block_for_all_descendants(self.base.flags));
773        let reference_frame_offset = reference_frame_data.origin.to_vector();
774        let adjusted_containing_block = ContainingBlock::new(
775            containing_block.rect.translate(-reference_frame_offset),
776            new_spatial_id,
777            None,
778            ClipId::INVALID,
779            containing_block.accumulated_reference_frame_offset + reference_frame_offset,
780            false,
781        );
782        let new_containing_block_info =
783            containing_block_info.new_for_non_absolute_descendants(&adjusted_containing_block);
784
785        let reference_frame_info = StackingContextReferenceFrameInfo {
786            parent_spatial_node_id: containing_block.scroll_node_id,
787            captured_clip_id: containing_block.clip_id,
788        };
789
790        self.build_stacking_context_tree_maybe_creating_stacking_context(
791            stacking_context_tree,
792            &adjusted_containing_block,
793            &new_containing_block_info,
794            parent_stacking_context,
795            Some(reference_frame_info),
796            parent_info,
797        );
798    }
799
800    fn build_stacking_context_tree_maybe_creating_stacking_context(
801        self: &Arc<Self>,
802        stacking_context_tree: &mut StackingContextTree,
803        containing_block: &ContainingBlock,
804        containing_block_info: &ContainingBlockInfo,
805        parent_stacking_context: &mut StackingContext,
806        reference_frame_info: Option<StackingContextReferenceFrameInfo>,
807        parent_info: &StackingContextParentInfo,
808    ) {
809        let with_style = &self.with_style();
810        let style = with_style.style();
811        let Some(stacking_context_type) = self.stacking_context_type() else {
812            with_style.build_stacking_context_tree_for_children(
813                stacking_context_tree,
814                containing_block,
815                containing_block_info,
816                parent_stacking_context,
817                parent_info,
818            );
819            return;
820        };
821
822        let new_scroll_frame_size = containing_block_info
823            .for_non_absolute_descendants
824            .scroll_frame_size;
825        let spatial_id = self.build_sticky_frame_if_necessary(
826            stacking_context_tree,
827            containing_block.scroll_node_id,
828            &containing_block.rect,
829            &new_scroll_frame_size,
830            containing_block.established_scroll_frame,
831        );
832
833        let clip_id = with_style.build_clip_frame_if_necessary(
834            stacking_context_tree,
835            spatial_id.unwrap_or(containing_block.scroll_node_id),
836            containing_block.clip_id,
837            &containing_block.rect,
838        );
839
840        let clip_id = stacking_context_tree
841            .clip_store
842            .add_for_clip_path(
843                &style.get_svg().clip_path,
844                spatial_id.unwrap_or(containing_block.scroll_node_id),
845                clip_id.unwrap_or(containing_block.clip_id),
846                with_style,
847                containing_block.rect.origin,
848            )
849            .or(clip_id);
850
851        let containing_block = if clip_id.is_some() || spatial_id.is_some() {
852            if let Some(clip_id) = clip_id {
853                self.set_generated_clip_id(clip_id);
854            }
855            if let Some(spatial_id) = spatial_id {
856                self.set_generated_scroll_tree_node_id(spatial_id);
857            }
858            &ContainingBlock {
859                scroll_node_id: spatial_id.unwrap_or(containing_block.scroll_node_id),
860                clip_id: clip_id.unwrap_or(containing_block.clip_id),
861                ..*containing_block
862            }
863        } else {
864            containing_block
865        };
866
867        let box_fragment = self.clone();
868        let mut child_stacking_context = parent_stacking_context.create_descendant(
869            stacking_context_type,
870            containing_block.rect.origin,
871            containing_block.scroll_node_id,
872            containing_block.clip_id,
873            box_fragment,
874            reference_frame_info,
875            parent_info,
876        );
877        with_style.build_stacking_context_tree_for_children(
878            stacking_context_tree,
879            containing_block,
880            containing_block_info,
881            &mut child_stacking_context,
882            parent_info,
883        );
884
885        let mut stolen_children = vec![];
886        if stacking_context_type != StackingContextType::StackingContext {
887            stolen_children =
888                std::mem::replace(&mut child_stacking_context.children, stolen_children);
889        } else {
890            child_stacking_context.sort();
891        }
892
893        parent_stacking_context
894            .children
895            .push(child_stacking_context);
896        parent_stacking_context
897            .children
898            .append(&mut stolen_children);
899    }
900}
901
902impl BoxFragmentWithStyle<'_> {
903    fn build_stacking_context_tree_for_children(
904        &self,
905        stacking_context_tree: &mut StackingContextTree,
906        containing_block: &ContainingBlock,
907        containing_block_info: &ContainingBlockInfo,
908        stacking_context: &mut StackingContext,
909        parent_info: &StackingContextParentInfo,
910    ) {
911        let style = self.style();
912        let establishes_containing_block_for_all_descendants =
913            style.establishes_containing_block_for_all_descendants(self.base.flags);
914        let establishes_containing_block_for_absolute_descendants =
915            style.establishes_containing_block_for_absolute_descendants(self.base.flags);
916
917        let original_scroll_node_id = containing_block.scroll_node_id;
918        let mut new_scroll_node_id = original_scroll_node_id;
919        self.spatial_tree_node.set(Some(new_scroll_node_id));
920
921        // We want to build the scroll frame after the background and border, because
922        // they shouldn't scroll with the rest of the box content.
923        let mut new_scroll_frame_size = containing_block_info
924            .for_non_absolute_descendants
925            .scroll_frame_size;
926
927        let mut established_scroll_frame = containing_block.established_scroll_frame;
928        // We want to skip leaving scroll frame for anonymous fragments,
929        // because anonymous fragment belong to same node as its closest non-anonymous child.
930        if established_scroll_frame && !self.base.is_anonymous() {
931            established_scroll_frame = false;
932        }
933        let mut new_clip_id = containing_block.clip_id;
934        if let Some(overflow_frame_data) = self.build_overflow_frame_if_necessary(
935            stacking_context_tree,
936            new_scroll_node_id,
937            new_clip_id,
938            &containing_block.rect,
939        ) {
940            new_clip_id = overflow_frame_data.clip_id;
941            self.set_generated_clip_id(new_clip_id);
942
943            if let Some(scroll_frame_data) = overflow_frame_data.scroll_frame_data {
944                new_scroll_node_id = scroll_frame_data.scroll_tree_node_id;
945                new_scroll_frame_size = Some(scroll_frame_data.scroll_frame_rect.size());
946                established_scroll_frame = true;
947                self.set_generated_scroll_tree_node_id(new_scroll_node_id);
948            }
949        }
950
951        let new_perspective_node = self.build_perspective_frame_if_necessary(
952            stacking_context_tree,
953            containing_block,
954            new_scroll_node_id,
955            original_scroll_node_id,
956            established_scroll_frame,
957        );
958
959        let content_rect = self
960            .content_rect()
961            .translate(containing_block.rect.origin.to_vector());
962        let containing_block_for_descendants = ContainingBlock::new(
963            content_rect,
964            new_scroll_node_id,
965            new_scroll_frame_size,
966            new_clip_id,
967            containing_block.accumulated_reference_frame_offset,
968            established_scroll_frame,
969        );
970
971        // Create a new `ContainingBlockInfo` for descendants depending on
972        // whether or not this fragment establishes a containing block for
973        // absolute and fixed descendants.
974        let new_containing_block_info = if establishes_containing_block_for_all_descendants {
975            containing_block_info
976                .new_for_absolute_and_fixed_descendants(&containing_block_for_descendants)
977        } else if establishes_containing_block_for_absolute_descendants {
978            containing_block_info.new_for_absolute_descendants(&containing_block_for_descendants)
979        } else {
980            containing_block_info
981                .new_for_non_absolute_descendants(&containing_block_for_descendants)
982        };
983
984        let parent_info_for_children = parent_info.for_children(self, new_perspective_node);
985        for child in &self.children {
986            child.build_stacking_context_tree(
987                stacking_context_tree,
988                &new_containing_block_info,
989                stacking_context,
990                &parent_info_for_children,
991            );
992        }
993    }
994
995    fn build_perspective_frame_if_necessary(
996        &self,
997        stacking_context_tree: &mut StackingContextTree,
998        containing_block: &ContainingBlock,
999        new_scroll_node_id: ScrollTreeNodeId,
1000        original_scroll_node_id: ScrollTreeNodeId,
1001        established_scroll_frame: bool,
1002    ) -> Option<ScrollTreeNodeId> {
1003        if !self.style().is_transformable(self.base.flags) {
1004            return None;
1005        }
1006
1007        let border_rect = self
1008            .border_rect()
1009            .translate(containing_block.rect.origin.to_vector());
1010        let perspective = self.calculate_perspective_matrix(&border_rect)?;
1011
1012        let perspective = perspective.change_basis(
1013            border_rect.origin.x.to_f32_px(),
1014            border_rect.origin.y.to_f32_px(),
1015            0.0,
1016        );
1017        let frame_origin_for_query = self
1018            .cumulative_border_box_rect(
1019                CumulativeContentRectCalculation::AlreadyDoneWithStackingContextTree,
1020            )
1021            .origin -
1022            border_rect.origin.to_vector();
1023        let scrolling_relative_to = if established_scroll_frame {
1024            Some(
1025                stacking_context_tree
1026                    .paint_info
1027                    .external_scroll_id_for_scroll_tree_node(original_scroll_node_id),
1028            )
1029        } else {
1030            None
1031        };
1032
1033        Some(stacking_context_tree.push_reference_frame(
1034            LayoutPoint::zero(),
1035            frame_origin_for_query.to_webrender(),
1036            new_scroll_node_id,
1037            wr::TransformStyle::Flat,
1038            perspective,
1039            wr::ReferenceFrameKind::Perspective {
1040                scrolling_relative_to,
1041            },
1042        ))
1043    }
1044
1045    fn build_clip_frame_if_necessary(
1046        &self,
1047        stacking_context_tree: &mut StackingContextTree,
1048        parent_scroll_node_id: ScrollTreeNodeId,
1049        parent_clip_id: ClipId,
1050        containing_block_rect: &PhysicalRect<Au>,
1051    ) -> Option<ClipId> {
1052        let style = self.style();
1053        let position = style.get_box().position;
1054        // https://drafts.csswg.org/css2/#clipping
1055        // The clip property applies only to absolutely positioned elements
1056        if !position.is_absolutely_positioned() {
1057            return None;
1058        }
1059
1060        // Only rectangles are supported for now.
1061        let clip_rect = match style.get_effects().clip {
1062            ClipRectOrAuto::Rect(rect) => rect,
1063            _ => return None,
1064        };
1065
1066        let border_rect = self.border_rect();
1067        let clip_rect = clip_rect
1068            .for_border_rect(border_rect)
1069            .translate(containing_block_rect.origin.to_vector())
1070            .to_webrender();
1071        Some(stacking_context_tree.clip_store.add(
1072            BorderRadius::zero(),
1073            clip_rect,
1074            parent_scroll_node_id,
1075            parent_clip_id,
1076        ))
1077    }
1078
1079    fn build_overflow_frame_if_necessary(
1080        &self,
1081        stacking_context_tree: &mut StackingContextTree,
1082        parent_scroll_node_id: ScrollTreeNodeId,
1083        parent_clip_id: ClipId,
1084        containing_block_rect: &PhysicalRect<Au>,
1085    ) -> Option<OverflowFrameData> {
1086        let style = self.style();
1087        let overflow = style.effective_overflow(self.base.flags);
1088
1089        if overflow.x == ComputedOverflow::Visible && overflow.y == ComputedOverflow::Visible {
1090            return None;
1091        }
1092
1093        // Non-scrollable overflow path
1094        if overflow.x == ComputedOverflow::Clip || overflow.y == ComputedOverflow::Clip {
1095            let overflow_clip_margin = style.get_margin().overflow_clip_margin;
1096            let mut overflow_clip_rect = match overflow_clip_margin.visual_box {
1097                OverflowClipMarginBox::ContentBox => self.content_rect(),
1098                OverflowClipMarginBox::PaddingBox => self.padding_rect(),
1099                OverflowClipMarginBox::BorderBox => self.border_rect(),
1100            }
1101            .translate(containing_block_rect.origin.to_vector())
1102            .to_webrender();
1103
1104            // Adjust by the overflow clip margin.
1105            // https://drafts.csswg.org/css-overflow-3/#overflow-clip-margin
1106            let clip_margin_offset = overflow_clip_margin.offset.px();
1107            overflow_clip_rect = overflow_clip_rect.inflate(clip_margin_offset, clip_margin_offset);
1108
1109            // The clipping region only gets rounded corners if both axes have `overflow: clip`.
1110            // https://drafts.csswg.org/css-overflow-3/#corner-clipping
1111            let radii =
1112                if overflow.x == ComputedOverflow::Clip && overflow.y == ComputedOverflow::Clip {
1113                    let builder = BuilderForBoxFragment::new(self, containing_block_rect.origin);
1114                    let mut offsets_from_border = SideOffsets2D::new_all_same(clip_margin_offset);
1115                    match overflow_clip_margin.visual_box {
1116                        OverflowClipMarginBox::ContentBox => {
1117                            offsets_from_border -= (self.border + self.padding).to_webrender();
1118                        },
1119                        OverflowClipMarginBox::PaddingBox => {
1120                            offsets_from_border -= self.border.to_webrender();
1121                        },
1122                        OverflowClipMarginBox::BorderBox => {},
1123                    };
1124                    offset_radii(builder.border_radius(), offsets_from_border)
1125                } else if overflow.x != ComputedOverflow::Clip {
1126                    let max = LayoutRect::max_rect();
1127                    overflow_clip_rect.min.x = max.min.x;
1128                    overflow_clip_rect.max.x = max.max.x;
1129                    BorderRadius::zero()
1130                } else {
1131                    let max = LayoutRect::max_rect();
1132                    overflow_clip_rect.min.y = max.min.y;
1133                    overflow_clip_rect.max.y = max.max.y;
1134                    BorderRadius::zero()
1135                };
1136
1137            let clip_id = stacking_context_tree.clip_store.add(
1138                radii,
1139                overflow_clip_rect,
1140                parent_scroll_node_id,
1141                parent_clip_id,
1142            );
1143
1144            return Some(OverflowFrameData {
1145                clip_id,
1146                scroll_frame_data: None,
1147            });
1148        }
1149
1150        let scroll_frame_rect = self
1151            .padding_rect()
1152            .translate(containing_block_rect.origin.to_vector())
1153            .to_webrender();
1154        let scroll_frame_content_rect = self
1155            .scrollable_overflow()
1156            .translate(containing_block_rect.origin.to_vector())
1157            .to_webrender();
1158
1159        let clip_id = stacking_context_tree.clip_store.add(
1160            BuilderForBoxFragment::new(self, containing_block_rect.origin).border_radius(),
1161            scroll_frame_rect,
1162            parent_scroll_node_id,
1163            parent_clip_id,
1164        );
1165
1166        let tag = self.base.tag?;
1167        let external_scroll_id = wr::ExternalScrollId(
1168            tag.to_display_list_fragment_id(),
1169            stacking_context_tree.paint_info.pipeline_id,
1170        );
1171
1172        let mut x_sensitivity: ScrollType = overflow.x.into();
1173        let mut y_sensitivity: ScrollType = overflow.y.into();
1174        let touch_action = TouchAction::from(style.get_box().touch_action);
1175        // `touch-action` only restricts direct touch manipulation; mouse wheel
1176        // (`InputEvents`) and script-driven scrolling are unaffected, so we only
1177        // strip `ScrollType::Touch` from the excluded axis.
1178        match touch_action {
1179            TouchAction::PanX => {
1180                y_sensitivity.remove(ScrollType::Touch);
1181            },
1182            TouchAction::PanY => {
1183                x_sensitivity.remove(ScrollType::Touch);
1184            },
1185            TouchAction::None => {
1186                x_sensitivity.remove(ScrollType::Touch);
1187                y_sensitivity.remove(ScrollType::Touch);
1188            },
1189            TouchAction::Auto => {},
1190        }
1191        let sensitivity = AxesScrollSensitivity {
1192            x: x_sensitivity,
1193            y: y_sensitivity,
1194        };
1195
1196        let scroll_tree_node_id = stacking_context_tree.define_scroll_frame(
1197            parent_scroll_node_id,
1198            external_scroll_id,
1199            scroll_frame_content_rect,
1200            scroll_frame_rect,
1201            sensitivity,
1202            touch_action,
1203        );
1204
1205        Some(OverflowFrameData {
1206            clip_id,
1207            scroll_frame_data: Some(ScrollFrameData {
1208                scroll_tree_node_id,
1209                scroll_frame_rect,
1210            }),
1211        })
1212    }
1213}
1214
1215impl BoxFragment {
1216    fn build_sticky_frame_if_necessary(
1217        &self,
1218        stacking_context_tree: &mut StackingContextTree,
1219        parent_scroll_node_id: ScrollTreeNodeId,
1220        containing_block_rect: &PhysicalRect<Au>,
1221        scroll_frame_size: &Option<LayoutSize>,
1222        established_scroll_frame: bool,
1223    ) -> Option<ScrollTreeNodeId> {
1224        let style = self.style();
1225        if style.get_box().position != ComputedPosition::Sticky {
1226            return None;
1227        }
1228
1229        let scroll_frame_size_for_resolve = match scroll_frame_size {
1230            Some(size) => size,
1231            None => {
1232                // This is a direct descendant of a reference frame.
1233                &stacking_context_tree
1234                    .paint_info
1235                    .viewport_details
1236                    .layout_size()
1237            },
1238        };
1239
1240        // Percentages sticky positions offsets are resovled against the size of the
1241        // nearest scroll frame instead of the containing block like for other types
1242        // of positioning.
1243        let scroll_frame_height = Au::from_f32_px(scroll_frame_size_for_resolve.height);
1244        let scroll_frame_width = Au::from_f32_px(scroll_frame_size_for_resolve.width);
1245        let offsets = style.physical_box_offsets();
1246        let offsets = PhysicalSides::<AuOrAuto>::new(
1247            offsets.top.map(|v| v.to_used_value(scroll_frame_height)),
1248            offsets.right.map(|v| v.to_used_value(scroll_frame_width)),
1249            offsets.bottom.map(|v| v.to_used_value(scroll_frame_height)),
1250            offsets.left.map(|v| v.to_used_value(scroll_frame_width)),
1251        );
1252        self.set_resolved_sticky_insets(offsets);
1253
1254        if scroll_frame_size.is_none() {
1255            return None;
1256        }
1257
1258        if offsets.top.is_auto() &&
1259            offsets.right.is_auto() &&
1260            offsets.bottom.is_auto() &&
1261            offsets.left.is_auto()
1262        {
1263            return None;
1264        }
1265
1266        // https://drafts.csswg.org/css-position/#stickypos-insets
1267        // > For each side of the box, if the corresponding inset property is not `auto`, and the
1268        // > corresponding border edge of the box would be outside the corresponding edge of the
1269        // > sticky view rectangle, the box must be visually shifted (as for relative positioning)
1270        // > to be inward of that sticky view rectangle edge, insofar as it can while its position
1271        // > box remains contained within its containing block.
1272        // > The *position box* is its margin box, except that for any side for which the distance
1273        // > between its margin edge and the corresponding edge of its containing block is less
1274        // > than its corresponding margin, that distance is used in place of that margin.
1275        //
1276        // Amendments:
1277        // - Using the "margin edge" seems nonsensical, the spec must mean "border edge" instead:
1278        //   https://github.com/w3c/csswg-drafts/issues/12833
1279        // - `auto` margins need to be treated as zero:
1280        //   https://github.com/w3c/csswg-drafts/issues/12852
1281        //
1282        // We implement this by enforcing a minimum negative offset and a maximum positive offset.
1283        // The logic below is a simplified (but equivalent) version of the description above.
1284        let border_rect = self.border_rect();
1285        let computed_margin = style.physical_margin();
1286        let parent_scroll_node = stacking_context_tree
1287            .paint_info
1288            .scroll_tree
1289            .get_node(parent_scroll_node_id);
1290        let sticky_offset_boundary = match parent_scroll_node.info {
1291            SpatialTreeNodeInfo::Scroll(ref scrollable_node_info) if established_scroll_frame => {
1292                let content_rect = &scrollable_node_info.content_rect;
1293                &PhysicalRect::new(
1294                    PhysicalPoint::new(
1295                        Au::from_f32_px(content_rect.min.x),
1296                        Au::from_f32_px(content_rect.min.y),
1297                    ),
1298                    PhysicalSize::new(
1299                        Au::from_f32_px(content_rect.max.x - content_rect.min.x),
1300                        Au::from_f32_px(content_rect.max.y - content_rect.min.y),
1301                    ),
1302                )
1303            },
1304            _ => containing_block_rect,
1305        };
1306        // Signed distance between each side of the border box to the corresponding side of the
1307        // containing block. Note that |border_rect| is already in the coordinate system of the
1308        // containing block.
1309        let distance_from_border_box_to_cb = PhysicalSides::new(
1310            border_rect.min_y(),
1311            sticky_offset_boundary.width() - border_rect.max_x(),
1312            sticky_offset_boundary.height() - border_rect.max_y(),
1313            border_rect.min_x(),
1314        );
1315        // Shrinks the signed distance by the margin, producing a limit on how much we can shift
1316        // the sticky positioned box without forcing the margin to move outside of the containing
1317        // block.
1318        let offset_bound = |distance, used_margin, computed_margin: LengthPercentageOrAuto| {
1319            let used_margin = if computed_margin.is_auto() {
1320                Au::zero()
1321            } else {
1322                used_margin
1323            };
1324            Au::zero().max(distance - used_margin).to_f32_px()
1325        };
1326
1327        // This is the minimum negative offset and then the maximum positive offset. We specify
1328        // all sides, but they will have no effect if the corresponding inset property is `auto`.
1329        let vertical_offset_bounds = wr::StickyOffsetBounds::new(
1330            -offset_bound(
1331                distance_from_border_box_to_cb.top,
1332                self.margin.top,
1333                computed_margin.top,
1334            ),
1335            offset_bound(
1336                distance_from_border_box_to_cb.bottom,
1337                self.margin.bottom,
1338                computed_margin.bottom,
1339            ),
1340        );
1341        let horizontal_offset_bounds = wr::StickyOffsetBounds::new(
1342            -offset_bound(
1343                distance_from_border_box_to_cb.left,
1344                self.margin.left,
1345                computed_margin.left,
1346            ),
1347            offset_bound(
1348                distance_from_border_box_to_cb.right,
1349                self.margin.right,
1350                computed_margin.right,
1351            ),
1352        );
1353
1354        let frame_rect = border_rect
1355            .translate(containing_block_rect.origin.to_vector())
1356            .to_webrender();
1357
1358        // These are the "margins" between the scrollport and |frame_rect|. They are not the same
1359        // as CSS margins.
1360        let margins = SideOffsets2D::new(
1361            offsets.top.non_auto().map(|v| v.to_f32_px()),
1362            offsets.right.non_auto().map(|v| v.to_f32_px()),
1363            offsets.bottom.non_auto().map(|v| v.to_f32_px()),
1364            offsets.left.non_auto().map(|v| v.to_f32_px()),
1365        );
1366
1367        let sticky_node_id = stacking_context_tree.define_sticky_frame(
1368            parent_scroll_node_id,
1369            frame_rect,
1370            margins,
1371            vertical_offset_bounds,
1372            horizontal_offset_bounds,
1373        );
1374
1375        Some(sticky_node_id)
1376    }
1377
1378    /// Optionally returns the data for building a transform reference frame, without yet
1379    /// building it.
1380    fn transform_reference_frame_data_if_necessary(
1381        &self,
1382        containing_block_rect: &PhysicalRect<Au>,
1383    ) -> Option<ReferenceFrameData> {
1384        if !self.style().has_effective_transform(self.base.flags) {
1385            return None;
1386        }
1387
1388        let relative_border_rect = self.border_rect();
1389        let border_rect = relative_border_rect.translate(containing_block_rect.origin.to_vector());
1390        let transform = self.calculate_transform_matrix(&border_rect)?;
1391        Some(ReferenceFrameData {
1392            origin: border_rect.origin,
1393            transform,
1394            kind: wr::ReferenceFrameKind::Transform {
1395                is_2d_scale_translation: false,
1396                should_snap: false,
1397                // WebRender ignores this value, so it doesn't matter what it is set to.
1398                paired_with_perspective: false,
1399            },
1400        })
1401    }
1402
1403    /// Returns the 4D matrix representing this fragment's transform.
1404    pub fn calculate_transform_matrix(
1405        &self,
1406        border_rect: &Rect<Au, CSSPixel>,
1407    ) -> Option<LayoutTransform> {
1408        let style = self.style();
1409        let list = &style.get_box().transform;
1410        let length_rect = au_rect_to_length_rect(border_rect);
1411        // https://drafts.csswg.org/css-transforms-2/#individual-transforms
1412        let rotate = match style.get_rotate() {
1413            GenericRotate::Rotate(angle) => (0., 0., 1., *angle),
1414            GenericRotate::Rotate3D(x, y, z, angle) => {
1415                // These are the raw, unormalized values from CSS, but euclid expects
1416                // rotation input to be normalized, so we must do that first.
1417                get_normalized_vector_and_angle(*x, *y, *z, *angle)
1418            },
1419            GenericRotate::None => (0., 0., 1., Angle::zero()),
1420        };
1421        let scale = match style.get_scale() {
1422            GenericScale::Scale(sx, sy, sz) => (*sx, *sy, *sz),
1423            GenericScale::None => (1., 1., 1.),
1424        };
1425        let translation = match style.get_translate() {
1426            GenericTranslate::Translate(x, y, z) => LayoutTransform::translation(
1427                x.resolve(length_rect.size.width).px(),
1428                y.resolve(length_rect.size.height).px(),
1429                z.px(),
1430            ),
1431            GenericTranslate::None => LayoutTransform::identity(),
1432        };
1433
1434        let angle = euclid::Angle::radians(rotate.3.radians());
1435        let transform_base = list
1436            .to_transform_3d_matrix(Some(&length_rect.to_untyped()))
1437            .ok()?;
1438        let transform = LayoutTransform::from_untyped(&transform_base.0)
1439            .then_rotate(rotate.0, rotate.1, rotate.2, angle)
1440            .then_scale(scale.0, scale.1, scale.2)
1441            .then(&translation);
1442
1443        let transform_origin = &style.get_box().transform_origin;
1444        let transform_origin_x = transform_origin
1445            .horizontal
1446            .to_used_value(border_rect.size.width)
1447            .to_f32_px();
1448        let transform_origin_y = transform_origin
1449            .vertical
1450            .to_used_value(border_rect.size.height)
1451            .to_f32_px();
1452        let transform_origin_z = transform_origin.depth.px();
1453
1454        Some(transform.change_basis(transform_origin_x, transform_origin_y, transform_origin_z))
1455    }
1456
1457    /// Returns the 4D matrix representing this fragment's perspective.
1458    pub fn calculate_perspective_matrix(
1459        &self,
1460        border_rect: &Rect<Au, CSSPixel>,
1461    ) -> Option<LayoutTransform> {
1462        let style = self.style();
1463        match style.get_box().perspective {
1464            Perspective::Length(length) => {
1465                let perspective_origin = &style.get_box().perspective_origin;
1466                let perspective_origin = LayoutPoint::new(
1467                    perspective_origin
1468                        .horizontal
1469                        .percentage_relative_to(border_rect.size.width.into())
1470                        .px(),
1471                    perspective_origin
1472                        .vertical
1473                        .percentage_relative_to(border_rect.size.height.into())
1474                        .px(),
1475                );
1476
1477                let perspective_matrix = LayoutTransform::from_untyped(
1478                    &transform::create_perspective_matrix(length.px()),
1479                );
1480
1481                Some(perspective_matrix.change_basis(
1482                    perspective_origin.x,
1483                    perspective_origin.y,
1484                    0.0,
1485                ))
1486            },
1487            Perspective::None => None,
1488        }
1489    }
1490
1491    fn clear_stacking_context_tree_traversal_data_recursively(&self) {
1492        fn clear_stacking_context_tree_traversal_data_on_fragments(fragments: &[Fragment]) {
1493            for fragment in fragments.iter() {
1494                match fragment {
1495                    Fragment::LayoutRoot(layout_root_fragment) => layout_root_fragment
1496                        .inner_box_fragment()
1497                        .clear_stacking_context_tree_traversal_data_recursively(),
1498                    Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => {
1499                        box_fragment.clear_stacking_context_tree_traversal_data_recursively();
1500                    },
1501                    Fragment::Positioning(positioning_fragment) => {
1502                        positioning_fragment.spatial_tree_node.clear();
1503                        clear_stacking_context_tree_traversal_data_on_fragments(
1504                            &positioning_fragment.children,
1505                        );
1506                    },
1507                    _ => {},
1508                }
1509            }
1510        }
1511
1512        self.spatial_tree_node.clear();
1513        self.clear_stacking_context_tree_traversal_data();
1514        clear_stacking_context_tree_traversal_data_on_fragments(&self.children);
1515    }
1516}
1517
1518impl PositioningFragment {
1519    fn build_stacking_context_tree(
1520        &self,
1521        stacking_context_tree: &mut StackingContextTree,
1522        containing_block_info: &ContainingBlockInfo,
1523        stacking_context: &mut StackingContext,
1524        parent_info: &StackingContextParentInfo,
1525    ) {
1526        let containing_block = containing_block_info.for_non_absolute_descendants;
1527        let cumulative_containing_block = containing_block
1528            .rect
1529            .translate(containing_block.accumulated_reference_frame_offset);
1530        self.set_cumulative_content_rect(&cumulative_containing_block);
1531        self.spatial_tree_node
1532            .set(Some(containing_block.scroll_node_id));
1533
1534        let rect = self
1535            .base
1536            .rect()
1537            .translate(containing_block.rect.origin.to_vector());
1538        let new_containing_block = containing_block.new_replacing_rect(&rect);
1539        let new_containing_block_info =
1540            containing_block_info.new_for_non_absolute_descendants(&new_containing_block);
1541
1542        for child in &self.children {
1543            child.build_stacking_context_tree(
1544                stacking_context_tree,
1545                &new_containing_block_info,
1546                stacking_context,
1547                parent_info,
1548            );
1549        }
1550    }
1551}
1552
1553pub(crate) fn au_rect_to_length_rect(rect: &Rect<Au, CSSPixel>) -> Rect<Length, CSSPixel> {
1554    Rect::new(
1555        Point2D::new(rect.origin.x.into(), rect.origin.y.into()),
1556        Size2D::new(rect.size.width.into(), rect.size.height.into()),
1557    )
1558}