1use 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#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
32pub struct ScrollType(u8);
33
34bitflags! {
35 impl ScrollType: u8 {
36 const InputEvents = 1 << 0;
39 const Script = 1 << 1;
41 const Touch = 1 << 2;
45 }
46}
47
48impl 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#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
63pub struct AxesScrollSensitivity {
64 pub x: ScrollType,
65 pub y: ScrollType,
66}
67
68#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
74pub enum TouchAction {
75 Auto,
79 PanX,
82 PanY,
85 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 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 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 sticky_offset.y = top_viewport_edge - sticky_rect.min.y;
155 }
156 }
157
158 if sticky_offset.y <= 0.0 &&
163 let Some(margin) = self.margins.bottom
164 {
165 sticky_rect.min.y += sticky_offset.y;
171 sticky_rect.max.y += sticky_offset.y;
172
173 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 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 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 pub frame_origin_for_query: LayoutPoint,
218 pub transform_style: TransformStyle,
219 pub transform: FastLayoutTransform,
220 pub kind: ReferenceFrameKind,
221}
222
223pub 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#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
238pub struct ScrollableNodeInfo {
239 pub external_id: ExternalScrollId,
242
243 pub content_rect: LayoutRect,
248
249 pub clip_rect: LayoutRect,
252
253 pub scroll_sensitivity: AxesScrollSensitivity,
255
256 pub touch_action: TouchAction,
261
262 pub offset: LayoutVector2D,
264
265 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 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 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#[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)]
362pub struct ScrollTreeNode {
365 pub parent: Option<ScrollTreeNodeId>,
368
369 pub children: Vec<ScrollTreeNodeId>,
371
372 pub webrender_id: Option<SpatialId>,
375
376 pub info: SpatialTreeNodeInfo,
379
380 transformation_cache: Cell<Option<ScrollTreeNodeTransformationCache>>,
383}
384
385impl ScrollTreeNode {
386 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 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 pub fn offset(&self) -> Option<LayoutVector2D> {
403 match self.info {
404 SpatialTreeNodeInfo::Scroll(ref info) => Some(info.offset),
405 _ => None,
406 }
407 }
408
409 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#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
493pub struct ScrollTree {
494 pub nodes: Vec<ScrollTreeNode>,
498}
499
500impl ScrollTree {
501 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 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 pub fn get_node_mut(&mut self, id: ScrollTreeNodeId) -> &mut ScrollTreeNode {
536 &mut self.nodes[id.index]
537 }
538
539 pub fn get_node(&self, id: ScrollTreeNodeId) -> &ScrollTreeNode {
541 &self.nodes[id.index]
542 }
543
544 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 );
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
903type AdjacencyListForPrint = Vec<Vec<ScrollTreeNodeId>>;
909
910impl 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 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#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
966pub struct PaintTimingReport(u8);
967
968bitflags! {
969 impl PaintTimingReport: u8 {
970 const FirstPaint = 1 << 0;
972 const FirstContentfulPaint = 1 << 1;
974 }
975}
976
977#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
979pub struct PaintTimingInfo {
980 pub rendering_update_end_time: CrossProcessInstant,
982 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 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 pub fn paint_time(&self) -> CrossProcessInstant {
1005 self.rendering_update_end_time
1008 }
1009
1010 pub fn presentation_time(&self) -> Option<CrossProcessInstant> {
1012 self.implementation_defined_presentation_time
1016 }
1017
1018 pub fn default_paint_timestamp(&self) -> CrossProcessInstant {
1020 self.implementation_defined_presentation_time
1023 .unwrap_or(self.rendering_update_end_time)
1024 }
1025}
1026
1027#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
1030pub struct PaintDisplayListInfo {
1031 pub pipeline_id: PipelineId,
1033
1034 pub iframes: FxHashMap<PipelineId, (ScrollTreeNodeId, LayoutRect)>,
1038
1039 pub viewport_details: ViewportDetails,
1042
1043 pub content_size: LayoutSize,
1045
1046 pub epoch: Epoch,
1048
1049 pub scroll_tree: ScrollTree,
1052
1053 pub root_reference_frame_id: ScrollTreeNodeId,
1056
1057 pub root_scroll_node_id: ScrollTreeNodeId,
1060
1061 pub first_reflow: bool,
1064
1065 pub paint_timing_report: PaintTimingReport,
1067
1068 pub paint_timing_info: PaintTimingInfo,
1070
1071 pub lcp_candidate: Option<(LCPCandidateID, usize)>,
1074
1075 pub container_timing_candidates: Vec<ContainerTimingID>,
1080
1081 pub caret_property_binding: Option<(PropertyBindingKey<ColorF>, ColorF)>,
1084}
1085
1086impl PaintDisplayListInfo {
1087 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 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}