Skip to main content

paint_api/
display_list.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
5//! Defines data structures which are consumed by `Paint`.
6
7use std::cell::Cell;
8use std::collections::HashMap;
9
10use bitflags::bitflags;
11use embedder_traits::ViewportDetails;
12use euclid::SideOffsets2D;
13use malloc_size_of_derive::MallocSizeOf;
14use rustc_hash::FxHashMap;
15use serde::{Deserialize, Serialize};
16use servo_base::Epoch;
17use servo_base::cross_process_instant::CrossProcessInstant;
18use servo_base::id::{ContainerTimingID, LCPCandidateID, ScrollTreeNodeId};
19use servo_base::print_tree::PrintTree;
20use servo_geometry::FastLayoutTransform;
21use style::values::specified::Overflow;
22use webrender_api::units::{LayoutPixel, LayoutPoint, LayoutRect, LayoutSize, LayoutVector2D};
23use webrender_api::{
24    ColorF, ExternalScrollId, PipelineId, PropertyBindingKey, ReferenceFrameKind, ScrollLocation,
25    SpatialId, StickyOffsetBounds, TransformStyle,
26};
27
28/// A scroll type, describing whether what kind of action originated this scroll request.
29/// This is a bitflag as it is also used to track what kinds of [`ScrollType`]s scroll
30/// nodes are sensitive to.
31#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
32pub struct ScrollType(u8);
33
34bitflags! {
35    impl ScrollType: u8 {
36        /// This node can be scrolled by mouse wheel or other non-touch input events, or
37        /// such an input event originated this scroll.
38        const InputEvents = 1 << 0;
39        /// This node can be scrolled by script events or script originated this scroll.
40        const Script = 1 << 1;
41        /// This node can be scrolled by touch direct manipulation, or a touch event
42        /// originated this scroll. Distinct from [`Self::InputEvents`] so that `touch-action`
43        /// can restrict touch panning without affecting mouse wheel scrolling.
44        const Touch = 1 << 2;
45    }
46}
47
48/// Convert [Overflow] to [ScrollType].
49impl From<Overflow> for ScrollType {
50    fn from(overflow: Overflow) -> Self {
51        match overflow {
52            Overflow::Hidden => ScrollType::Script,
53            Overflow::Scroll | Overflow::Auto => {
54                ScrollType::Script | ScrollType::InputEvents | ScrollType::Touch
55            },
56            Overflow::Visible | Overflow::Clip => ScrollType::empty(),
57        }
58    }
59}
60
61/// The [ScrollType] of particular node in the vertical and horizontal axes.
62#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
63pub struct AxesScrollSensitivity {
64    pub x: ScrollType,
65    pub y: ScrollType,
66}
67
68/// A simplified representation of the CSS `touch-action` property, used by the
69/// compositor to decide how a touch gesture may scroll a given node.
70///
71/// NOTE: Directional variants (`pan-left`/`pan-right`/...) are not supported in Stylo at all.
72/// Firefox also fails the parsing.
73#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
74pub enum TouchAction {
75    /// `touch-action: auto` (and `manipulation`, `pan-x pan-y`). The compositor
76    /// applies the scroll-chaining axis lock: lock to the dominant axis only
77    /// when the hit node cannot scroll that axis.
78    Auto,
79    /// `touch-action: pan-x`. The vertical axis is excluded from input-event
80    /// scrolling (chains to ancestor); the gesture locks to its dominant axis.
81    PanX,
82    /// `touch-action: pan-y`. The horizontal axis is excluded from input-event
83    /// scrolling (chains to ancestor); the gesture locks to its dominant axis.
84    PanY,
85    /// `touch-action: none` (and `pinch-zoom` alone). No single-finger direct
86    /// manipulation: do not scroll.
87    None,
88}
89
90impl From<style::values::specified::TouchAction> for TouchAction {
91    fn from(stylo: style::values::specified::TouchAction) -> Self {
92        use style::values::specified::TouchAction as T;
93        if stylo.contains(T::NONE) {
94            return TouchAction::None;
95        }
96        if stylo.contains(T::AUTO) || stylo.contains(T::MANIPULATION) {
97            return TouchAction::Auto;
98        }
99        match (stylo.contains(T::PAN_X), stylo.contains(T::PAN_Y)) {
100            (true, true) => TouchAction::Auto,
101            (true, false) => TouchAction::PanX,
102            (false, true) => TouchAction::PanY,
103            (false, false) => TouchAction::None,
104        }
105    }
106}
107
108#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
109pub enum SpatialTreeNodeInfo {
110    ReferenceFrame(ReferenceFrameNodeInfo),
111    Scroll(ScrollableNodeInfo),
112    Sticky(StickyNodeInfo),
113}
114
115#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
116pub struct StickyNodeInfo {
117    pub frame_rect: LayoutRect,
118    pub margins: SideOffsets2D<Option<f32>, LayoutPixel>,
119    pub vertical_offset_bounds: StickyOffsetBounds,
120    pub horizontal_offset_bounds: StickyOffsetBounds,
121}
122
123impl StickyNodeInfo {
124    /// Calculate the sticky offset for this [`StickyNodeInfo`] given information about
125    /// sticky positioning from its ancestors.
126    ///
127    /// This is originally taken from WebRender `SpatialTree` implementation.
128    fn calculate_sticky_offset(
129        &self,
130        viewport_scroll_offset: &LayoutVector2D,
131        viewport_rect: &LayoutRect,
132    ) -> LayoutVector2D {
133        if self.margins.top.is_none() &&
134            self.margins.bottom.is_none() &&
135            self.margins.left.is_none() &&
136            self.margins.right.is_none()
137        {
138            return LayoutVector2D::zero();
139        }
140
141        // The viewport and margins of the item establishes the maximum amount that it can
142        // be offset in order to keep it on screen. Since we care about the relationship
143        // between the scrolled content and unscrolled viewport we adjust the viewport's
144        // position by the scroll offset in order to work with their relative positions on the
145        // page.
146        let mut sticky_rect = self.frame_rect.translate(*viewport_scroll_offset);
147
148        let mut sticky_offset = LayoutVector2D::zero();
149        if let Some(margin) = self.margins.top {
150            let top_viewport_edge = viewport_rect.min.y + margin;
151            if sticky_rect.min.y < top_viewport_edge {
152                // If the sticky rect is positioned above the top edge of the viewport (plus margin)
153                // we move it down so that it is fully inside the viewport.
154                sticky_offset.y = top_viewport_edge - sticky_rect.min.y;
155            }
156        }
157
158        // If we don't have a sticky-top offset (sticky_offset.y == 0) then we check for
159        // handling the bottom margin case. Note that the "don't have a sticky-top offset"
160        // case includes the case where we *had* a sticky-top offset but we reduced it to
161        // zero in the above block.
162        if sticky_offset.y <= 0.0 &&
163            let Some(margin) = self.margins.bottom
164        {
165            // If sticky_offset.y is nonzero that means we must have set it
166            // in the sticky-top handling code above, so this item must have
167            // both top and bottom sticky margins. We adjust the item's rect
168            // by the top-sticky offset, and then combine any offset from
169            // the bottom-sticky calculation into sticky_offset below.
170            sticky_rect.min.y += sticky_offset.y;
171            sticky_rect.max.y += sticky_offset.y;
172
173            // Same as the above case, but inverted for bottom-sticky items. Here
174            // we adjust items upwards, resulting in a negative sticky_offset.y,
175            // or reduce the already-present upward adjustment, resulting in a positive
176            // sticky_offset.y.
177            let bottom_viewport_edge = viewport_rect.max.y - margin;
178            if sticky_rect.max.y > bottom_viewport_edge {
179                sticky_offset.y += bottom_viewport_edge - sticky_rect.max.y;
180            }
181        }
182
183        // Same as above, but for the x-axis.
184        if let Some(margin) = self.margins.left {
185            let left_viewport_edge = viewport_rect.min.x + margin;
186            if sticky_rect.min.x < left_viewport_edge {
187                sticky_offset.x = left_viewport_edge - sticky_rect.min.x;
188            }
189        }
190
191        if sticky_offset.x <= 0.0 &&
192            let Some(margin) = self.margins.right
193        {
194            sticky_rect.min.x += sticky_offset.x;
195            sticky_rect.max.x += sticky_offset.x;
196            let right_viewport_edge = viewport_rect.max.x - margin;
197            if sticky_rect.max.x > right_viewport_edge {
198                sticky_offset.x += right_viewport_edge - sticky_rect.max.x;
199            }
200        }
201
202        // The total "sticky offset" and the extra amount we computed as a result of
203        // scrolling, stored in sticky_offset needs to be clamped to the provided bounds.
204        let clamp =
205            |value: f32, bounds: &StickyOffsetBounds| (value).max(bounds.min).min(bounds.max);
206        sticky_offset.y = clamp(sticky_offset.y, &self.vertical_offset_bounds);
207        sticky_offset.x = clamp(sticky_offset.x, &self.horizontal_offset_bounds);
208
209        sticky_offset
210    }
211}
212
213#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
214pub struct ReferenceFrameNodeInfo {
215    pub origin: LayoutPoint,
216    /// Origin of this frame relative to the document for bounding box queries.
217    pub frame_origin_for_query: LayoutPoint,
218    pub transform_style: TransformStyle,
219    pub transform: FastLayoutTransform,
220    pub kind: ReferenceFrameKind,
221}
222
223/// Returns the minimum and maximum allowed scroll offsets for a scroll container,
224/// given its scrolling area and scrollport rectangles.
225pub fn scroll_range_for_scrolling_area_and_scrollport(
226    scrolling_area: &LayoutRect,
227    scrollport: &LayoutRect,
228) -> (LayoutVector2D, LayoutVector2D) {
229    (
230        (scrolling_area.min - scrollport.min).min(LayoutVector2D::zero()),
231        (scrolling_area.max - scrollport.max).max(LayoutVector2D::zero()),
232    )
233}
234
235/// Data stored for nodes in the [ScrollTree] that actually scroll,
236/// as opposed to reference frames and sticky nodes which do not.
237#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
238pub struct ScrollableNodeInfo {
239    /// The external scroll id of this node, used to track
240    /// it between successive re-layouts.
241    pub external_id: ExternalScrollId,
242
243    /// The content rectangle for this scroll node. Also called "scrolling area"
244    /// or "scrollable overflow rectangle".
245    /// <https://www.w3.org/TR/cssom-view-1/#scrolling-area>
246    /// <https://www.w3.org/TR/css-overflow-3/#scrollable-overflow-rectangle>
247    pub content_rect: LayoutRect,
248
249    /// The clip rectange (scrollport) for this scroll node.
250    /// <https://www.w3.org/TR/css-overflow-3/#scrollport>
251    pub clip_rect: LayoutRect,
252
253    /// Whether this `ScrollableNode` is sensitive to input events.
254    pub scroll_sensitivity: AxesScrollSensitivity,
255
256    /// The effective `touch-action` value for this node. The sensitivity above
257    /// is already restricted accordingly (e.g. `pan-x` strips `InputEvents`
258    /// from the y axis), so this field is only consulted to decide the axis
259    /// lock policy at pan-start.
260    pub touch_action: TouchAction,
261
262    /// The current offset of this scroll node.
263    pub offset: LayoutVector2D,
264
265    /// Whether or not the scroll offset of this node has changed and it needs it's
266    /// cached transformations invalidated.
267    pub offset_changed: Cell<bool>,
268}
269
270impl ScrollableNodeInfo {
271    fn scroll_range(&self) -> (LayoutVector2D, LayoutVector2D) {
272        scroll_range_for_scrolling_area_and_scrollport(&self.content_rect, &self.clip_rect)
273    }
274
275    fn scroll_to_offset(
276        &mut self,
277        new_offset: LayoutVector2D,
278        context: ScrollType,
279    ) -> Option<LayoutVector2D> {
280        if !self.scroll_sensitivity.x.contains(context) &&
281            !self.scroll_sensitivity.y.contains(context)
282        {
283            return None;
284        }
285
286        let original_layer_scroll_offset = self.offset;
287        let (min_scroll_range, max_scroll_range) = self.scroll_range();
288        if min_scroll_range.x != max_scroll_range.x && self.scroll_sensitivity.x.contains(context) {
289            self.offset.x = new_offset.x.clamp(min_scroll_range.x, max_scroll_range.x);
290        }
291
292        if min_scroll_range.y != max_scroll_range.y && self.scroll_sensitivity.y.contains(context) {
293            self.offset.y = new_offset.y.clamp(min_scroll_range.y, max_scroll_range.y);
294        }
295
296        if self.offset != original_layer_scroll_offset {
297            self.offset_changed.set(true);
298            Some(self.offset)
299        } else {
300            None
301        }
302    }
303
304    fn scroll_to_webrender_location(
305        &mut self,
306        scroll_location: ScrollLocation,
307        context: ScrollType,
308    ) -> Option<LayoutVector2D> {
309        if !self.scroll_sensitivity.x.contains(context) &&
310            !self.scroll_sensitivity.y.contains(context)
311        {
312            return None;
313        }
314
315        let (min_scroll_range, max_scroll_range) = self.scroll_range();
316        let delta = match scroll_location {
317            ScrollLocation::Delta(delta) => delta,
318            ScrollLocation::Start => {
319                let start = min_scroll_range.y;
320                if self.offset.y.round() <= start {
321                    // Nothing to do on this layer.
322                    return None;
323                }
324
325                self.offset.y = start;
326                self.offset_changed.set(true);
327                return Some(self.offset);
328            },
329            ScrollLocation::End => {
330                let end = max_scroll_range.y;
331                if self.offset.y.round() >= end {
332                    // Nothing to do on this layer.
333                    return None;
334                }
335
336                self.offset.y = end;
337                self.offset_changed.set(true);
338                return Some(self.offset);
339            },
340        };
341
342        self.scroll_to_offset(self.offset + delta, context)
343    }
344}
345
346/// A cached of transforms of a particular [`ScrollTree`] node in both directions:
347/// mapping from node-relative points to root-relative points and vice-versa.
348///
349/// Potential ideas for improvement:
350///  - Test optimizing simple translations to avoid having to do full matrix
351///    multiplication when transforms are not involved.
352#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
353pub struct ScrollTreeNodeTransformationCache {
354    node_to_root_transform: FastLayoutTransform,
355    root_to_node_transform: Option<FastLayoutTransform>,
356    nearest_scrolling_ancestor_offset: LayoutVector2D,
357    nearest_scrolling_ancestor_viewport: LayoutRect,
358    cumulative_sticky_offsets: LayoutVector2D,
359}
360
361#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
362/// A node in a tree of scroll nodes. This may either be a scrollable
363/// node which responds to scroll events or a non-scrollable one.
364pub struct ScrollTreeNode {
365    /// The index of the parent of this node in the tree. If this is
366    /// None then this is the root node.
367    pub parent: Option<ScrollTreeNodeId>,
368
369    /// The children of this [`ScrollTreeNode`].
370    pub children: Vec<ScrollTreeNodeId>,
371
372    /// The WebRender id, which is filled in when this tree is serialiezd
373    /// into a WebRender display list.
374    pub webrender_id: Option<SpatialId>,
375
376    /// Specific information about this node, depending on whether it is a scroll node
377    /// or a reference frame.
378    pub info: SpatialTreeNodeInfo,
379
380    /// Cached transformation information that's used to do things like hit testing
381    /// and viewport bounding box calculation.
382    transformation_cache: Cell<Option<ScrollTreeNodeTransformationCache>>,
383}
384
385impl ScrollTreeNode {
386    /// Get the WebRender [`SpatialId`] for the given [`ScrollNodeId`]. This will
387    /// panic if [`ScrollTree::build_display_list`] has not been called yet.
388    pub fn webrender_id(&self) -> SpatialId {
389        self.webrender_id
390            .expect("Should have called ScrollTree::build_display_list before querying SpatialId")
391    }
392
393    /// Get the external id of this node.
394    pub fn external_id(&self) -> Option<ExternalScrollId> {
395        match self.info {
396            SpatialTreeNodeInfo::Scroll(ref info) => Some(info.external_id),
397            _ => None,
398        }
399    }
400
401    /// Get the offset id of this node if it applies.
402    pub fn offset(&self) -> Option<LayoutVector2D> {
403        match self.info {
404            SpatialTreeNodeInfo::Scroll(ref info) => Some(info.offset),
405            _ => None,
406        }
407    }
408
409    /// Scroll this node given a WebRender ScrollLocation. Returns a tuple that can
410    /// be used to scroll an individual WebRender scroll frame if the operation
411    /// actually changed an offset.
412    fn scroll(
413        &mut self,
414        scroll_location: ScrollLocation,
415        context: ScrollType,
416    ) -> Option<(ExternalScrollId, LayoutVector2D)> {
417        let SpatialTreeNodeInfo::Scroll(ref mut info) = self.info else {
418            return None;
419        };
420
421        info.scroll_to_webrender_location(scroll_location, context)
422            .map(|location| (info.external_id, location))
423    }
424
425    pub fn debug_print(&self, print_tree: &mut PrintTree, node_index: usize) {
426        match &self.info {
427            SpatialTreeNodeInfo::ReferenceFrame(info) => {
428                print_tree.new_level(format!(
429                    "Reference Frame({node_index}): webrender_id={:?}\
430                        \norigin: {:?}\
431                        \ntransform_style: {:?}\
432                        \ntransform: {:?}\
433                        \nkind: {:?}",
434                    self.webrender_id, info.origin, info.transform_style, info.transform, info.kind,
435                ));
436            },
437            SpatialTreeNodeInfo::Scroll(info) => {
438                print_tree.new_level(format!(
439                    "Scroll Frame({node_index}): webrender_id={:?}\
440                        \nexternal_id: {:?}\
441                        \ncontent_rect: {:?}\
442                        \nclip_rect: {:?}\
443                        \nscroll_sensitivity: {:?}\
444                        \noffset: {:?}",
445                    self.webrender_id,
446                    info.external_id,
447                    info.content_rect,
448                    info.clip_rect,
449                    info.scroll_sensitivity,
450                    info.offset,
451                ));
452            },
453            SpatialTreeNodeInfo::Sticky(info) => {
454                print_tree.new_level(format!(
455                    "Sticky Frame({node_index}): webrender_id={:?}\
456                        \nframe_rect: {:?}\
457                        \nmargins: {:?}\
458                        \nhorizontal_offset_bounds: {:?}\
459                        \nvertical_offset_bounds: {:?}",
460                    self.webrender_id,
461                    info.frame_rect,
462                    info.margins,
463                    info.horizontal_offset_bounds,
464                    info.vertical_offset_bounds,
465                ));
466            },
467        };
468    }
469
470    fn invalidate_cached_transforms(&self, scroll_tree: &ScrollTree, ancestors_invalid: bool) {
471        let node_invalid = match &self.info {
472            SpatialTreeNodeInfo::Scroll(info) => info.offset_changed.take(),
473            _ => false,
474        };
475
476        let invalid = node_invalid || ancestors_invalid;
477        if invalid {
478            self.transformation_cache.set(None);
479        }
480
481        for child_id in &self.children {
482            scroll_tree
483                .get_node(*child_id)
484                .invalidate_cached_transforms(scroll_tree, invalid);
485        }
486    }
487}
488
489/// A tree of spatial nodes, which mirrors the spatial nodes in the WebRender
490/// display list, except these are used for scrolling in `Paint` so that
491/// new offsets can be sent to WebRender.
492#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
493pub struct ScrollTree {
494    /// A list of `Paint`-side scroll nodes that describe the tree
495    /// of WebRender spatial nodes, used by `Paint` to scroll the
496    /// contents of the display list.
497    pub nodes: Vec<ScrollTreeNode>,
498}
499
500impl ScrollTree {
501    /// Add a scroll node to this ScrollTree returning the id of the new node.
502    pub fn add_scroll_tree_node(
503        &mut self,
504        parent: Option<ScrollTreeNodeId>,
505        info: SpatialTreeNodeInfo,
506    ) -> ScrollTreeNodeId {
507        self.nodes.push(ScrollTreeNode {
508            parent,
509            children: Vec::new(),
510            webrender_id: None,
511            info,
512            transformation_cache: Cell::default(),
513        });
514
515        let new_node_id = ScrollTreeNodeId {
516            index: self.nodes.len() - 1,
517        };
518
519        if let Some(parent_id) = parent {
520            self.get_node_mut(parent_id).children.push(new_node_id);
521        }
522
523        new_node_id
524    }
525
526    /// Once WebRender display list construction is complete for this [`ScrollTree`], update
527    /// the mapping of nodes to WebRender [`SpatialId`]s.
528    pub fn update_mapping(&mut self, mapping: Vec<SpatialId>) {
529        for (spatial_id, node) in mapping.into_iter().zip(self.nodes.iter_mut()) {
530            node.webrender_id = Some(spatial_id);
531        }
532    }
533
534    /// Get a mutable reference to the node with the given index.
535    pub fn get_node_mut(&mut self, id: ScrollTreeNodeId) -> &mut ScrollTreeNode {
536        &mut self.nodes[id.index]
537    }
538
539    /// Get an immutable reference to the node with the given index.
540    pub fn get_node(&self, id: ScrollTreeNodeId) -> &ScrollTreeNode {
541        &self.nodes[id.index]
542    }
543
544    /// Get the WebRender [`SpatialId`] for the given [`ScrollNodeId`]. This will
545    /// panic if [`ScrollTree::build_display_list`] has not been called yet.
546    pub fn webrender_id(&self, id: ScrollTreeNodeId) -> SpatialId {
547        self.get_node(id).webrender_id()
548    }
549
550    pub fn scroll_node_or_ancestor_inner(
551        &mut self,
552        scroll_node_id: ScrollTreeNodeId,
553        scroll_location: ScrollLocation,
554        context: ScrollType,
555    ) -> Option<(ExternalScrollId, LayoutVector2D)> {
556        let parent = {
557            let node = &mut self.get_node_mut(scroll_node_id);
558            let result = node.scroll(scroll_location, context);
559            if result.is_some() {
560                return result;
561            }
562            node.parent
563        };
564
565        parent
566            .and_then(|parent| self.scroll_node_or_ancestor_inner(parent, scroll_location, context))
567    }
568
569    fn node_with_external_scroll_node_id(
570        &self,
571        external_id: ExternalScrollId,
572    ) -> Option<ScrollTreeNodeId> {
573        self.nodes
574            .iter()
575            .enumerate()
576            .find_map(|(index, node)| match &node.info {
577                SpatialTreeNodeInfo::Scroll(info) if info.external_id == external_id => {
578                    Some(ScrollTreeNodeId { index })
579                },
580                _ => None,
581            })
582    }
583
584    /// Look up the [`TouchAction`] and the structurally scrollable axes
585    /// for the scroll node with the given [`ExternalScrollId`].
586    /// Used by the compositor at pan-start to decide the axis-lock policy.
587    pub fn touch_action_and_scrollable_axes_for(
588        &self,
589        external_id: ExternalScrollId,
590    ) -> Option<(TouchAction, bool, bool)> {
591        let node_id = self.node_with_external_scroll_node_id(external_id)?;
592        let SpatialTreeNodeInfo::Scroll(scroll_node_info) = &self.get_node(node_id).info else {
593            return None;
594        };
595        let (min_scroll_range, max_scroll_range) = scroll_node_info.scroll_range();
596        Some((
597            scroll_node_info.touch_action,
598            min_scroll_range.x != max_scroll_range.x,
599            min_scroll_range.y != max_scroll_range.y,
600        ))
601    }
602
603    /// Scroll the scroll node with the given [`ExternalScrollId`] on this scroll tree. If
604    /// the node cannot be scrolled, because it's already scrolled to the maximum scroll
605    /// extent, try to scroll an ancestor of this node. Returns the node scrolled and the
606    /// new offset if a scroll was performed, otherwise returns None.
607    pub fn scroll_node_or_ancestor(
608        &mut self,
609        external_id: ExternalScrollId,
610        scroll_location: ScrollLocation,
611        context: ScrollType,
612    ) -> Option<(ExternalScrollId, LayoutVector2D)> {
613        let scroll_node_id = self.node_with_external_scroll_node_id(external_id)?;
614        let result = self.scroll_node_or_ancestor_inner(scroll_node_id, scroll_location, context);
615        if result.is_some() {
616            self.invalidate_cached_transforms();
617        }
618        result
619    }
620
621    /// Given an [`ExternalScrollId`] and an offset, update the scroll offset of the scroll node
622    /// with the given id.
623    pub fn set_scroll_offset_for_node_with_external_scroll_id(
624        &mut self,
625        external_scroll_id: ExternalScrollId,
626        offset: LayoutVector2D,
627        context: ScrollType,
628    ) -> Option<LayoutVector2D> {
629        let result = self.nodes.iter_mut().find_map(|node| match node.info {
630            SpatialTreeNodeInfo::Scroll(ref mut scroll_info)
631                if scroll_info.external_id == external_scroll_id =>
632            {
633                scroll_info.scroll_to_offset(offset, context)
634            },
635            _ => None,
636        });
637
638        if result.is_some() {
639            self.invalidate_cached_transforms();
640        }
641
642        result
643    }
644
645    /// Given a set of all scroll offsets coming from the Servo renderer, update all of the offsets
646    /// for nodes that actually exist in this tree.
647    ///
648    /// Returns a map of all scroll offsets which were actually set.
649    pub fn set_all_scroll_offsets(
650        &mut self,
651        offsets: &FxHashMap<ExternalScrollId, LayoutVector2D>,
652    ) -> FxHashMap<ExternalScrollId, LayoutVector2D> {
653        let mut result = FxHashMap::default();
654        for node in self.nodes.iter_mut() {
655            if let SpatialTreeNodeInfo::Scroll(ref mut scroll_info) = node.info &&
656                let Some(offset) = offsets.get(&scroll_info.external_id) &&
657                let Some(result_offset) =
658                    scroll_info.scroll_to_offset(*offset, ScrollType::Script)
659            {
660                result.insert(scroll_info.external_id, result_offset);
661            }
662        }
663
664        if !result.is_empty() {
665            self.invalidate_cached_transforms();
666        }
667
668        result
669    }
670
671    /// Set the offsets of all scrolling nodes in this tree to 0.
672    pub fn reset_all_scroll_offsets(&mut self) {
673        for node in self.nodes.iter_mut() {
674            if let SpatialTreeNodeInfo::Scroll(ref mut scroll_info) = node.info {
675                scroll_info.scroll_to_offset(LayoutVector2D::zero(), ScrollType::Script);
676            }
677        }
678
679        self.invalidate_cached_transforms();
680    }
681
682    /// Collect all of the scroll offsets of the scrolling nodes of this tree into a
683    /// [`HashMap`] which can be applied to another tree.
684    pub fn scroll_offsets(&self) -> FxHashMap<ExternalScrollId, LayoutVector2D> {
685        HashMap::from_iter(self.nodes.iter().filter_map(|node| match node.info {
686            SpatialTreeNodeInfo::Scroll(ref scroll_info) => {
687                Some((scroll_info.external_id, scroll_info.offset))
688            },
689            _ => None,
690        }))
691    }
692
693    /// Get the scroll offset for the given [`ExternalScrollId`] or `None` if that node cannot
694    /// be found in the tree.
695    pub fn scroll_offset(&self, id: ExternalScrollId) -> Option<LayoutVector2D> {
696        self.nodes.iter().find_map(|node| match node.info {
697            SpatialTreeNodeInfo::Scroll(ref info) if info.external_id == id => Some(info.offset),
698            _ => None,
699        })
700    }
701
702    /// Find a transformation that can convert a point in the node coordinate system to a
703    /// point in the root coordinate system.
704    pub fn cumulative_node_to_root_transform(
705        &self,
706        node_id: ScrollTreeNodeId,
707    ) -> FastLayoutTransform {
708        self.cumulative_node_transform(node_id)
709            .node_to_root_transform
710    }
711
712    /// Find a transformation that can convert a point in the root coordinate system to a
713    /// point in the coordinate system of the given node. This may be `None` if the cumulative
714    /// transform is uninvertible.
715    pub fn cumulative_root_to_node_transform(
716        &self,
717        node_id: ScrollTreeNodeId,
718    ) -> Option<FastLayoutTransform> {
719        self.cumulative_node_transform(node_id)
720            .root_to_node_transform
721    }
722
723    /// Find the untransformed offset in the initial containing block of the nearest
724    /// inclusive ancestor reference frame for the given spatial tree node.
725    pub fn reference_frame_offset(&self, node_id: ScrollTreeNodeId) -> LayoutPoint {
726        let mut maybe_node_id = Some(node_id);
727        while let Some(node_id) = maybe_node_id {
728            let node = self.get_node(node_id);
729            if let SpatialTreeNodeInfo::ReferenceFrame(reference_frame) = &node.info {
730                return reference_frame.frame_origin_for_query;
731            }
732            maybe_node_id = node.parent;
733        }
734        Default::default()
735    }
736
737    /// Find the cumulative offsets of sticky positioned boxes from the given node up to
738    /// the root.
739    pub fn cumulative_sticky_offsets(&self, node_id: ScrollTreeNodeId) -> LayoutVector2D {
740        self.cumulative_node_transform(node_id)
741            .cumulative_sticky_offsets
742    }
743
744    #[servo_tracing::instrument(name = "ScrollTree::cumulative_node_transform", skip_all)]
745    fn cumulative_node_transform(
746        &self,
747        node_id: ScrollTreeNodeId,
748    ) -> ScrollTreeNodeTransformationCache {
749        let node = self.get_node(node_id);
750        if let Some(cached_transforms) = node.transformation_cache.get() {
751            return cached_transforms;
752        }
753
754        let transforms = self.cumulative_node_transform_inner(node);
755        node.transformation_cache.set(Some(transforms));
756        transforms
757    }
758
759    /// This is a replication of WebRender's code for determining the transform to use for
760    /// a reference frame which takes into account perspective frames that scroll relative
761    /// to different scroll frames.
762    fn reference_frame_transform(
763        &self,
764        node: &ScrollTreeNode,
765        info: &ReferenceFrameNodeInfo,
766        cumulative_sticky_offset: LayoutVector2D,
767    ) -> FastLayoutTransform {
768        let ReferenceFrameKind::Perspective {
769            scrolling_relative_to: Some(scrolling_relative_to),
770        } = &info.kind
771        else {
772            return info.transform;
773        };
774
775        let mut scroll_offset = LayoutVector2D::zero();
776        let mut current_node = node;
777        let mut ending_cumulative_sticky_offset = LayoutVector2D::zero();
778
779        while let Some(parent_id) = current_node.parent {
780            let parent_node = self.get_node(parent_id);
781            if let SpatialTreeNodeInfo::Scroll(parent_info) = &parent_node.info {
782                if parent_info.external_id == *scrolling_relative_to {
783                    ending_cumulative_sticky_offset = self.cumulative_sticky_offsets(parent_id);
784                    break;
785                }
786                scroll_offset += parent_info.offset;
787            }
788            current_node = parent_node;
789        }
790
791        scroll_offset -= cumulative_sticky_offset - ending_cumulative_sticky_offset;
792        info.transform
793            .pre_translate(-scroll_offset)
794            .then_translate(scroll_offset)
795    }
796
797    /// Traverse a scroll node to its root to calculate the transform.
798    #[servo_tracing::instrument(name = "ScrollTree::cumulative_node_transform_inner", skip_all)]
799    fn cumulative_node_transform_inner(
800        &self,
801        node: &ScrollTreeNode,
802    ) -> ScrollTreeNodeTransformationCache {
803        let parent_transforms = node
804            .parent
805            .map(|parent_id| self.cumulative_node_transform(parent_id))
806            .unwrap_or_default();
807
808        let node_to_root_transform = |node_to_parent_transform: FastLayoutTransform| {
809            node_to_parent_transform.then(&parent_transforms.node_to_root_transform)
810        };
811        let root_to_node_transform = |parent_to_node_transform: FastLayoutTransform| {
812            parent_transforms
813                .root_to_node_transform
814                .map_or(parent_to_node_transform, |parent_transform| {
815                    parent_transform.then(&parent_to_node_transform)
816                })
817        };
818
819        match &node.info {
820            SpatialTreeNodeInfo::ReferenceFrame(info) => {
821                // To apply a transformation we need to make sure the rectangle's
822                // coordinate space is the same as reference frame's coordinate space.
823                let offset = info.frame_origin_for_query.to_vector();
824                let transform = self.reference_frame_transform(
825                    node,
826                    info,
827                    parent_transforms.cumulative_sticky_offsets,
828                );
829                let node_to_parent_transform =
830                    transform.pre_translate(-offset).then_translate(offset);
831                let parent_to_node_transform = transform.inverse().map(|inverse_transform| {
832                    FastLayoutTransform::Offset(-info.origin.to_vector()).then(&inverse_transform)
833                });
834                ScrollTreeNodeTransformationCache {
835                    node_to_root_transform: node_to_root_transform(node_to_parent_transform),
836                    root_to_node_transform: parent_to_node_transform.map(root_to_node_transform),
837                    nearest_scrolling_ancestor_viewport: parent_transforms
838                        .nearest_scrolling_ancestor_viewport
839                        .translate(-info.origin.to_vector()),
840                    nearest_scrolling_ancestor_offset: parent_transforms
841                        .nearest_scrolling_ancestor_offset,
842                    cumulative_sticky_offsets: parent_transforms.cumulative_sticky_offsets,
843                }
844            },
845            SpatialTreeNodeInfo::Scroll(info) => {
846                let node_to_parent_transform = FastLayoutTransform::Offset(-info.offset);
847                let parent_to_node_transform = node_to_parent_transform.inverse();
848                ScrollTreeNodeTransformationCache {
849                    node_to_root_transform: node_to_root_transform(node_to_parent_transform),
850                    root_to_node_transform: parent_to_node_transform.map(root_to_node_transform),
851                    nearest_scrolling_ancestor_viewport: info.clip_rect,
852                    nearest_scrolling_ancestor_offset: -info.offset,
853                    cumulative_sticky_offsets: parent_transforms.cumulative_sticky_offsets,
854                }
855            },
856
857            SpatialTreeNodeInfo::Sticky(info) => {
858                let offset = info.calculate_sticky_offset(
859                    &parent_transforms.nearest_scrolling_ancestor_offset,
860                    &parent_transforms.nearest_scrolling_ancestor_viewport,
861                );
862                let node_to_parent_transform = FastLayoutTransform::Offset(offset);
863                let parent_to_node_transform = node_to_parent_transform.inverse();
864                ScrollTreeNodeTransformationCache {
865                    node_to_root_transform: node_to_root_transform(node_to_parent_transform),
866                    root_to_node_transform: parent_to_node_transform.map(root_to_node_transform),
867                    nearest_scrolling_ancestor_viewport: parent_transforms
868                        .nearest_scrolling_ancestor_viewport,
869                    nearest_scrolling_ancestor_offset: parent_transforms
870                        .nearest_scrolling_ancestor_offset +
871                        offset,
872                    cumulative_sticky_offsets: parent_transforms.cumulative_sticky_offsets + offset,
873                }
874            },
875        }
876    }
877
878    #[servo_tracing::instrument(name = "ScrollTree::invalidate_cached_transforms", skip_all)]
879    fn invalidate_cached_transforms(&self) {
880        let Some(root_node) = self.nodes.first() else {
881            return;
882        };
883        root_node.invalidate_cached_transforms(self, false /* ancestors_invalid */);
884    }
885
886    fn external_scroll_id_for_scroll_tree_node(
887        &self,
888        id: ScrollTreeNodeId,
889    ) -> Option<ExternalScrollId> {
890        let mut maybe_node = Some(self.get_node(id));
891
892        while let Some(node) = maybe_node {
893            if let Some(external_scroll_id) = node.external_id() {
894                return Some(external_scroll_id);
895            }
896            maybe_node = node.parent.map(|id| self.get_node(id));
897        }
898
899        None
900    }
901}
902
903/// In order to pretty print the [ScrollTree] structure, we are converting
904/// the node list inside the tree to be a adjacency list. The adjacency list
905/// then is used for the [ScrollTree::debug_print_traversal] of the tree.
906///
907/// This preprocessing helps decouples print logic a lot from its construction.
908type AdjacencyListForPrint = Vec<Vec<ScrollTreeNodeId>>;
909
910/// Implementation of [ScrollTree] that is related to debugging.
911// FIXME: probably we could have a universal trait for this. Especially for
912//        structures that utilizes PrintTree.
913impl ScrollTree {
914    fn nodes_in_adjacency_list(&self) -> AdjacencyListForPrint {
915        let mut adjacency_list: AdjacencyListForPrint = vec![Default::default(); self.nodes.len()];
916
917        for (node_index, node) in self.nodes.iter().enumerate() {
918            let current_id = ScrollTreeNodeId { index: node_index };
919            if let Some(parent_id) = node.parent {
920                adjacency_list[parent_id.index].push(current_id);
921            }
922        }
923
924        adjacency_list
925    }
926
927    fn debug_print_traversal(
928        &self,
929        print_tree: &mut PrintTree,
930        current_id: ScrollTreeNodeId,
931        adjacency_list: &[Vec<ScrollTreeNodeId>],
932    ) {
933        for node_id in &adjacency_list[current_id.index] {
934            self.nodes[node_id.index].debug_print(print_tree, node_id.index);
935            self.debug_print_traversal(print_tree, *node_id, adjacency_list);
936        }
937        print_tree.end_level();
938    }
939
940    /// Print the [ScrollTree]. Particularly, we are printing the node in
941    /// preorder traversal. The order of the nodes will depends of the
942    /// index of a node in the [ScrollTree] which corresponds to the
943    /// declarations of the nodes.
944    // TODO(stevennovaryo): add information about which fragment that
945    //                      defines this node.
946    pub fn debug_print(&self) {
947        let mut print_tree = PrintTree::new("Scroll Tree");
948
949        let adj_list = self.nodes_in_adjacency_list();
950        let root_id = ScrollTreeNodeId { index: 0 };
951
952        self.nodes[root_id.index].debug_print(&mut print_tree, root_id.index);
953        self.debug_print_traversal(&mut print_tree, root_id, &adj_list);
954        print_tree.end_level();
955    }
956}
957
958/// A bitflags set that represents the paint timing report for a display list.
959///
960/// <https://www.w3.org/TR/paint-timing/#set-of-previously-reported-paints>
961/// Note: Analogous to the document's "set of previously reported paints". It
962/// is produced by layout's `mark paint timing` as the report for the current
963/// display list. In the specification this is an ordered set of paint-type
964/// strings (`"first-paint"`,`"first-contentful-paint"`).
965#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
966pub struct PaintTimingReport(u8);
967
968bitflags! {
969    impl PaintTimingReport: u8 {
970        /// Report first paint (the spec's `"first-paint"`).
971        const FirstPaint = 1 << 0;
972        /// Report first contentful paint (the spec's `"first-contentful-paint"`).
973        const FirstContentfulPaint = 1 << 1;
974    }
975}
976
977/// <https://www.w3.org/TR/paint-timing/#paint-timing-info>
978#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
979pub struct PaintTimingInfo {
980    /// <https://w3c.github.io/paint-timing/#paint-timing-info-rendering-update-end-time>
981    pub rendering_update_end_time: CrossProcessInstant,
982    /// <https://w3c.github.io/paint-timing/#paint-timing-info-implementation-defined-presentation-time>
983    pub implementation_defined_presentation_time: Option<CrossProcessInstant>,
984}
985
986impl PaintTimingInfo {
987    pub fn now() -> Self {
988        Self {
989            rendering_update_end_time: CrossProcessInstant::now(),
990            implementation_defined_presentation_time: None,
991        }
992    }
993
994    /// Return a copy of this [`PaintTimingInfo`] with its implementation-defined
995    /// presentation time set to `presentation_time`.
996    pub fn with_presentation_time(self, presentation_time: CrossProcessInstant) -> Self {
997        Self {
998            implementation_defined_presentation_time: Some(presentation_time),
999            ..self
1000        }
1001    }
1002
1003    /// <https://www.w3.org/TR/paint-timing/#dom-painttimingmixin-painttime>
1004    pub fn paint_time(&self) -> CrossProcessInstant {
1005        // The `paintTime` attribute's getter step is to return this's paint
1006        // timing info's rendering update end time.
1007        self.rendering_update_end_time
1008    }
1009
1010    /// <https://www.w3.org/TR/paint-timing/#dom-painttimingmixin-presentationtime>
1011    pub fn presentation_time(&self) -> Option<CrossProcessInstant> {
1012        // The `presentationTime` attribute's getter step, if it exists, is to
1013        // return this's paint timing info's implementation-defined
1014        // presentation time.
1015        self.implementation_defined_presentation_time
1016    }
1017
1018    /// <https://www.w3.org/TR/paint-timing/#default-paint-timestamp>
1019    pub fn default_paint_timestamp(&self) -> CrossProcessInstant {
1020        // Return paintTimingInfo's implementation-defined presentation time if
1021        // it is non-null, otherwise paintTimingInfo's rendering update end time.
1022        self.implementation_defined_presentation_time
1023            .unwrap_or(self.rendering_update_end_time)
1024    }
1025}
1026
1027/// A data structure which stores `Paint`-side information about
1028/// display lists sent to `Paint`.
1029#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
1030pub struct PaintDisplayListInfo {
1031    /// The WebRender [PipelineId] of this display list.
1032    pub pipeline_id: PipelineId,
1033
1034    /// A map of `<iframe>` [`PipelineId`]s to their rectangle and containing [`ScrollTreeNodeId`].
1035    /// This can be used to translate from coordinates within an `<iframe>` to root WebView
1036    /// coordinates.
1037    pub iframes: FxHashMap<PipelineId, (ScrollTreeNodeId, LayoutRect)>,
1038
1039    /// The [`ViewportDetails`] that describe the viewport in the script/layout thread at
1040    /// the time this display list was created.
1041    pub viewport_details: ViewportDetails,
1042
1043    /// The size of this display list's content.
1044    pub content_size: LayoutSize,
1045
1046    /// The epoch of the display list.
1047    pub epoch: Epoch,
1048
1049    /// A ScrollTree used by `Paint` to scroll the contents of the
1050    /// display list.
1051    pub scroll_tree: ScrollTree,
1052
1053    /// The `ScrollTreeNodeId` of the root reference frame of this info's scroll
1054    /// tree.
1055    pub root_reference_frame_id: ScrollTreeNodeId,
1056
1057    /// The `ScrollTreeNodeId` of the topmost scrolling frame of this info's scroll
1058    /// tree.
1059    pub root_scroll_node_id: ScrollTreeNodeId,
1060
1061    /// Whether the first layout or a subsequent (incremental) layout triggered this
1062    /// display list creation.
1063    pub first_reflow: bool,
1064
1065    /// The paint-timing report for this display list.
1066    pub paint_timing_report: PaintTimingReport,
1067
1068    /// The [`PaintTimingInfo`] for this display list.
1069    pub paint_timing_info: PaintTimingInfo,
1070
1071    /// New largest-contentful-paint candidate in this display list, if any.
1072    /// The pair is the candidate's id and its reported area.
1073    pub lcp_candidate: Option<(LCPCandidateID, usize)>,
1074
1075    /// The Container Timing updates produced by this display list, if any. Only the IDs
1076    /// travel here: the records themselves go straight from layout to script, and paint's
1077    /// sole job is to hand these IDs back once the frame has actually been composited.
1078    /// <https://wicg.github.io/container-timing/>
1079    pub container_timing_candidates: Vec<ContainerTimingID>,
1080
1081    /// If this display list contains a blinking caret, this value will be filled with its animation
1082    /// key and original color value so that the painter can animate the caret.
1083    pub caret_property_binding: Option<(PropertyBindingKey<ColorF>, ColorF)>,
1084}
1085
1086impl PaintDisplayListInfo {
1087    /// Create a new PaintDisplayListInfo with the root reference frame
1088    /// and scroll frame already added to the scroll tree.
1089    pub fn new(
1090        viewport_details: ViewportDetails,
1091        content_rect: LayoutRect,
1092        pipeline_id: PipelineId,
1093        epoch: Epoch,
1094        viewport_scroll_sensitivity: AxesScrollSensitivity,
1095        first_reflow: bool,
1096    ) -> Self {
1097        let mut scroll_tree = ScrollTree::default();
1098        let root_reference_frame_id = scroll_tree.add_scroll_tree_node(
1099            None,
1100            SpatialTreeNodeInfo::ReferenceFrame(ReferenceFrameNodeInfo {
1101                origin: Default::default(),
1102                frame_origin_for_query: Default::default(),
1103                transform_style: TransformStyle::Flat,
1104                transform: FastLayoutTransform::identity(),
1105                kind: ReferenceFrameKind::default(),
1106            }),
1107        );
1108        let root_scroll_node_id = scroll_tree.add_scroll_tree_node(
1109            Some(root_reference_frame_id),
1110            SpatialTreeNodeInfo::Scroll(ScrollableNodeInfo {
1111                external_id: ExternalScrollId(0, pipeline_id),
1112                content_rect,
1113                clip_rect: LayoutRect::from_origin_and_size(
1114                    LayoutPoint::zero(),
1115                    viewport_details.layout_size(),
1116                ),
1117                scroll_sensitivity: viewport_scroll_sensitivity,
1118                touch_action: TouchAction::Auto,
1119                offset: LayoutVector2D::zero(),
1120                offset_changed: Cell::new(false),
1121            }),
1122        );
1123
1124        PaintDisplayListInfo {
1125            pipeline_id,
1126            iframes: Default::default(),
1127            viewport_details,
1128            content_size: content_rect.size(),
1129            epoch,
1130            scroll_tree,
1131            root_reference_frame_id,
1132            root_scroll_node_id,
1133            first_reflow,
1134            lcp_candidate: None,
1135            container_timing_candidates: Vec::new(),
1136            paint_timing_report: PaintTimingReport::default(),
1137            paint_timing_info: PaintTimingInfo::now(),
1138            caret_property_binding: Default::default(),
1139        }
1140    }
1141
1142    /// Find the [`ExternalScrollId`] of the scroll node identified by the given
1143    /// [`ScrollTreeNodeId`]. This will walk up the tree to find the first inclusive
1144    /// ancestor scroll node.
1145    pub fn external_scroll_id_for_scroll_tree_node(
1146        &self,
1147        id: ScrollTreeNodeId,
1148    ) -> ExternalScrollId {
1149        self.scroll_tree
1150            .external_scroll_id_for_scroll_tree_node(id)
1151            .unwrap_or(ExternalScrollId(0, self.pipeline_id))
1152    }
1153}