Truly independent web browser
LibCompositing+LibWeb+Compositor: Composite every frame from tiles
Aliaksandr Kalenikbbb0a6cdf53b
diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex 937f4bbee5f..1e6d3c4089d 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -409,8 +409,6 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiCompositorAnimationPublishOutcome","FfiVisualAnimationSummary","FfiRasterPainter",- "RecordSpan",- "FfiReplaySelection","FfiEasingDescriptor","FfiEasingKind","FfiLinearEasingPoint",diff --git a/Libraries/LibCompositing/Rust/src/display_list/animated_content.rs b/Libraries/LibCompositing/Rust/src/display_list/animated_content.rsnew file mode 100644index 00000000000..a8ecdb49617--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/animated_content.rs@@ -0,0 +1,267 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Whether what the animations of a visual context tree move can reach the viewport.++use super::replay::{OwnSpaceClipExtent, own_space_clip_extent};+use super::storage::DisplayListStorage;+use crate::display_list::builder::{+ bounding_rect_computed_from_payload, for_each_command, has_inline_clip_in_its_own_space, inline_clips_of,+};+use crate::display_list::commands::{EffectNodeIndex, SpatialNodeIndex};+use crate::host::FfiAnimatedContentViewportEffect;+use crate::visual_context::{EffectNodeData, VisualContextTree, WorldTransforms};+use libgfx_rust::{FloatMatrix4x4, FloatPoint, IntRect};+use std::cell::OnceCell;++/// Whether the content the tree's animations move at `sample_time_ns` can reach the viewport. The+/// finished animations keep their final values in place; the running ones must all be opacity or+/// plane rotations, whose extents the bounds query can replace, for the answer to be anything but+/// yes. The answer is cached until scene geometry or scrolling changes, and bounding rotating+/// content deliberately ignores clips, so no animation phase can reveal pixels outside the bounds.+pub fn animated_content_may_affect_viewport_at(+ display_list: &DisplayListStorage,+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+ sample_time_ns: i64,+) -> FfiAnimatedContentViewportEffect {+ let extents = tree.visual_animation_extents_at(sample_time_ns);+ if !extents.all_running_animations_are_bounded {+ return FfiAnimatedContentViewportEffect {+ may_affect_viewport: true,+ stable_until_scene_changes: false,+ };+ }+ let may_affect_viewport_with_tree = |tree: &VisualContextTree| {+ animated_content_may_affect_viewport(+ display_list,+ tree,+ scroll_offsets,+ &extents.rotation_nodes,+ &extents.opacity_nodes,+ viewport_rect,+ )+ };+ let may_affect_viewport = if extents.has_finished_animation {+ may_affect_viewport_with_tree(&tree.with_visual_animation_samples(sample_time_ns))+ } else {+ may_affect_viewport_with_tree(tree)+ };+ FfiAnimatedContentViewportEffect {+ may_affect_viewport,+ stable_until_scene_changes: !extents.has_unfinished_finite_animation,+ }+}++pub fn animated_content_may_affect_viewport(+ display_list: &DisplayListStorage,+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ rotation_nodes: &[SpatialNodeIndex],+ opacity_nodes: &[EffectNodeIndex],+ viewport_rect: IntRect,+) -> bool {+ let is_in_rotating_subtree_by_spatial_node = tree.spatial_nodes_in_subtrees_of(rotation_nodes);+ let mut is_rotation_node_by_spatial_node = vec![false; tree.spatial_nodes.len()];+ for node in rotation_nodes {+ let Some(is_rotation_node) = is_rotation_node_by_spatial_node.get_mut(node.0 as usize) else {+ return true;+ };+ *is_rotation_node = true;+ }+ let world_made_on_first_use = OnceCell::new();+ let mut may_affect_viewport = false;+ for chunk in display_list.chunks() {+ let records = chunk.records();+ for run in chunk.runs() {+ let run_bytes = &records[run.offset as usize..(run.offset + run.size) as usize];+ for_each_command(run_bytes, |header, _, payload| {+ if may_affect_viewport || header.command_type.is_compositor_metadata() {+ return;+ }+ let spatial_is_animated = is_in_rotating_subtree_by_spatial_node[run.context.spatial.0 as usize];+ let has_inline_clip_in_its_own_space =+ header.inline_clip_count != 0 && has_inline_clip_in_its_own_space(header, payload);+ if has_inline_clip_in_its_own_space+ && !spatial_is_animated+ && inline_clips_of(header, payload).any(|inline_clip| {+ inline_clip.has_own_space+ && is_in_rotating_subtree_by_spatial_node+ .get(inline_clip.space.0 as usize)+ .is_none_or(|is_animated| *is_animated)+ })+ {+ may_affect_viewport = true;+ return;+ }+ let mut clip = run.context.clip;+ while !clip.is_none() {+ let node = &tree.clip_nodes[clip.0 as usize];+ if !spatial_is_animated && is_in_rotating_subtree_by_spatial_node[node.spatial.0 as usize] {+ may_affect_viewport = true;+ return;+ }+ clip = node.parent;+ }+ let mut effect = run.context.effect;+ let mut opacity_is_animated = false;+ let mut filter_can_draw_past_record_bounds = false;+ while !effect.is_none() {+ let node = &tree.effect_nodes[effect.0 as usize];+ opacity_is_animated |= opacity_nodes.contains(&effect);+ if !spatial_is_animated && is_in_rotating_subtree_by_spatial_node[node.spatial.0 as usize] {+ may_affect_viewport = true;+ return;+ }+ if let EffectNodeData::Effects(effects) = &node.data+ && (effects.filter.is_some() || effects.backdrop_filter.is_some())+ {+ filter_can_draw_past_record_bounds = true;+ }+ effect = node.parent;+ }+ if !spatial_is_animated && !opacity_is_animated {+ return;+ }+ if filter_can_draw_past_record_bounds {+ may_affect_viewport = true;+ return;+ }+ let bounding_rect = bounding_rect_computed_from_payload(header, payload);+ let mut rect = bounding_rect.unwrap_or_default().to_float();+ if has_inline_clip_in_its_own_space && bounding_rect.is_some() {+ let world = world_made_on_first_use+ .get_or_init(|| WorldTransforms::new(tree, scroll_offsets, Some(FloatMatrix4x4::identity())));+ if let Some(command_to_root) = world.draw_matrix_if_known(run.context.spatial)+ && let Some(OwnSpaceClipExtent::Within(clipped_rect)) =+ own_space_clip_extent(header, payload, rect, command_to_root, |space| {+ world.draw_matrix_if_known(space)+ })+ {+ if clipped_rect.is_empty() {+ return;+ }+ rect = clipped_rect;+ }+ }+ let Some(bounds) = tree.rect_with_rotation_bounds_to_viewport(+ run.context.spatial,+ rect,+ &is_rotation_node_by_spatial_node,+ scroll_offsets,+ ) else {+ may_affect_viewport = true;+ return;+ };+ let bounds = bounds.inflated(2.0, 2.0);+ may_affect_viewport = bounds.x <= viewport_rect.right() as f32+ && bounds.right() >= viewport_rect.x as f32+ && bounds.y <= viewport_rect.bottom() as f32+ && bounds.bottom() >= viewport_rect.y as f32;+ });+ }+ }+ may_affect_viewport+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::builder::{DisplayListBuilder, PendingInlineClip};+ use crate::display_list::commands::{ContextRef, FillRect, VISUAL_VIEWPORT_NODE_INDEX};+ use crate::node_slot_id::NodeSlotId;+ use crate::visual_context::{+ ClipNodeIndex, EffectsData, ScrollData, SpatialData, TransformData, TransformDataRole,+ };+ use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatRect};++ fn transform(matrix: FloatMatrix4x4) -> TransformData {+ TransformData {+ matrix,+ origin: FloatPoint::default(),+ sorting_context_root_index: None,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: false,+ bounds: FloatRect::default(),+ }+ }++ #[test]+ fn animated_content_follows_inline_clips_in_spaces_of_their_own() {+ let mut tree = VisualContextTree::create(transform(FloatMatrix4x4::identity()));+ let scroll = tree.append_spatial(+ SpatialData::Scroll(ScrollData {+ state_slot: 1,+ owner_paintable: NodeSlotId::INVALID,+ }),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ let rotating = tree.append_spatial(+ SpatialData::Transform(transform(FloatMatrix4x4::identity())),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ let effect = tree.append_effect(+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 0.5,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: None,+ }),+ EffectNodeIndex::NONE,+ VISUAL_VIEWPORT_NODE_INDEX,+ ClipNodeIndex::NONE,+ );+ let viewport = IntRect::new(0, 0, 800, 600);+ let draw_clipped_to = |clip_space: SpatialNodeIndex, clip_rect: IntRect, context: ContextRef| {+ let mut builder = DisplayListBuilder::new();+ builder.append_with_inline_clips(+ &FillRect {+ rect: viewport,+ color: Color::from_rgb(255, 0, 0),+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ },+ &[],+ context,+ &[PendingInlineClip::intersecting_float_rect(clip_rect.to_float()).in_space(clip_space)],+ );+ DisplayListStorage::of_builder(&builder)+ };+ let may_affect_viewport = |display_list: &DisplayListStorage, rotation_nodes: &[SpatialNodeIndex]| {+ animated_content_may_affect_viewport(+ display_list,+ &tree,+ &[FloatPoint::default(), FloatPoint::default()],+ rotation_nodes,+ &[effect],+ viewport,+ )+ };+ let faded = ContextRef {+ effect,+ ..ContextRef::default()+ };++ // An animated opacity only affects the viewport where the clip lets the draw show.+ let box_on_screen = IntRect::new(0, 10, 10, 10);+ let box_off_screen = IntRect::new(0, 2000, 10, 10);+ assert!(may_affect_viewport(&draw_clipped_to(scroll, box_on_screen, faded), &[]));+ assert!(!may_affect_viewport(+ &draw_clipped_to(scroll, box_off_screen, faded),+ &[]+ ));++ // A clip in a rotating space moves the draw it clips, though the draw's own space stands still.+ assert!(may_affect_viewport(+ &draw_clipped_to(rotating, box_on_screen, ContextRef::default()),+ &[rotating]+ ));+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/animated_transform_spaces.rs b/Libraries/LibCompositing/Rust/src/display_list/animated_transform_spaces.rsnew file mode 100644index 00000000000..896deb82191--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/animated_transform_spaces.rs@@ -0,0 +1,501 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The raster spaces at spatial nodes whose transform the compositor animates: which nodes get one, the scale their+//! content is rastered at, and where that content can show around the node wherever the animation takes it.++use crate::display_list::commands::{EffectNodeIndex, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX};+use crate::display_list::placement::ValuesFoldedDownSpatialChains;+use crate::easing::Easing;+use crate::host::{FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};+use crate::visual_animation::{VisualAnimation, VisualAnimationTransformOperation, VisualAnimationValue};+use crate::visual_context::{EffectNodeData, SpatialData, VisualContextTree};+use libgfx_rust::{FloatMatrix4x4, FloatRect};++pub const MAXIMUM_ANIMATED_TRANSFORM_SPACE_COUNT: usize = 32;+const LARGEST_RASTER_SCALE_PAST_PARENT_SCALE: f32 = 4.0;+pub(crate) const SMALLEST_RASTER_SCALE: f32 = 1.0 / 64.0;+const RASTER_SCALE_STEPS_PER_UNIT: f32 = 64.0;++fn transform_animations_of(tree: &VisualContextTree) -> impl Iterator<Item = &VisualAnimation> {+ tree.visual_animations()+ .iter()+ .filter(|animation| animation.target_kind == FfiVisualAnimationTargetKind::Transform)+}++/// The nodes whose transform the compositor animates that `is_root` takes.+pub(crate) fn roots_of_transform_animations(+ tree: &VisualContextTree,+ is_root: impl Fn(SpatialNodeIndex) -> bool,+) -> impl Iterator<Item = SpatialNodeIndex> {+ transform_animations_of(tree)+ .flat_map(|animation| animation.node_indices.iter().map(|&index| SpatialNodeIndex(index)))+ .filter(move |&node| is_root(node))+}++/// Per spatial node, whether it is or is under a node whose transform the compositor animates that `is_root` takes, or+/// empty where it takes none.+pub(crate) fn spatial_nodes_under_transform_animations(+ tree: &VisualContextTree,+ is_root: impl Fn(SpatialNodeIndex) -> bool,+) -> Vec<bool> {+ let roots: Vec<SpatialNodeIndex> = roots_of_transform_animations(tree, is_root).collect();+ if roots.is_empty() {+ return Vec::new();+ }+ tree.spatial_nodes_in_subtrees_of(&roots)+}++fn matrix_of_operations(operations: &[VisualAnimationTransformOperation]) -> FloatMatrix4x4 {+ operations.iter().fold(FloatMatrix4x4::identity(), |matrix, operation| {+ matrix.multiplied(operation.to_matrix())+ })+}++fn transform_keyframe_matrices(animation: &VisualAnimation) -> impl Iterator<Item = FloatMatrix4x4> + '_ {+ animation.keyframes.iter().filter_map(|keyframe| match &keyframe.value {+ VisualAnimationValue::Transform(operations) => Some(matrix_of_operations(operations)),+ _ => None,+ })+}++/// Whether every sample of a transform animation keeps what it transforms in the plane, so that its samples are 2D+/// affine. A sample interpolates the values of each operation of two keyframes, so each operation has to stay in the+/// plane at every keyframe, and a rotation out of the plane has to keep its angle, as one between two angles that stay+/// in the plane can leave it.+pub fn transform_animation_stays_in_plane(animation: &VisualAnimation) -> bool {+ use FfiVisualAnimationTransformOperationKind as Kind;+ let Some(operations_of_keyframes) = animation+ .keyframes+ .iter()+ .map(|keyframe| match &keyframe.value {+ VisualAnimationValue::Transform(operations) => Some(operations.as_slice()),+ _ => None,+ })+ .collect::<Option<Vec<_>>>()+ else {+ return false;+ };+ let each_operation_stays_in_plane = operations_of_keyframes+ .iter()+ .flat_map(|operations| operations.iter())+ .all(|operation| operation.to_matrix().is_2d_affine());+ let each_rotation_out_of_plane_keeps_its_angle = operations_of_keyframes.windows(2).all(|pair| {+ pair[0]+ .iter()+ .zip(pair[1])+ .all(|(from, to)| !matches!(from.kind, Kind::RotateX | Kind::RotateY) || from.values() == to.values())+ });+ each_operation_stays_in_plane && each_rotation_out_of_plane_keeps_its_angle+}++/// The largest factor a 2D affine matrix scales lengths along either axis by.+fn largest_axis_scale(matrix: FloatMatrix4x4) -> f32 {+ let affine = matrix.extract_2d_affine();+ let x_axis_scale = (affine.a() * affine.a() + affine.b() * affine.b()).sqrt();+ let y_axis_scale = (affine.c() * affine.c() + affine.d() * affine.d()).sqrt();+ x_axis_scale.max(y_axis_scale)+}++fn matrix_from_root_to_node_space(tree: &VisualContextTree, node: SpatialNodeIndex) -> FloatMatrix4x4 {+ let mut chain = Vec::new();+ let mut index = node;+ loop {+ chain.push(index);+ if index == VISUAL_VIEWPORT_NODE_INDEX {+ break;+ }+ index = tree.spatial_nodes[index.0 as usize].parent;+ }+ chain.iter().rev().fold(FloatMatrix4x4::identity(), |matrix, &index| {+ tree.local_transform(index, &[]).applied_to(matrix)+ })+}++/// The scale content under `anchor` is rastered at: as far as its parent scales it times the largest scale any of its+/// keyframes reach, so that the content stays as sharp as a direct raster at the largest, rounded so that samples+/// of one animation share it.+pub(crate) fn raster_scale_of(tree: &VisualContextTree, anchor: SpatialNodeIndex) -> f32 {+ let parent_scale = largest_axis_scale(matrix_from_root_to_node_space(+ tree,+ tree.spatial_nodes[anchor.0 as usize].parent,+ ));+ let largest_keyframe_scale = transform_animations_of(tree)+ .filter(|animation| animation.node_indices.contains(&anchor.0))+ .flat_map(transform_keyframe_matrices)+ .map(largest_axis_scale)+ .fold(0.0f32, f32::max);+ let scale_at_largest_keyframe = parent_scale * largest_keyframe_scale;+ if !parent_scale.is_finite() || scale_at_largest_keyframe.is_nan() {+ return 1.0;+ }+ // A parent that scales content down far enough puts the largest scale below the smallest one, which then wins.+ let largest_raster_scale = (parent_scale * LARGEST_RASTER_SCALE_PAST_PARENT_SCALE).max(SMALLEST_RASTER_SCALE);+ let raster_scale = scale_at_largest_keyframe+ .max(SMALLEST_RASTER_SCALE)+ .min(largest_raster_scale);+ if !raster_scale.is_finite() {+ return 1.0;+ }+ ((raster_scale * RASTER_SCALE_STEPS_PER_UNIT).round() / RASTER_SCALE_STEPS_PER_UNIT).max(SMALLEST_RASTER_SCALE)+}++fn effect_reads_what_is_below_it(data: &EffectNodeData) -> bool {+ match data {+ EffectNodeData::Effects(effects) => {+ effects.backdrop_filter.is_some()+ || effects.blend_mode != libgfx_rust::CompositingAndBlendingOperator::Normal+ }+ EffectNodeData::Mask(mask) => mask.masks_backdrop,+ _ => false,+ }+}++/// The spatial nodes whose transform the compositor animates that get raster spaces of their own, as the tree alone+/// decides: the outermost of them, whose animations stay in the plane, under 2D affine+/// transforms, holding no effect that reads what is below it and no part of a 3D sorting context, in tree order up+/// to as many as get one.+pub fn animated_transform_anchors(tree: &VisualContextTree) -> Vec<SpatialNodeIndex> {+ let mut is_animated_by_spatial_index = vec![false; tree.spatial_nodes.len()];+ let mut stays_in_plane_by_spatial_index = vec![true; tree.spatial_nodes.len()];+ for animation in transform_animations_of(tree) {+ let stays_in_plane = transform_animation_stays_in_plane(animation);+ for &node_index in &animation.node_indices {+ let Some(is_animated) = is_animated_by_spatial_index.get_mut(node_index as usize) else {+ continue;+ };+ *is_animated = true;+ stays_in_plane_by_spatial_index[node_index as usize] &= stays_in_plane;+ }+ }+ if !is_animated_by_spatial_index.contains(&true) {+ return Vec::new();+ }+ let mut chain_below_viewport_holds_animated_node = ValuesFoldedDownSpatialChains::<bool>::new();+ let mut matrices_from_root_to_node_spaces = ValuesFoldedDownSpatialChains::<FloatMatrix4x4>::new();+ let matrix_from_root_to_viewport_node_space = tree+ .local_transform(VISUAL_VIEWPORT_NODE_INDEX, &[])+ .applied_to(FloatMatrix4x4::identity());+ let mut subtrees_that_keep_nodes_from_anchoring_spaces = None;+ let mut anchors = Vec::new();+ for (index, node) in tree.spatial_nodes.iter().enumerate() {+ if anchors.len() == MAXIMUM_ANIMATED_TRANSFORM_SPACE_COUNT {+ break;+ }+ let anchor = SpatialNodeIndex(index as u32);+ if !is_animated_by_spatial_index[index]+ || !stays_in_plane_by_spatial_index[index]+ || !matches!(node.data, SpatialData::Transform(_))+ {+ continue;+ }+ let is_outermost = node.parent == VISUAL_VIEWPORT_NODE_INDEX+ || chain_below_viewport_holds_animated_node.value_of(+ tree,+ node.parent,+ false,+ |node, chain_above_holds| chain_above_holds || is_animated_by_spatial_index[node.0 as usize],+ ) == Some(false);+ if !is_outermost {+ continue;+ }+ let is_under_2d_affine_transforms = matrices_from_root_to_node_spaces+ .value_of(+ tree,+ node.parent,+ matrix_from_root_to_viewport_node_space,+ |node, matrix_from_root_to_parent_space| {+ tree.local_transform(node, &[])+ .applied_to(matrix_from_root_to_parent_space)+ },+ )+ .is_some_and(|matrix| matrix.is_2d_affine());+ if !is_under_2d_affine_transforms {+ continue;+ }+ let subtrees = subtrees_that_keep_nodes_from_anchoring_spaces+ .get_or_insert_with(|| SubtreesThatKeepNodesFromAnchoringSpaces::of(tree));+ if subtrees.touch_sorting_context_by_spatial_index[index]+ || subtrees.hold_effect_reading_below_it_by_spatial_index[index]+ {+ continue;+ }+ anchors.push(anchor);+ }+ anchors+}++// Per spatial node, whether its subtree holds part of a 3D sorting context, and whether it holds an effect that reads+// what is below it.+struct SubtreesThatKeepNodesFromAnchoringSpaces {+ touch_sorting_context_by_spatial_index: Vec<bool>,+ hold_effect_reading_below_it_by_spatial_index: Vec<bool>,+}++impl SubtreesThatKeepNodesFromAnchoringSpaces {+ fn of(tree: &VisualContextTree) -> Self {+ let mut touch_sorting_context_by_spatial_index: Vec<bool> = tree+ .roots_of_contexts_sorting_planes_by_depth()+ .iter()+ .map(Option::is_some)+ .collect();+ let mut hold_effect_reading_below_it_by_spatial_index = vec![false; tree.spatial_nodes.len()];+ for effect_node in &tree.effect_nodes {+ if effect_reads_what_is_below_it(&effect_node.data)+ && let Some(holds) =+ hold_effect_reading_below_it_by_spatial_index.get_mut(effect_node.spatial.0 as usize)+ {+ *holds = true;+ }+ }+ let mut live_nodes_parents_first = Vec::with_capacity(tree.spatial_nodes.len());+ tree.visit_spatial_nodes_parents_first(|index| live_nodes_parents_first.push(index));+ for &index in live_nodes_parents_first.iter().rev() {+ if index == VISUAL_VIEWPORT_NODE_INDEX.0 as usize {+ continue;+ }+ let parent = tree.spatial_nodes[index].parent.0 as usize;+ touch_sorting_context_by_spatial_index[parent] |= touch_sorting_context_by_spatial_index[index];+ hold_effect_reading_below_it_by_spatial_index[parent] |=+ hold_effect_reading_below_it_by_spatial_index[index];+ }+ Self {+ touch_sorting_context_by_spatial_index,+ hold_effect_reading_below_it_by_spatial_index,+ }+ }+}++/// Whether an effect reads what is below it, which content of a space whose anchor the compositor animates cannot be+/// placed under.+pub fn effect_reads_below_it(tree: &VisualContextTree, effect: EffectNodeIndex) -> bool {+ effect_reads_what_is_below_it(&tree.effect_nodes[effect.0 as usize].data)+}++pub(crate) fn easing_stays_within_unit_interval(easing: &Easing) -> bool {+ match easing {+ Easing::Linear(points) => points.iter().all(|point| (0.0..=1.0).contains(&point.output)),+ Easing::CubicBezier { y1, y2, .. } => (0.0..=1.0).contains(y1) && (0.0..=1.0).contains(y2),+ Easing::Steps { .. } => true,+ }+}++#[derive(Clone, Copy)]+struct ValueRange {+ lowest: f32,+ highest: f32,+}++impl ValueRange {+ fn of(value: f32) -> Self {+ Self {+ lowest: value,+ highest: value,+ }+ }++ fn widened_to(self, value: f32) -> Self {+ Self {+ lowest: self.lowest.min(value),+ highest: self.highest.max(value),+ }+ }++ fn times(self, lowest_factor: f32, highest_factor: f32) -> Self {+ let products = [+ self.lowest * lowest_factor,+ self.lowest * highest_factor,+ self.highest * lowest_factor,+ self.highest * highest_factor,+ ];+ Self {+ lowest: products.iter().copied().fold(f32::INFINITY, f32::min),+ highest: products.iter().copied().fold(f32::NEG_INFINITY, f32::max),+ }+ }+}++/// What a 2D operation can do to points, over the values its keyframes give it.+#[derive(Clone, Copy)]+enum SweptOperation {+ Translate { x: ValueRange, y: ValueRange },+ Scale { x: ValueRange, y: ValueRange },+ Rotate,+}++fn x_and_y_of_operation(operation: &VisualAnimationTransformOperation) -> Option<(f32, f32)> {+ use FfiVisualAnimationTransformOperationKind as Kind;+ let values = operation.values();+ let first = values.first().copied().unwrap_or(0.0);+ let second = values.get(1).copied();+ Some(match operation.kind {+ Kind::Translate => (first, second.unwrap_or(0.0)),+ Kind::TranslateX => (first, 0.0),+ Kind::TranslateY => (0.0, first),+ Kind::Scale => (first, second.unwrap_or(first)),+ Kind::ScaleX => (first, 1.0),+ Kind::ScaleY => (1.0, first),+ Kind::Rotate | Kind::RotateZ => (0.0, 0.0),+ _ => return None,+ })+}++fn swept_operations_of(animation: &VisualAnimation) -> Option<Vec<SweptOperation>> {+ use FfiVisualAnimationTransformOperationKind as Kind;+ if !easing_stays_within_unit_interval(&animation.easing)+ || !animation+ .keyframes+ .iter()+ .all(|keyframe| easing_stays_within_unit_interval(&keyframe.easing))+ {+ return None;+ }+ let mut swept_operations: Option<Vec<SweptOperation>> = None;+ for keyframe in &animation.keyframes {+ let VisualAnimationValue::Transform(operations) = &keyframe.value else {+ return None;+ };+ let operations_of_keyframe = operations+ .iter()+ .map(|operation| {+ let (x, y) = x_and_y_of_operation(operation)?;+ Some(match operation.kind {+ Kind::Translate | Kind::TranslateX | Kind::TranslateY => SweptOperation::Translate {+ x: ValueRange::of(x),+ y: ValueRange::of(y),+ },+ Kind::Scale | Kind::ScaleX | Kind::ScaleY => SweptOperation::Scale {+ x: ValueRange::of(x),+ y: ValueRange::of(y),+ },+ _ => SweptOperation::Rotate,+ })+ })+ .collect::<Option<Vec<_>>>()?;+ swept_operations = Some(match swept_operations {+ None => operations_of_keyframe,+ Some(swept_so_far) => {+ if swept_so_far.len() != operations_of_keyframe.len() {+ return None;+ }+ swept_so_far+ .into_iter()+ .zip(operations_of_keyframe)+ .map(|pair| match pair {+ (+ SweptOperation::Translate { x, y },+ SweptOperation::Translate {+ x: keyframe_x,+ y: keyframe_y,+ },+ ) => Some(SweptOperation::Translate {+ x: x.widened_to(keyframe_x.lowest),+ y: y.widened_to(keyframe_y.lowest),+ }),+ (+ SweptOperation::Scale { x, y },+ SweptOperation::Scale {+ x: keyframe_x,+ y: keyframe_y,+ },+ ) => Some(SweptOperation::Scale {+ x: x.widened_to(keyframe_x.lowest),+ y: y.widened_to(keyframe_y.lowest),+ }),+ (SweptOperation::Rotate, SweptOperation::Rotate) => Some(SweptOperation::Rotate),+ _ => None,+ })+ .collect::<Option<Vec<_>>>()?+ }+ });+ }+ swept_operations+}++fn swept_through(operation: SweptOperation, rect: FloatRect) -> FloatRect {+ let (x, y) = (+ ValueRange {+ lowest: rect.x,+ highest: rect.right(),+ },+ ValueRange {+ lowest: rect.y,+ highest: rect.bottom(),+ },+ );+ let (x, y) = match operation {+ SweptOperation::Translate {+ x: translation_x,+ y: translation_y,+ } => (+ ValueRange {+ lowest: x.lowest + translation_x.lowest,+ highest: x.highest + translation_x.highest,+ },+ ValueRange {+ lowest: y.lowest + translation_y.lowest,+ highest: y.highest + translation_y.highest,+ },+ ),+ SweptOperation::Scale { x: scale_x, y: scale_y } => (+ x.times(scale_x.lowest, scale_x.highest),+ y.times(scale_y.lowest, scale_y.highest),+ ),+ SweptOperation::Rotate => {+ let radius = [+ (x.lowest, y.lowest),+ (x.highest, y.lowest),+ (x.lowest, y.highest),+ (x.highest, y.highest),+ ]+ .iter()+ .map(|&(corner_x, corner_y)| (corner_x * corner_x + corner_y * corner_y).sqrt())+ .fold(0.0f32, f32::max);+ (+ ValueRange {+ lowest: -radius,+ highest: radius,+ },+ ValueRange {+ lowest: -radius,+ highest: radius,+ },+ )+ }+ };+ FloatRect::new(x.lowest, y.lowest, x.highest - x.lowest, y.highest - y.lowest)+}++/// Where content within `content_rect`, in the coordinates of `anchor`'s content, can show in those of the anchor's+/// parent wherever the compositor's animation of the anchor takes it, or what the tree holds while the animation shows+/// nothing; none where that cannot be bounded, as for a skew or an easing that overshoots.+pub fn swept_bounds_in_parent(+ tree: &VisualContextTree,+ anchor: SpatialNodeIndex,+ content_rect: FloatRect,+) -> Option<FloatRect> {+ let SpatialData::Transform(transform) = &tree.spatial_nodes[anchor.0 as usize].data else {+ return None;+ };+ let mut animations_of_anchor =+ transform_animations_of(tree).filter(|animation| animation.node_indices.contains(&anchor.0));+ let animation = animations_of_anchor.next()?;+ if animations_of_anchor.next().is_some() {+ return None;+ }+ let origin = transform.origin;+ let mut swept = content_rect.translated(-origin.x, -origin.y);+ for operation in swept_operations_of(animation)?.into_iter().rev() {+ swept = swept_through(operation, swept);+ }+ let swept = swept.translated(origin.x, origin.y);+ let where_tree_holds_it = transform+ .matrix_including_origin()+ .extract_2d_affine()+ .map_rect(content_rect);+ let bounds = swept.united(where_tree_holds_it);+ crate::display_list::placement::is_finite_rect(bounds).then_some(bounds)+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/builder.rs b/Libraries/LibCompositing/Rust/src/display_list/builder.rsindex 96a25dffa4b..0779c5842b6 100644--- a/Libraries/LibCompositing/Rust/src/display_list/builder.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/builder.rs@@ -7,6 +7,7 @@use super::chunks::{Chunk, ChunkId, DisplayListChunk, chunk_id, chunks_of};use super::commands::*;use crate::display_list::ffi_bytes::FfiBytes;+use crate::display_list::placement::enclosing_int_rect_within_extent_limit;use libgfx_rust::path::Path;use libgfx_rust::{AffineTransform, CornerRadii, FloatRect, IntRect, WindingRule, enclosing_int_rect};use std::rc::Rc;@@ -154,12 +155,14 @@ fn record_bounding_rect(inline_transform: Option<AffineTransform>,rects_of_inline_clips_confining_the_command: impl IntoIterator<Item = FloatRect>,) -> Option<IntRect> {- let mut bounding_rect = command_bounding_rect;+ let mut bounding_rect = command_bounding_rect.map(int_rect_within_record_bounds_limit);if let (Some(transform), Some(rect)) = (inline_transform, bounding_rect) {- bounding_rect = Some(enclosing_int_rect(transform.map_rect(rect.to_float())));+ bounding_rect = Some(enclosing_int_rect_within_extent_limit(+ transform.map_rect(rect.to_float()),+ ));}for clip_rect in rects_of_inline_clips_confining_the_command {- let restriction = enclosing_int_rect(clip_rect);+ let restriction = enclosing_int_rect_within_record_bounds_limit(clip_rect);bounding_rect = Some(match bounding_rect {Some(rect) => rect.intersected(restriction),None => restriction,@@ -893,6 +896,25 @@ mod tests {)}+ // A list from another process can record a command through an inline transform that maps it past what an+ // `IntRect` holds.+ #[test]+ fn a_bounding_rect_mapped_through_an_inline_transform_is_kept_within_the_extent_limit() {+ let mut builder = DisplayListBuilder::new();+ let scale = 1e9;+ let maps_fill_far_past_every_edge = AffineTransform::new(scale, 0.0, 0.0, scale, -50.0 * scale, -50.0 * scale);+ builder.append_with_inline_state(+ &fill_rect(0, 0, 100, 100),+ &[],+ context(0, None),+ &[],+ Some(maps_fill_far_past_every_edge),+ );+ let bounding_rect = bounding_rect_of_record_at(&builder, 0).expect("the fill has a bounding rect");+ assert!(bounding_rect.contains_rect(IntRect::new(0, 0, 800, 600)));+ assert!(crate::display_list::placement::extent_limit_rect().contains_rect(bounding_rect.to_float()));+ }+#[test]fn a_confining_clip_narrows_the_bounding_rect_and_appends_a_tail_entry() {let mut builder = DisplayListBuilder::new();diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rsindex 40a0c4ac447..611bc6759cc 100644--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs@@ -414,7 +414,7 @@ mod tests {use super::*;use crate::display_list::builder::{HEADER_SIZE, read_command, read_header};use crate::display_list::nested_records::span_bytes;- use crate::display_list::storage::write_run;+ use crate::display_list::storage::write_run_with_zeroed_padding;use crate::display_list::validate::validate_tape;use libgfx_rust::IntRect;@@ -586,7 +586,7 @@ mod tests {let mut writer = TapeWriter::default();writer.save();let mut run_bytes = vec![0u8; size_of::<DisplayListCommandRun>()];- write_run(+ write_run_with_zeroed_padding(&DisplayListCommandRun {offset: 0,size: u32::try_from(writer.bytes().len()).unwrap(),diff --git a/Libraries/LibCompositing/Rust/src/display_list/chunks.rs b/Libraries/LibCompositing/Rust/src/display_list/chunks.rsindex 1c8cc554fb8..c4f260d6f5a 100644--- a/Libraries/LibCompositing/Rust/src/display_list/chunks.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/chunks.rs@@ -10,15 +10,10 @@//! that replaces another is then mostly the same chunks, a recording reuses whole chunks of the one before it, and a//! chunk is named by what it holds, so two tapes can be told apart chunk by chunk.-use super::builder::{for_each_command, has_inline_clip_in_its_own_space, read_command};-use super::commands::{- CompositorScrollbar, DeclareMaskContent, DisplayListCommandRun, DisplayListCommandType, EffectNodeIndex,- PaintScrollBar, SpatialNodeIndex,-};-use super::nested_records::{for_each_nested_record_span, span_bytes};-use super::storage::write_run;+use super::builder::{for_each_command, has_inline_clip_in_its_own_space, inline_clips_of, read_command};+use super::commands::{DisplayListCommandRun, DisplayListCommandType, PaintScrollBar, SpatialNodeIndex};+use super::storage::write_run_with_zeroed_padding;use std::hash::{BuildHasher, Hasher};-use std::ops::Range;/// Names a chunk by what it holds: chunks with one id hold the same records in the same runs.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]@@ -57,33 +52,40 @@ pub const DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT: usize = 4;/// so both always keep the same chunks without telling each other.#[derive(Debug, Default)]pub struct KeptChunks {- latest_lists: std::collections::VecDeque<Box<[ChunkId]>>,- lists_naming: std::collections::HashMap<ChunkId, u32>,+ distinct_chunk_ids_of_latest_lists: std::collections::VecDeque<Box<[ChunkId]>>,+ count_of_kept_lists_naming_chunk: std::collections::HashMap<ChunkId, u32>,}impl KeptChunks {pub fn keeps(&self, id: ChunkId) -> bool {- self.lists_naming.contains_key(&id)+ self.count_of_kept_lists_naming_chunk.contains_key(&id)}/// Takes in the display list the context presents next, which names `chunks`, and answers the chunks that no list/// still kept names.pub fn take_in(&mut self, chunks: &[ChunkId]) -> Vec<ChunkId> {- let mut named_once: Vec<ChunkId> = chunks.to_vec();- named_once.sort_unstable_by_key(|id| id.0);- named_once.dedup();- for id in &named_once {- *self.lists_naming.entry(*id).or_default() += 1;+ let mut distinct_chunk_ids: Vec<ChunkId> = chunks.to_vec();+ distinct_chunk_ids.sort_unstable_by_key(|id| id.0);+ distinct_chunk_ids.dedup();+ for id in &distinct_chunk_ids {+ *self.count_of_kept_lists_naming_chunk.entry(*id).or_default() += 1;}- self.latest_lists.push_back(named_once.into_boxed_slice());+ self.distinct_chunk_ids_of_latest_lists+ .push_back(distinct_chunk_ids.into_boxed_slice());let mut dropped = Vec::new();- while self.latest_lists.len() > DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {- let oldest = self.latest_lists.pop_front().expect("more lists than are kept");+ while self.distinct_chunk_ids_of_latest_lists.len() > DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {+ let oldest = self+ .distinct_chunk_ids_of_latest_lists+ .pop_front()+ .expect("more lists than are kept");for id in oldest {- let count = self.lists_naming.get_mut(&id).expect("a kept list names a kept chunk");+ let count = self+ .count_of_kept_lists_naming_chunk+ .get_mut(&id)+ .expect("a kept list names a kept chunk");*count -= 1;if *count == 0 {- self.lists_naming.remove(&id);+ self.count_of_kept_lists_naming_chunk.remove(&id);dropped.push(id);}}@@ -109,7 +111,7 @@ pub fn chunk_id(bytes: &[u8], runs: &[DisplayListCommandRun], chunk_start: u32)let write_runs = |hasher: &mut crate::fast_hash::FastHasher| {let mut run_bytes = [0; RUN_SIZE];for run in runs {- write_run(+ write_run_with_zeroed_padding(&DisplayListCommandRun {offset: run.offset - chunk_start,..*run@@ -119,14 +121,13 @@ pub fn chunk_id(bytes: &[u8], runs: &[DisplayListCommandRun], chunk_start: u32)hasher.write(&run_bytes);}};- // Two digests that differ in their seed and in the order they read the chunk in.- let mut records_first = foldhash::fast::FixedState::with_seed(0x6368_756e_6b5f_6964).build_hasher();- records_first.write(bytes);- write_runs(&mut records_first);- let mut runs_first = foldhash::fast::FixedState::with_seed(0x7461_7065_5f63_7574).build_hasher();- write_runs(&mut runs_first);- runs_first.write(bytes);- ChunkId([records_first.finish(), runs_first.finish()])+ let mut records_then_runs_hasher = foldhash::fast::FixedState::with_seed(0x6368_756e_6b5f_6964).build_hasher();+ records_then_runs_hasher.write(bytes);+ write_runs(&mut records_then_runs_hasher);+ let mut runs_then_records_hasher = foldhash::fast::FixedState::with_seed(0x7461_7065_5f63_7574).build_hasher();+ write_runs(&mut runs_then_records_hasher);+ runs_then_records_hasher.write(bytes);+ ChunkId([records_then_runs_hasher.finish(), runs_then_records_hasher.finish()])}/// The bytes and runs of each chunk of a tape, in tape order.@@ -146,219 +147,60 @@ pub fn chunks_of<'a>(})}+/// What a record depends on outside the visual context of its run, which a raster space that does not move with it+/// cannot raster it under.#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ReachOutsideChunk {+pub enum ReachOutsideRunContext {ScrollbarThumbFollowsScrollOffsetOf(SpatialNodeIndex),- InlineClipInItsOwnSpace,- DeclaresMaskContentOf(EffectNodeIndex),- ScrollbarPaintedByCompositor,+ InlineClipInSpaceOf(SpatialNodeIndex),}#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub struct TopLevelRecordReachingOutsideItsChunk {+pub struct TopLevelRecordReachingOutsideRunContext {pub record_offset: u32,pub run_index: u32,- pub reach: ReachOutsideChunk,+ pub reach_outside_run_context: ReachOutsideRunContext,}-pub fn top_level_records_reaching_outside_their_chunk(+pub fn top_level_records_reaching_outside_run_context(bytes: &[u8],runs: &[DisplayListCommandRun],-) -> Vec<TopLevelRecordReachingOutsideItsChunk> {+) -> Vec<TopLevelRecordReachingOutsideRunContext> {let mut records = Vec::new();for (run_index, run) in runs.iter().enumerate() {let run_start = run.offset as usize;for_each_command(&bytes[run_start..run_start + run.size as usize],|header, offset_in_run, payload| {- let mut note = |reach| {- records.push(TopLevelRecordReachingOutsideItsChunk {+ let mut note = |reach_outside_run_context| {+ records.push(TopLevelRecordReachingOutsideRunContext {record_offset: (run_start + offset_in_run) as u32,run_index: run_index as u32,- reach,+ reach_outside_run_context,});};- match header.command_type {- DisplayListCommandType::PaintScrollBar => {- note(ReachOutsideChunk::ScrollbarThumbFollowsScrollOffsetOf(- read_command::<PaintScrollBar>(payload).scroll_node_index,- ));- }- DisplayListCommandType::CompositorScrollbar- if read_command::<CompositorScrollbar>(payload).is_painted_by_compositor =>- {- note(ReachOutsideChunk::ScrollbarPaintedByCompositor);- }- _ => {}+ if header.command_type == DisplayListCommandType::PaintScrollBar {+ note(ReachOutsideRunContext::ScrollbarThumbFollowsScrollOffsetOf(+ read_command::<PaintScrollBar>(payload).scroll_node_index,+ ));}if header.inline_clip_count != 0 && has_inline_clip_in_its_own_space(header, payload) {- note(ReachOutsideChunk::InlineClipInItsOwnSpace);+ for clip in inline_clips_of(header, payload).filter(|clip| clip.has_own_space) {+ note(ReachOutsideRunContext::InlineClipInSpaceOf(clip.space));+ }}- for_each_mask_content_declared_in_record(header.command_type, payload, &mut |effect| {- note(ReachOutsideChunk::DeclaresMaskContentOf(effect));- });},);}records}-fn for_each_mask_content_declared_in_record(- command_type: DisplayListCommandType,- payload: &[u8],- visit: &mut impl FnMut(EffectNodeIndex),-) {- if command_type == DisplayListCommandType::DeclareMaskContent {- visit(read_command::<DeclareMaskContent>(payload).effect);- }- for_each_nested_record_span(command_type, payload, |_, span| {- for_each_command(span_bytes(payload, span), |nested_header, _, nested_payload| {- for_each_mask_content_declared_in_record(nested_header.command_type, nested_payload, visit);- });- });-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-struct ChunkOfTape {- id: ChunkId,- run_end: u32,- reaching_records_end: u32,-}--#[derive(Debug, Default, PartialEq, Eq)]-pub struct TapeChunks {- chunks_in_paint_order: Vec<ChunkOfTape>,- records_reaching_outside_their_chunks: Vec<TopLevelRecordReachingOutsideItsChunk>,-}--impl TapeChunks {- pub fn len(&self) -> usize {- self.chunks_in_paint_order.len()- }-- pub fn is_empty(&self) -> bool {- self.chunks_in_paint_order.is_empty()- }-- pub fn id(&self, chunk_index: usize) -> ChunkId {- self.chunks_in_paint_order[chunk_index].id- }-- pub fn runs_of(&self, chunk_index: usize) -> Range<usize> {- let start = chunk_index- .checked_sub(1)- .map_or(0, |previous| self.chunks_in_paint_order[previous].run_end as usize);- start..self.chunks_in_paint_order[chunk_index].run_end as usize- }-- pub fn records_reaching_outside(&self, chunk_index: usize) -> &[TopLevelRecordReachingOutsideItsChunk] {- let start = chunk_index.checked_sub(1).map_or(0, |previous| {- self.chunks_in_paint_order[previous].reaching_records_end as usize- });- &self.records_reaching_outside_their_chunks- [start..self.chunks_in_paint_order[chunk_index].reaching_records_end as usize]- }-- pub fn try_reserve(&mut self, chunk_count: usize, reaching_record_count: usize) -> Result<(), &'static str> {- self.chunks_in_paint_order- .try_reserve_exact(chunk_count)- .and_then(|()| {- self.records_reaching_outside_their_chunks- .try_reserve_exact(reaching_record_count)- })- .map_err(|_| "Display list has too many chunks to receive")- }-- pub fn push_chunk(- &mut self,- id: ChunkId,- first_run_index: u32,- run_count: usize,- first_record_offset: u32,- records_reaching_outside: &[TopLevelRecordReachingOutsideItsChunk],- ) {- debug_assert_eq!(- first_run_index as usize,- self.chunks_in_paint_order- .last()- .map_or(0, |chunk| chunk.run_end as usize)- );- self.records_reaching_outside_their_chunks- .extend(- records_reaching_outside- .iter()- .map(|record| TopLevelRecordReachingOutsideItsChunk {- record_offset: record.record_offset + first_record_offset,- run_index: record.run_index + first_run_index,- ..*record- }),- );- self.chunks_in_paint_order.push(ChunkOfTape {- id,- run_end: first_run_index + run_count as u32,- reaching_records_end: self.records_reaching_outside_their_chunks.len() as u32,- });- }-- pub fn of_tape(bytes: &[u8], runs: &[DisplayListCommandRun], chunks: &[DisplayListChunk]) -> Self {- let mut tape_chunks = Self::default();- let mut covered_run_count = 0;- let mut covered_byte_count = 0;- for (chunk, _, chunk_runs) in chunks_of(bytes, runs, chunks) {- tape_chunks.push_chunk(- chunk.id,- covered_run_count,- chunk_runs.len(),- 0,- &top_level_records_reaching_outside_their_chunk(bytes, chunk_runs),- );- covered_run_count = chunk.run_end;- covered_byte_count = chunk.byte_end;- }- let uncovered_runs = &runs[covered_run_count as usize..];- if !uncovered_runs.is_empty() {- tape_chunks.push_chunk(- chunk_id(- &bytes[covered_byte_count as usize..],- uncovered_runs,- covered_byte_count,- ),- covered_run_count,- uncovered_runs.len(),- 0,- &top_level_records_reaching_outside_their_chunk(bytes, uncovered_runs),- );- }- tape_chunks- }-- #[cfg(test)]- pub(crate) fn with_a_chunk_per_run(bytes: &[u8], runs: &[DisplayListCommandRun]) -> Self {- let chunks: Vec<DisplayListChunk> = runs- .iter()- .enumerate()- .map(|(run_index, run)| DisplayListChunk {- id: chunk_id(- &bytes[run.offset as usize..(run.offset + run.size) as usize],- std::slice::from_ref(run),- run.offset,- ),- byte_end: run.offset + run.size,- run_end: run_index as u32 + 1,- })- .collect();- Self::of_tape(bytes, runs, &chunks)- }-}-#[cfg(test)]mod tests {use super::*;use crate::display_list::builder::{DisplayListBuilder, PendingInlineClip, RecordedDisplayList};- use crate::display_list::commands::{- ClipNodeIndex, ContextRef, DisplayListDataSpan, DrawIsolatedGroup, EffectNodeIndex, FillRect, SpatialNodeIndex,- };- use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatRect, IntRect, MaskKind};+ use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, FillRect, SpatialNodeIndex};+ use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatRect, IntRect};fn context(spatial: u32) -> ContextRef {ContextRef {@@ -421,43 +263,8 @@ mod tests {assert_ne!(builder.finish().chunks[0].id, tape.chunks[0].id);}- fn compositor_scrollbar(is_painted_by_compositor: bool) -> CompositorScrollbar {- CompositorScrollbar {- scroll_node_index: SpatialNodeIndex(1),- gutter_rect: IntRect::new(90, 0, 10, 100),- thumb_rect: IntRect::new(90, 0, 10, 20),- track_rect: IntRect::new(90, 0, 10, 100),- expanded_gutter_rect: IntRect::new(86, 0, 14, 100),- expanded_thumb_rect: IntRect::new(86, 0, 14, 20),- scroll_size: 0.5,- expanded_scroll_size: 0.5,- min_scroll_offset: 0.0,- max_scroll_offset: 100.0,- thumb_color: Color::default(),- thumb_outline_color: Color::default(),- track_color: Color::default(),- vertical: true,- is_painted_by_compositor,- }- }-- fn declare_mask_content(builder: &mut DisplayListBuilder, effect: EffectNodeIndex, context: ContextRef) {- let declaration = builder.begin_group::<DeclareMaskContent>(Vec::new());- builder.append(&fill_rect(0), &[], context);- let content = builder.group_content_span(&declaration);- builder.finish_group(- declaration,- &DeclareMaskContent {- rect: IntRect::new(0, 0, 10, 10),- effect,- content,- },- context,- );- }-#[test]- fn records_that_reach_outside_their_chunk_are_found_where_they_are_or_where_they_are_nested() {+ fn records_that_reach_outside_their_chunk_are_found_with_what_they_reach() {let mut builder = DisplayListBuilder::new();builder.append(&fill_rect(0), &[], context(1));let paint_scrollbar_offset = builder.byte_size() as u32;@@ -477,62 +284,39 @@ mod tests {&[],context(1),);- let compositor_scrollbar_offset = builder.byte_size() as u32;- builder.append(&compositor_scrollbar(true), &[], context(1));- builder.append(&compositor_scrollbar(false), &[], context(1));let own_space_clip_offset = builder.byte_size() as u32;let clip = PendingInlineClip::intersecting_float_rect(FloatRect::new(0.0, 0.0, 5.0, 5.0));- builder.append_with_inline_clips(&fill_rect(20), &[], context(2), &[clip.in_space(SpatialNodeIndex(4))]);- builder.append_with_inline_clips(&fill_rect(30), &[], context(2), &[clip]);- let mask_offset = builder.byte_size() as u32;- declare_mask_content(&mut builder, EffectNodeIndex(1), context(2));- let group_offset = builder.byte_size() as u32;- let group = builder.begin_group::<DrawIsolatedGroup>(Vec::new());- declare_mask_content(&mut builder, EffectNodeIndex(2), context(2));- let content = builder.group_content_span(&group);- builder.finish_group(- group,- &DrawIsolatedGroup {- clip_rect: FloatRect::new(0.0, 0.0, 10.0, 10.0),- content,- mask: DisplayListDataSpan::default(),- filter: DisplayListDataSpan::default(),- opacity: 1.0,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- mask_kind: MaskKind::Alpha,- },+ builder.append_with_inline_clips(+ &fill_rect(20),+ &[],context(2),+ &[clip.in_space(SpatialNodeIndex(4)), clip.in_space(SpatialNodeIndex(6))],);+ builder.append_with_inline_clips(&fill_rect(30), &[], context(2), &[clip]);let chunk = builder.take_chunk();- let record = |record_offset, run_index, reach| TopLevelRecordReachingOutsideItsChunk {+ let record = |record_offset, run_index, reach_outside_run_context| TopLevelRecordReachingOutsideRunContext {record_offset,run_index,- reach,+ reach_outside_run_context,};assert_eq!(- top_level_records_reaching_outside_their_chunk(&chunk.records, &chunk.runs),+ top_level_records_reaching_outside_run_context(&chunk.records, &chunk.runs),[record(paint_scrollbar_offset,1,- ReachOutsideChunk::ScrollbarThumbFollowsScrollOffsetOf(SpatialNodeIndex(5))+ ReachOutsideRunContext::ScrollbarThumbFollowsScrollOffsetOf(SpatialNodeIndex(5))),record(- compositor_scrollbar_offset,+ own_space_clip_offset,2,- ReachOutsideChunk::ScrollbarPaintedByCompositor+ ReachOutsideRunContext::InlineClipInSpaceOf(SpatialNodeIndex(4))),- record(own_space_clip_offset, 3, ReachOutsideChunk::InlineClipInItsOwnSpace),record(- mask_offset,- 3,- ReachOutsideChunk::DeclaresMaskContentOf(EffectNodeIndex(1))- ),- record(- group_offset,- 3,- ReachOutsideChunk::DeclaresMaskContentOf(EffectNodeIndex(2))+ own_space_clip_offset,+ 2,+ ReachOutsideRunContext::InlineClipInSpaceOf(SpatialNodeIndex(6))),]);diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rsindex b5edc9b9d03..41c4c1d8264 100644--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs@@ -1084,11 +1084,14 @@ display_list_record_fields!(PaintOuterBoxShadow {impl DisplayListCommand for PaintOuterBoxShadow {const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::PaintOuterBoxShadow;fn bounding_rect(&self) -> Option<IntRect> {- let blur_margin = self.blur_radius * 2;- Some(- self.shadow_rect- .inflated_edges(blur_margin, blur_margin, blur_margin, blur_margin),- )+ let blur_margin = i64::from(self.blur_radius) * 2;+ let rect = self.shadow_rect;+ Some(int_rect_of_edges_within_record_bounds_limit(+ i64::from(rect.x) - blur_margin,+ i64::from(rect.y) - blur_margin,+ i64::from(rect.x) + i64::from(rect.width) + blur_margin,+ i64::from(rect.y) + i64::from(rect.height) + blur_margin,+ ))}}@@ -1154,13 +1157,15 @@ impl DisplayListCommand for PaintPathBoxShadow {// NB: The player grows the shape by the outline of a miter-joined stroke, whose miters reach out to Skia's default// miter limit of 4 times half the stroke width, so up to 4 times the spread at sharp corners.const MITER_LIMIT: f32 = 4.0;- let margin = (self.spread_distance.max(0.0) * MITER_LIMIT).ceil() as i32 + self.blur_radius * 2;- let mut shadow_rect = shape_rect.inflated_edges(margin, margin, margin, margin);- shadow_rect.x += self.offset.x.floor() as i32;- shadow_rect.y += self.offset.y.floor() as i32;- shadow_rect.width += 1;- shadow_rect.height += 1;- Some(shadow_rect)+ let margin = (self.spread_distance.max(0.0) * MITER_LIMIT).ceil() as i64 + i64::from(self.blur_radius) * 2;+ let left = i64::from(shape_rect.x) - margin + self.offset.x.floor() as i64;+ let top = i64::from(shape_rect.y) - margin + self.offset.y.floor() as i64;+ Some(int_rect_of_edges_within_record_bounds_limit(+ left,+ top,+ left + i64::from(shape_rect.width) + 2 * margin + 1,+ top + i64::from(shape_rect.height) + 2 * margin + 1,+ ))}}@@ -1391,7 +1396,15 @@ display_list_record_fields!(DrawLine {impl DisplayListCommand for DrawLine {const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::DrawLine;fn bounding_rect(&self) -> Option<IntRect> {- Some(int_rect_from_two_points(self.from, self.to).inflated(self.thickness, self.thickness))+ let thickness = i64::from(self.thickness);+ let left = i64::from(self.from.x.min(self.to.x)) - thickness / 2;+ let top = i64::from(self.from.y.min(self.to.y)) - thickness / 2;+ Some(int_rect_of_edges_within_record_bounds_limit(+ left,+ top,+ left + (i64::from(self.from.x) - i64::from(self.to.x)).abs() + thickness,+ top + (i64::from(self.from.y) - i64::from(self.to.y)).abs() + thickness,+ ))}}@@ -1704,9 +1717,9 @@ impl DisplayListCommand for PaintScrollBar {const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::PaintScrollBar;fn bounding_rect(&self) -> Option<IntRect> {Some(- self.track_rect- .united(self.thumb_rect)- .united(self.expanded_gutter_rect),+ int_rect_within_record_bounds_limit(self.track_rect)+ .united(int_rect_within_record_bounds_limit(self.thumb_rect))+ .united(int_rect_within_record_bounds_limit(self.expanded_gutter_rect)),)}}@@ -2057,8 +2070,35 @@ impl DisplayListCommand for Canvas2DPutImageFrame {const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DPutImageFrame;}-pub fn int_rect_from_two_points(a: IntPoint, b: IntPoint) -> IntRect {- IntRect::new(a.x.min(b.x), a.y.min(b.y), (a.x - b.x).abs(), (a.y - b.y).abs())+/// How far from the origin the bounds of a record reach at most, so that the bounds of any two records unite into a rect+/// whose edges fit.+pub const RECORD_BOUNDS_LIMIT_IN_DEVICE_PIXELS: i64 = (1 << 30) - 1;++/// The rect between the edges, cut to `RECORD_BOUNDS_LIMIT_IN_DEVICE_PIXELS` from the origin.+pub fn int_rect_of_edges_within_record_bounds_limit(left: i64, top: i64, right: i64, bottom: i64) -> IntRect {+ let limit = RECORD_BOUNDS_LIMIT_IN_DEVICE_PIXELS;+ let [left, top, right, bottom] = [left, top, right, bottom].map(|edge| edge.clamp(-limit, limit) as i32);+ IntRect::new(left, top, right - left, bottom - top)+}++/// `rect` cut to `RECORD_BOUNDS_LIMIT_IN_DEVICE_PIXELS` from the origin, whatever its edges.+pub fn int_rect_within_record_bounds_limit(rect: IntRect) -> IntRect {+ int_rect_of_edges_within_record_bounds_limit(+ i64::from(rect.x),+ i64::from(rect.y),+ i64::from(rect.x) + i64::from(rect.width),+ i64::from(rect.y) + i64::from(rect.height),+ )+}++/// The smallest rect of whole pixels that holds `rect`, cut to `RECORD_BOUNDS_LIMIT_IN_DEVICE_PIXELS` from the origin.+pub fn enclosing_int_rect_within_record_bounds_limit(rect: FloatRect) -> IntRect {+ int_rect_of_edges_within_record_bounds_limit(+ rect.x.floor() as i64,+ rect.y.floor() as i64,+ rect.right().ceil() as i64,+ rect.bottom().ceil() as i64,+ )}#[cfg(test)]diff --git a/Libraries/LibCompositing/Rust/src/display_list/damage.rs b/Libraries/LibCompositing/Rust/src/display_list/damage.rsdeleted file mode 100644index e19dacebcdc..00000000000--- a/Libraries/LibCompositing/Rust/src/display_list/damage.rs+++ /dev/null@@ -1,3290 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use super::chunks::{ReachOutsideChunk, TapeChunks, TopLevelRecordReachingOutsideItsChunk};-use super::effect_clip_plan::EffectClipPlan;-use super::effect_geometry::{Extent, changed_extent_through_filters, nearest_spreading_effects};-use super::layers::{LayerKind, LayerPlan};-use super::replay::{OwnSpaceClipExtent, own_space_clip_extent};-use super::summary::{DisplayListSummary, LiveContent};-use crate::display_list::builder::{- HEADER_SIZE, bounding_rect_computed_from_payload, for_each_command, has_inline_clip_in_its_own_space,- inline_clips_of, read_header,-};-use crate::display_list::commands::{- CanvasId, ClipMode, ClipNodeIndex, CompositorContextId, ContextRef, DisplayListCommandHeader,- DisplayListCommandRun, EffectNodeIndex, ImageFrameResourceId, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,- VideoSinkHandle,-};-use crate::host::FfiAnimatedContentViewportEffect;-use crate::visual_context::queries::TreeCullingScratch;-use crate::visual_context::{- ClipNodeData, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,-};-use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect, enclosing_int_rect};-use std::cell::OnceCell;--struct RecordOnTape<'a> {- header: DisplayListCommandHeader,- payload: &'a [u8],- context: ContextRef,- record_offset: u32,-}--impl<'a> RecordOnTape<'a> {- fn at(bytes: &'a [u8], record_offset: u32, context: ContextRef) -> Self {- let offset = record_offset as usize;- let header = read_header(&bytes[offset..]);- let payload_start = offset + HEADER_SIZE;- Self {- header,- payload: &bytes[payload_start..payload_start + header.payload_size as usize],- context,- record_offset,- }- }-}--fn spatial_data_is_equal(- index: SpatialNodeIndex,- a: &SpatialData,- a_scroll_offsets: &[FloatPoint],- b: &SpatialData,- b_scroll_offsets: &[FloatPoint],-) -> bool {- match (a, b) {- // The payload carries no offset key; replay reads the offset stored under each node's- // own index, so that is what has to match.- (SpatialData::Scroll(_), SpatialData::Scroll(_)) | (SpatialData::Sticky(_), SpatialData::Sticky(_)) => {- device_offset_for_index(a_scroll_offsets, index) == device_offset_for_index(b_scroll_offsets, index)- }- (SpatialData::Transform(data), SpatialData::Transform(other)) => data == other,- (SpatialData::Perspective(data), SpatialData::Perspective(other)) => data == other,- (SpatialData::BackfaceVisibility(data), SpatialData::BackfaceVisibility(other)) => data == other,- (SpatialData::AnchorScrollShift(data), SpatialData::AnchorScrollShift(other)) => {- data.negate == other.negate- && data.compensate_horizontal_scroll == other.compensate_horizontal_scroll- && data.compensate_vertical_scroll == other.compensate_vertical_scroll- && data.masked_offset(a_scroll_offsets) == other.masked_offset(b_scroll_offsets)- }- _ => false,- }-}--fn clip_data_is_equal(a: &ClipNodeData, b: &ClipNodeData) -> bool {- match (a, b) {- (ClipNodeData::Rect(data), ClipNodeData::Rect(other)) => data == other,- (ClipNodeData::Path(data), ClipNodeData::Path(other)) => {- data.bounding_rect == other.bounding_rect- && data.fill_rule == other.fill_rule- && (std::sync::Arc::ptr_eq(&data.path, &other.path) || *data.path == *other.path)- }- _ => false,- }-}--fn effect_data_is_equal(a: &EffectNodeData, b: &EffectNodeData) -> bool {- match (a, b) {- (EffectNodeData::BackgroundColorAnimation, EffectNodeData::BackgroundColorAnimation) => true,- (EffectNodeData::Effects(data), EffectNodeData::Effects(other)) => {- data.isolation == other.isolation- && data.opacity == other.opacity- && data.blend_mode == other.blend_mode- && data.filter == other.filter- && data.backdrop_filter == other.backdrop_filter- }- (EffectNodeData::Mask(data), EffectNodeData::Mask(other)) => data == other,- _ => false,- }-}--fn propagate_changes_to_descendants(changed: &mut [bool], parent_of: impl Fn(usize) -> Option<usize>) {- if !changed.contains(&true) {- return;- }- let node_count = changed.len();- let mut verdicts: Vec<Option<bool>> = changed.iter().map(|&changed| changed.then_some(true)).collect();- let mut unresolved_ancestors = Vec::new();- for start in 0..node_count {- let mut node = start;- let chain_changed = loop {- if let Some(verdict) = verdicts[node] {- break verdict;- }- if unresolved_ancestors.len() > node_count {- break true;- }- unresolved_ancestors.push(node);- match parent_of(node) {- None => break false,- Some(parent) if parent < node_count => node = parent,- Some(_) => break true,- }- };- for node in unresolved_ancestors.drain(..) {- verdicts[node] = Some(chain_changed);- }- }- for (changed, verdict) in changed.iter_mut().zip(verdicts) {- *changed = verdict.unwrap_or(true);- }-}--#[derive(Default)]-struct ChangedVisualContextNodes {- spatial: Vec<bool>,- clip: Vec<bool>,- effect: Vec<bool>,- any_changed: bool,-}--fn changed_spatial_nodes(- (old_tree, old_scroll_offsets): (&VisualContextTree, &[FloatPoint]),- (new_tree, new_scroll_offsets): (&VisualContextTree, &[FloatPoint]),-) -> Vec<bool> {- let mut changed: Vec<bool> = (0..old_tree.spatial_nodes.len().max(new_tree.spatial_nodes.len()))- .map(|index| {- let (Some(old_node), Some(new_node)) =- (old_tree.spatial_nodes.get(index), new_tree.spatial_nodes.get(index))- else {- return true;- };- old_node.parent != new_node.parent- || !spatial_data_is_equal(- SpatialNodeIndex(index as u32),- &old_node.data,- old_scroll_offsets,- &new_node.data,- new_scroll_offsets,- )- })- .collect();- propagate_changes_to_descendants(&mut changed, |index| {- (index != VISUAL_VIEWPORT_NODE_INDEX.0 as usize).then(|| new_tree.spatial_nodes[index].parent.0 as usize)- });- changed-}--fn changed_clip_nodes(- old_tree: &VisualContextTree,- new_tree: &VisualContextTree,- changed_spatial_nodes: &[bool],-) -> Vec<bool> {- let mut changed: Vec<bool> = (0..old_tree.clip_nodes.len().max(new_tree.clip_nodes.len()))- .map(|index| {- let (Some(old_node), Some(new_node)) = (old_tree.clip_nodes.get(index), new_tree.clip_nodes.get(index))- else {- return true;- };- old_node.parent != new_node.parent- || old_node.spatial != new_node.spatial- || !clip_data_is_equal(&old_node.data, &new_node.data)- || changed_spatial_nodes- .get(new_node.spatial.0 as usize)- .is_none_or(|changed| *changed)- })- .collect();- propagate_changes_to_descendants(&mut changed, |index| {- let parent = new_tree.clip_nodes[index].parent;- (!parent.is_none()).then_some(parent.0 as usize)- });- changed-}--fn effect_nodes_that_differ_where_they_are(- (old_tree, old_effect_clips): (&VisualContextTree, &EffectClipPlan),- (new_tree, new_effect_clips): (&VisualContextTree, &EffectClipPlan),- changed_spatial_nodes: &[bool],- changed_clip_nodes: &[bool],-) -> Vec<bool> {- let clip_changed = |clip: ClipNodeIndex| changed_clip_nodes.get(clip.0 as usize).copied().unwrap_or(false);- (0..old_tree.effect_nodes.len().max(new_tree.effect_nodes.len()))- .map(|index| {- let (Some(old_node), Some(new_node)) = (old_tree.effect_nodes.get(index), new_tree.effect_nodes.get(index))- else {- return true;- };- let effect = EffectNodeIndex(index as u32);- let new_output_clip = new_effect_clips.output_clip_if_participating(effect);- old_node.parent != new_node.parent- || old_node.spatial != new_node.spatial- || old_node.local_clip != new_node.local_clip- || old_effect_clips.output_clip_if_participating(effect) != new_output_clip- || !effect_data_is_equal(&old_node.data, &new_node.data)- || changed_spatial_nodes- .get(new_node.spatial.0 as usize)- .is_none_or(|changed| *changed)- || clip_changed(new_node.local_clip)- || new_output_clip.is_some_and(clip_changed)- })- .collect()-}--impl ChangedVisualContextNodes {- fn spatial_changed(&self, index: SpatialNodeIndex) -> bool {- self.spatial.get(index.0 as usize).copied().unwrap_or(false)- }-- fn clip_changed(&self, index: ClipNodeIndex) -> bool {- self.clip.get(index.0 as usize).copied().unwrap_or(false)- }-- fn effect_changed(&self, index: EffectNodeIndex) -> bool {- self.effect.get(index.0 as usize).copied().unwrap_or(false)- }-- fn chains_changed(&self, context: ContextRef) -> bool {- self.spatial_changed(context.spatial) || self.clip_changed(context.clip) || self.effect_changed(context.effect)- }-- fn mark_effect_changed(&mut self, effect: EffectNodeIndex) {- if let Some(changed) = self.effect.get_mut(effect.0 as usize) {- *changed = true;- }- }-- fn between(- old: &DiffSide<'_>,- new: &DiffSide<'_>,- scroll_offsets_differ: bool,- pairings: impl Iterator<Item = ChunkPairing>,- ) -> Self {- let (old_tree, new_tree) = (old.geometry.tree, new.geometry.tree);- let (old_effect_clips, new_effect_clips) = (old.geometry.effect_clips, new.geometry.effect_clips);- let trees_draw_alike = std::ptr::eq(old_tree, new_tree)- && !scroll_offsets_differ- && (std::ptr::eq(old_effect_clips, new_effect_clips) || old_effect_clips == new_effect_clips);- if trees_draw_alike && std::ptr::eq(old.frame.chunks, new.frame.chunks) {- return Self::default();- }-- let mut changed = Self::default();- if trees_draw_alike {- changed.effect = vec![false; new_tree.effect_nodes.len()];- } else {- changed.spatial = changed_spatial_nodes(- (old_tree, old.geometry.scroll_offsets),- (new_tree, new.geometry.scroll_offsets),- );- changed.clip = changed_clip_nodes(old_tree, new_tree, &changed.spatial);- changed.effect = effect_nodes_that_differ_where_they_are(- (old_tree, old_effect_clips),- (new_tree, new_effect_clips),- &changed.spatial,- &changed.clip,- );- }- for effect in changed.effects_whose_mask_content_changed(old, new, pairings) {- changed.mark_effect_changed(effect);- }- if old_tree.root_isolation_effect != new_tree.root_isolation_effect {- for effect in [old_tree.root_isolation_effect, new_tree.root_isolation_effect]- .into_iter()- .flatten()- {- changed.mark_effect_changed(effect);- }- }- propagate_changes_to_descendants(&mut changed.effect, |index| {- let parent = new_tree.effect_nodes.get(index)?.parent;- (!parent.is_none()).then_some(parent.0 as usize)- });-- changed.any_changed =- changed.spatial.contains(&true) || changed.clip.contains(&true) || changed.effect.contains(&true);- changed- }-- fn effects_whose_mask_content_changed(- &self,- old: &DiffSide<'_>,- new: &DiffSide<'_>,- pairings: impl Iterator<Item = ChunkPairing>,- ) -> Vec<EffectNodeIndex> {- let declaration_moved = |run_index: u32| {- let context = new.frame.command_runs[run_index as usize].context;- self.spatial_changed(context.spatial) || self.clip_changed(context.clip)- };- let mut effects = Vec::new();- for pairing in pairings {- let (side, chunk, declaration_changed): (_, _, &dyn Fn(u32) -> bool) = match pairing {- ChunkPairing::OnlyOld(chunk) => (old, chunk, &|_| true),- ChunkPairing::OnlyNew(chunk) => (new, chunk, &|_| true),- ChunkPairing::Matched { new: chunk, .. } => (new, chunk, &declaration_moved),- };- for record in side.frame.chunks.records_reaching_outside(chunk) {- if let ReachOutsideChunk::DeclaresMaskContentOf(effect) = record.reach- && declaration_changed(record.run_index)- {- effects.push(effect);- }- }- }- effects- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum ChunkPairing {- Matched { old: usize, new: usize },- OnlyOld(usize),- OnlyNew(usize),-}--fn chunk_positions_by_id(chunks: &TapeChunks, positions: std::ops::Range<usize>) -> Vec<([u64; 2], usize)> {- let mut positions_by_id: Vec<([u64; 2], usize)> =- positions.map(|position| (chunks.id(position).0, position)).collect();- positions_by_id.sort_unstable();- positions_by_id-}--fn next_position_of(positions_by_id: &[([u64; 2], usize)], id: [u64; 2], from: usize) -> Option<usize> {- let first_at_or_after = positions_by_id.partition_point(|&entry| entry < (id, from));- positions_by_id- .get(first_at_or_after)- .filter(|(other_id, _)| *other_id == id)- .map(|&(_, position)| position)-}--fn pair_chunks_by_name(old: &TapeChunks, new: &TapeChunks) -> Vec<ChunkPairing> {- let (old_count, new_count) = (old.len(), new.len());- let mut pairings = Vec::with_capacity(old_count.max(new_count));- let common_prefix_count = (0..old_count.min(new_count))- .take_while(|&index| old.id(index) == new.id(index))- .count();- let common_suffix_count = (0..old_count.min(new_count) - common_prefix_count)- .take_while(|&from_end| old.id(old_count - from_end - 1) == new.id(new_count - from_end - 1))- .count();- pairings.extend((0..common_prefix_count).map(|index| ChunkPairing::Matched { old: index, new: index }));-- let (old_middle_end, new_middle_end) = (old_count - common_suffix_count, new_count - common_suffix_count);- let (mut old_index, mut new_index) = (common_prefix_count, common_prefix_count);- if old_index < old_middle_end && new_index < new_middle_end {- let old_positions_by_id = chunk_positions_by_id(old, old_index..old_middle_end);- let new_positions_by_id = chunk_positions_by_id(new, new_index..new_middle_end);- while old_index < old_middle_end && new_index < new_middle_end {- let (old_id, new_id) = (old.id(old_index), new.id(new_index));- if old_id == new_id {- pairings.push(ChunkPairing::Matched {- old: old_index,- new: new_index,- });- old_index += 1;- new_index += 1;- continue;- }- match (- next_position_of(&new_positions_by_id, old_id.0, new_index),- next_position_of(&old_positions_by_id, new_id.0, old_index),- ) {- (Some(old_id_in_new), Some(new_id_in_old)) if old_id_in_new - new_index < new_id_in_old - old_index => {- pairings.push(ChunkPairing::OnlyNew(new_index));- new_index += 1;- }- (Some(_), None) => {- pairings.push(ChunkPairing::OnlyNew(new_index));- new_index += 1;- }- (_, Some(_)) => {- pairings.push(ChunkPairing::OnlyOld(old_index));- old_index += 1;- }- (None, None) => {- pairings.push(ChunkPairing::OnlyOld(old_index));- pairings.push(ChunkPairing::OnlyNew(new_index));- old_index += 1;- new_index += 1;- }- }- }- }- pairings.extend((old_index..old_middle_end).map(ChunkPairing::OnlyOld));- pairings.extend((new_index..new_middle_end).map(ChunkPairing::OnlyNew));-- pairings.extend((0..common_suffix_count).map(|from_start| ChunkPairing::Matched {- old: old_middle_end + from_start,- new: new_middle_end + from_start,- }));- pairings-}--struct SideGeometry<'a> {- tree: &'a VisualContextTree,- scroll_offsets: &'a [FloatPoint],- effect_clips: &'a EffectClipPlan,- culling: OnceCell<TreeCullingScratch>,- nearest_spreading_effects: OnceCell<Vec<EffectNodeIndex>>,- world_transforms: OnceCell<WorldTransforms>,-}--impl<'a> SideGeometry<'a> {- fn new(tree: &'a VisualContextTree, scroll_offsets: &'a [FloatPoint], effect_clips: &'a EffectClipPlan) -> Self {- Self {- tree,- scroll_offsets,- effect_clips,- culling: OnceCell::new(),- nearest_spreading_effects: OnceCell::new(),- world_transforms: OnceCell::new(),- }- }-- // Damage maps commands with the matrices replay draws them with.- fn world(&self) -> &WorldTransforms {- self.world_transforms- .get_or_init(|| WorldTransforms::new(self.tree, self.scroll_offsets, Some(FloatMatrix4x4::identity())))- }-- fn culling(&self) -> &TreeCullingScratch {- self.culling.get_or_init(|| {- let mut culling = TreeCullingScratch::default();- self.tree.fill_culling_scratch(&mut culling);- culling- })- }-- fn nearest_spreading_effects(&self) -> &[EffectNodeIndex] {- self.nearest_spreading_effects- .get_or_init(|| nearest_spreading_effects(self.tree))- }-- // Where a command's inline clips in spaces of their own let it draw on one side of the comparison.- fn own_space_clip_extent_of(&self, record: &RecordOnTape<'_>) -> Option<OwnSpaceClipExtent> {- if record.header.inline_clip_count == 0 || !has_inline_clip_in_its_own_space(&record.header, record.payload) {- return None;- }- let bounding_rect = bounding_rect_computed_from_payload(&record.header, record.payload)?;- let world = self.world();- own_space_clip_extent(- &record.header,- record.payload,- bounding_rect.to_float(),- world.draw_matrix_if_known(record.context.spatial)?,- |space| world.draw_matrix_if_known(space),- )- }-}--struct DiffSide<'a> {- frame: DisplayListFrame<'a>,- geometry: SideGeometry<'a>,- side: FrameSide,-}--impl<'a> DiffSide<'a> {- fn new(frame: DisplayListFrame<'a>, side: FrameSide) -> Self {- Self {- frame,- geometry: SideGeometry::new(frame.visual_context_tree, frame.scroll_offsets, frame.effect_clip_plan),- side,- }- }-- fn record_at(&self, record: &TopLevelRecordReachingOutsideItsChunk) -> RecordOnTape<'a> {- RecordOnTape::at(- self.frame.command_bytes,- record.record_offset,- self.frame.command_runs[record.run_index as usize].context,- )- }-}--// The viewport bounds that the clips outside every filter on a context's effect chain put on the-// filtered output, or None when no rect clip bounds it. Replay can widen an effect's output clip-// for escaping descendants, so the complete display list's layer plan says which clips are outside.-fn filter_output_clip_bounds(context: ContextRef, side: &SideGeometry<'_>) -> Option<FloatRect> {- let (tree, effect_clips) = (side.tree, side.effect_clips);- let mut clip = context.clip;- let mut effect = context.effect;- while !effect.is_none() {- let node = &tree.effect_nodes[effect.0 as usize];- if let EffectNodeData::Effects(effects) = &node.data- && (effects.filter.is_some() || effects.backdrop_filter.is_some())- {- clip = effect_clips.output_clip(effect);- }- effect = node.parent;- }- let mut output_bounds: Option<FloatRect> = None;- while !clip.is_none() {- let node = &tree.clip_nodes[clip.0 as usize];- if let ClipNodeData::Rect(data) = &node.data- && data.mode == ClipMode::Intersect- {- let bounds = side- .world()- .map_rect_to_root(node.spatial, data.rect)- .inflated(1.0, 1.0);- if bounds.x.is_finite() && bounds.y.is_finite() && bounds.width.is_finite() && bounds.height.is_finite() {- output_bounds = Some(output_bounds.map_or(bounds, |output_bounds| output_bounds.intersected(bounds)));- }- }- clip = node.parent;- }- output_bounds-}--fn intersect_like_gfx_int_rect(rect: IntRect, other: IntRect) -> IntRect {- let left = rect.x.max(other.x);- let right = rect.right().min(other.right());- let top = rect.y.max(other.y);- let bottom = rect.bottom().min(other.bottom());- if left > right || top > bottom {- return IntRect::default();- }- IntRect::new(left, top, right - left, bottom - top)-}--/// The layer plans of the old and the new frame, which have the same layers. A layer keeps its raster between the-/// frames, so damage is attributed to the layers that draw the content it comes from.-#[derive(Clone, Copy)]-pub struct LayerPlans<'a> {- pub old: &'a LayerPlan,- pub new: &'a LayerPlan,-}--#[derive(Clone, Copy)]-enum FrameSide {- Old,- New,-}--#[derive(Clone, Copy)]-enum DamagedLayers {- OfRecord(FrameSide, u32),- OfRun(FrameSide, DisplayListCommandRun),- All,-}--#[derive(Clone, Copy, Default)]-struct LayerDamage {- rect: Option<IntRect>,- is_unbounded: bool,-}--struct DamageAccumulator<'a> {- damage_rect: Option<IntRect>,- changed_unbounded_command: bool,- viewport_rect: IntRect,- layer_plans: Option<LayerPlans<'a>>,- damage_of_layers: Vec<LayerDamage>,-}--impl DamageAccumulator<'_> {- // Once the damage covers the viewport in every raster it reaches, no further command can change the outcome.- fn covers_viewport(&self) -> bool {- let covers = |is_unbounded: bool, rect: Option<IntRect>| {- is_unbounded || rect.is_some_and(|rect| rect.contains_rect(self.viewport_rect))- };- covers(self.changed_unbounded_command, self.damage_rect)- && self.layer_plans.is_none_or(|plans| {- plans- .new- .layers- .iter()- .zip(&self.damage_of_layers)- .all(|(layer, damage)| {- matches!(layer.kind, LayerKind::Media { .. }) || covers(damage.is_unbounded, damage.rect)- })- })- }-- fn for_each_damaged_layer(&mut self, layers: DamagedLayers, mut f: impl FnMut(&mut LayerDamage)) {- let Some(plans) = self.layer_plans else {- return;- };- let plan_of = |side: FrameSide| match side {- FrameSide::Old => plans.old,- FrameSide::New => plans.new,- };- match layers {- DamagedLayers::OfRecord(side, record_offset) => {- f(&mut self.damage_of_layers[plan_of(side).layer_of_record(record_offset)]);- }- DamagedLayers::OfRun(side, run) => {- for layer in plan_of(side).layers_drawing_records_of(&run) {- f(&mut self.damage_of_layers[layer]);- }- }- DamagedLayers::All => self.damage_of_layers.iter_mut().for_each(f),- }- }-- fn add_unbounded_damage(&mut self, layers: DamagedLayers) {- self.changed_unbounded_command = true;- self.for_each_damaged_layer(layers, |damage| damage.is_unbounded = true);- }-- fn add_damage_rect(&mut self, rect: IntRect, layers: DamagedLayers) {- let united =- |damage_rect: Option<IntRect>| Some(damage_rect.map_or(rect, |damage_rect| damage_rect.united(rect)));- self.damage_rect = united(self.damage_rect);- self.for_each_damaged_layer(layers, |damage| damage.rect = united(damage.rect));- }-- fn add_record_damage(&mut self, side: &DiffSide<'_>, record: &RecordOnTape<'_>) {- if side.geometry.culling().context_culls_everything(record.context) {- return;- }- if record.header.command_type.is_compositor_metadata() {- return;- }- // The bounds of a command leave out its inline clips in spaces of their own, so they limit it here.- let rect = match side.geometry.own_space_clip_extent_of(record) {- Some(OwnSpaceClipExtent::Within(rect)) => rect,- _ => bounding_rect_computed_from_payload(&record.header, record.payload)- .unwrap_or_default()- .to_float(),- };- if rect.is_empty() {- return;- }- self.add_changed_content_damage(- rect,- record.context,- &side.geometry,- DamagedLayers::OfRecord(side.side, record.record_offset),- );- }-- fn add_run_damage(&mut self, side: &DiffSide<'_>, run: &DisplayListCommandRun) {- if side.geometry.culling().context_culls_everything(run.context) {- return;- }- let rect = run.ink_bounds.to_float();- if rect.is_empty() {- return;- }- self.add_changed_content_damage(rect, run.context, &side.geometry, DamagedLayers::OfRun(side.side, *run));- }-- // Damage for content drawn within `rect` in `context` that changed, wherever the filters above- // it spread the change.- fn add_changed_content_damage(- &mut self,- rect: FloatRect,- context: ContextRef,- side: &SideGeometry<'_>,- layers: DamagedLayers,- ) {- let nearest_spreading_effects = side.nearest_spreading_effects();- let spread_by_filters =- !context.effect.is_none() && !nearest_spreading_effects[context.effect.0 as usize].is_none();- let (space, extent) = changed_extent_through_filters(- side.tree,- nearest_spreading_effects,- context.spatial,- rect,- context.effect,- side.world(),- );- // Spread content can reach far past the clips it was drawn in, but not past those outside- // the filters.- let output_clip_bounds = if spread_by_filters {- filter_output_clip_bounds(context, side)- } else {- None- };- let mut transformed_rect = match (extent, output_clip_bounds) {- (Extent::Within(rect), _) => side.world().map_rect_to_root(space, rect),- (_, Some(output_clip_bounds)) => output_clip_bounds,- _ => {- self.add_unbounded_damage(layers);- return;- }- };- // Transform matrices with entries near float max can overflow the projection to non-finite values.- // NaN survives both intersect() and is_empty(), so treat such rects as unbounded damage instead of- // feeding them to enclosing_int_rect(), where the float-to-int conversion would be undefined.- if !transformed_rect.x.is_finite()- || !transformed_rect.y.is_finite()- || !transformed_rect.width.is_finite()- || !transformed_rect.height.is_finite()- {- self.add_unbounded_damage(layers);- return;- }- if let Some(output_clip_bounds) = output_clip_bounds {- transformed_rect = transformed_rect.intersected(output_clip_bounds);- }- // Eye-plane clamping in the projection can produce coordinates beyond integer range, and converting- // such a float to int is undefined.- const DAMAGE_COORDINATE_LIMIT: f32 = 16777216.0;- transformed_rect = transformed_rect.intersected(FloatRect::new(- -DAMAGE_COORDINATE_LIMIT,- -DAMAGE_COORDINATE_LIMIT,- 2.0 * DAMAGE_COORDINATE_LIMIT,- 2.0 * DAMAGE_COORDINATE_LIMIT,- ));- if transformed_rect.is_empty() {- return;- }- self.add_damage_rect(enclosing_int_rect(transformed_rect), layers);- }-- // A backdrop filter can read the pixels around its region, so damage beneath the region changes it- // wherever the filter carries that damage in. The whole region then changes as content of the- // backdrop's effect: that effect's own filter and the filters above it spread it further, and it- // can carry the damage on to the backdrop filters above it.- fn add_backdrop_filter_damage(&mut self, side: &SideGeometry<'_>, command_runs: &[DisplayListCommandRun]) {- let tree = side.tree;- let backdrop_of = |effect: EffectNodeIndex| match &tree.effect_nodes[effect.0 as usize].data {- EffectNodeData::Effects(effects) => effects.backdrop_filter.as_ref(),- _ => None,- };- if self.damage_rect.is_none()- || !(0..tree.effect_nodes.len()).any(|index| backdrop_of(EffectNodeIndex(index as u32)).is_some())- {- return;- }- let mut seen_effects = vec![false; tree.effect_nodes.len()];- // Each effect with a backdrop filter, with the offset of its first record.- let mut backdrop_effects = Vec::new();- for run in command_runs {- let mut effect = run.context.effect;- while !effect.is_none() && !seen_effects[effect.0 as usize] {- seen_effects[effect.0 as usize] = true;- if backdrop_of(effect).is_some() {- backdrop_effects.push((effect, run.offset));- }- effect = tree.effect_nodes[effect.0 as usize].parent;- }- }-- let mut region_is_damaged = vec![false; backdrop_effects.len()];- loop {- if self.covers_viewport() {- return;- }- let Some(damage_rect) = self.damage_rect else {- return;- };- let damage = damage_rect.to_float();- let mut damage_grew = false;- for (index, &(effect, first_record_offset)) in backdrop_effects.iter().enumerate() {- if region_is_damaged[index] {- continue;- }- let node = &tree.effect_nodes[effect.0 as usize];- let backdrop = backdrop_of(effect).expect("only effects with a backdrop filter are collected");- let region = backdrop.region.to_float();- let to_root_matrix = side.world().draw_matrix(node.spatial);- let reads_damage = (|| {- if !to_root_matrix.is_2d_affine() {- return None;- }- let damage_in_effect_space = to_root_matrix.extract_2d_affine().inverse()?.map_rect(damage);- let reached = crate::filter_bytes::changed_output_bounds(&backdrop.filter, damage_in_effect_space)?;- Some(!reached.intersected(region).is_empty())- })()- .unwrap_or(true);- if !reads_damage {- continue;- }- region_is_damaged[index] = true;- damage_grew = true;- let backdrop_context = ContextRef {- spatial: node.spatial,- clip: side.effect_clips.output_clip(effect),- effect,- };- self.add_changed_content_damage(- region,- backdrop_context,- side,- DamagedLayers::OfRecord(FrameSide::New, first_record_offset),- );- }- if !damage_grew {- return;- }- }- }-- fn add_unmatched_chunk_damage(&mut self, side: &DiffSide<'_>, chunk: usize, changed: &ChangedVisualContextNodes) {- let chunks = side.frame.chunks;- for run in &side.frame.command_runs[chunks.runs_of(chunk)] {- if self.covers_viewport() {- return;- }- self.add_run_damage(side, run);- }- for record in chunks.records_reaching_outside(chunk) {- if record.reach == ReachOutsideChunk::ScrollbarPaintedByCompositor- && changed.chains_changed(side.frame.command_runs[record.run_index as usize].context)- {- self.changed_unbounded_command = true;- }- }- }-- // A command that draws in a different space than one of its inline clips shows another part of- // itself whenever one of the two spaces moves, though neither the command nor its context changed.- // Where the clips can be mapped into the command's space, command damage covers only what they let it draw.- fn add_inline_clip_scroll_damage(- &mut self,- (old, old_record): (&DiffSide<'_>, &RecordOnTape<'_>),- (new, new_record): (&DiffSide<'_>, &RecordOnTape<'_>),- changed: &ChangedVisualContextNodes,- ) {- if !inline_clips_of(&new_record.header, new_record.payload)- .any(|clip| clip.has_own_space && changed.spatial_changed(clip.space))- {- return;- }- let clips_did_not_move = match (- old.geometry.own_space_clip_extent_of(old_record),- new.geometry.own_space_clip_extent_of(new_record),- ) {- (None, None) => true,- (Some(OwnSpaceClipExtent::Within(old_rect)), Some(OwnSpaceClipExtent::Within(new_rect))) => {- old_rect == new_rect- }- _ => false,- };- if clips_did_not_move {- return;- }- self.add_record_damage(old, old_record);- self.add_record_damage(new, new_record);- }-- fn add_matched_chunk_damage(- &mut self,- (old, old_chunk): (&DiffSide<'_>, usize),- (new, new_chunk): (&DiffSide<'_>, usize),- changed: &ChangedVisualContextNodes,- scroll_offsets_differ: bool,- ) {- let (old_runs, new_runs) = (old.frame.chunks.runs_of(old_chunk), new.frame.chunks.runs_of(new_chunk));- debug_assert_eq!(old_runs.len(), new_runs.len(), "chunks of one name hold the same runs");- let mut records_reaching_outside = old- .frame- .chunks- .records_reaching_outside(old_chunk)- .iter()- .zip(new.frame.chunks.records_reaching_outside(new_chunk))- .peekable();- for (old_run_index, new_run_index) in old_runs.zip(new_runs) {- if self.covers_viewport() {- return;- }- let (old_run, new_run) = (- &old.frame.command_runs[old_run_index],- &new.frame.command_runs[new_run_index],- );- let run_moved = changed.chains_changed(new_run.context);- let run_changes_layers = self- .layer_plans- .is_some_and(|plans| !plans.old.places_run_like(old_run, plans.new, new_run));- if run_moved || run_changes_layers {- self.add_run_damage(old, old_run);- self.add_run_damage(new, new_run);- }- while let Some((old_record, new_record)) =- records_reaching_outside.next_if(|(old_record, _)| old_record.run_index as usize == old_run_index)- {- match new_record.reach {- ReachOutsideChunk::ScrollbarPaintedByCompositor => {- if run_moved {- self.changed_unbounded_command = true;- }- }- _ if run_moved || run_changes_layers => {}- ReachOutsideChunk::ScrollbarThumbFollowsScrollOffsetOf(scroll_node) => {- if scroll_offsets_differ- && device_offset_for_index(old.frame.scroll_offsets, scroll_node)- != device_offset_for_index(new.frame.scroll_offsets, scroll_node)- {- self.add_record_damage(old, &old.record_at(old_record));- self.add_record_damage(new, &new.record_at(new_record));- }- }- ReachOutsideChunk::InlineClipInItsOwnSpace => {- if changed.any_changed {- self.add_inline_clip_scroll_damage(- (old, &old.record_at(old_record)),- (new, &new.record_at(new_record)),- changed,- );- }- }- ReachOutsideChunk::DeclaresMaskContentOf(_) => {}- }- }- }- }-}--// This query is cached until scene geometry or scrolling changes. It deliberately ignores clips when-// bounding rotating content, so animation phases cannot reveal pixels outside the computed bounds.-/// Whether the content the tree's animations move at `sample_time_ns` can reach the viewport. The-/// finished animations keep their final values in place; the running ones must all be opacity or-/// plane rotations, whose extents the bounds query can replace, for the answer to be anything but-/// yes.-pub fn animated_content_may_affect_viewport_at(- command_bytes: &[u8],- command_runs: &[DisplayListCommandRun],- tree: &VisualContextTree,- scroll_offsets: &[FloatPoint],- viewport_rect: IntRect,- sample_time_ns: i64,-) -> FfiAnimatedContentViewportEffect {- let extents = tree.visual_animation_extents_at(sample_time_ns);- if !extents.all_running_animations_are_bounded {- return FfiAnimatedContentViewportEffect {- may_affect_viewport: true,- stable_until_scene_changes: false,- };- }- let bounded = |tree: &VisualContextTree| {- animated_content_may_affect_viewport(- command_bytes,- command_runs,- tree,- scroll_offsets,- &extents.rotation_nodes,- &extents.opacity_nodes,- viewport_rect,- )- };- let may_affect_viewport = if extents.has_finished_animation {- bounded(&tree.with_visual_animation_samples(sample_time_ns))- } else {- bounded(tree)- };- FfiAnimatedContentViewportEffect {- may_affect_viewport,- stable_until_scene_changes: !extents.has_unfinished_finite_animation,- }-}--pub fn animated_content_may_affect_viewport(- command_bytes: &[u8],- command_runs: &[DisplayListCommandRun],- tree: &VisualContextTree,- scroll_offsets: &[FloatPoint],- rotation_nodes: &[SpatialNodeIndex],- opacity_nodes: &[EffectNodeIndex],- viewport_rect: IntRect,-) -> bool {- let in_rotating_subtree = tree.spatial_nodes_in_subtrees_of(rotation_nodes);- let mut rotating_nodes = vec![false; tree.spatial_nodes.len()];- for node in rotation_nodes {- let Some(flag) = rotating_nodes.get_mut(node.0 as usize) else {- return true;- };- *flag = true;- }- let world = OnceCell::new();- let mut may_affect_viewport = false;- for run in command_runs {- let run_bytes = &command_bytes[run.offset as usize..(run.offset + run.size) as usize];- for_each_command(run_bytes, |header, _, payload| {- if may_affect_viewport || header.command_type.is_compositor_metadata() {- return;- }- let spatial_is_animated = in_rotating_subtree[run.context.spatial.0 as usize];- let has_inline_clip_in_its_own_space =- header.inline_clip_count != 0 && has_inline_clip_in_its_own_space(header, payload);- if has_inline_clip_in_its_own_space- && !spatial_is_animated- && inline_clips_of(header, payload).any(|inline_clip| {- inline_clip.has_own_space- && in_rotating_subtree- .get(inline_clip.space.0 as usize)- .is_none_or(|is_animated| *is_animated)- })- {- may_affect_viewport = true;- return;- }- let mut clip = run.context.clip;- while !clip.is_none() {- let node = &tree.clip_nodes[clip.0 as usize];- if !spatial_is_animated && in_rotating_subtree[node.spatial.0 as usize] {- may_affect_viewport = true;- return;- }- clip = node.parent;- }- let mut effect = run.context.effect;- let mut opacity_is_animated = false;- let mut has_filter = false;- while !effect.is_none() {- let node = &tree.effect_nodes[effect.0 as usize];- opacity_is_animated |= opacity_nodes.contains(&effect);- if !spatial_is_animated && in_rotating_subtree[node.spatial.0 as usize] {- may_affect_viewport = true;- return;- }- if let EffectNodeData::Effects(effects) = &node.data- && (effects.filter.is_some() || effects.backdrop_filter.is_some())- {- has_filter = true;- }- effect = node.parent;- }- if !spatial_is_animated && !opacity_is_animated {- return;- }- // Filters can expand the output beyond the command bounds.- if has_filter {- may_affect_viewport = true;- return;- }- let bounding_rect = bounding_rect_computed_from_payload(header, payload);- let mut rect = bounding_rect.unwrap_or_default().to_float();- if has_inline_clip_in_its_own_space && bounding_rect.is_some() {- let world =- world.get_or_init(|| WorldTransforms::new(tree, scroll_offsets, Some(FloatMatrix4x4::identity())));- if let Some(command_to_root) = world.draw_matrix_if_known(run.context.spatial)- && let Some(OwnSpaceClipExtent::Within(clipped_rect)) =- own_space_clip_extent(header, payload, rect, command_to_root, |space| {- world.draw_matrix_if_known(space)- })- {- if clipped_rect.is_empty() {- return;- }- rect = clipped_rect;- }- }- let Some(bounds) =- tree.rect_with_rotation_bounds_to_viewport(run.context.spatial, rect, &rotating_nodes, scroll_offsets)- else {- may_affect_viewport = true;- return;- };- let bounds = bounds.inflated(2.0, 2.0);- may_affect_viewport = bounds.x <= viewport_rect.right() as f32- && bounds.right() >= viewport_rect.x as f32- && bounds.y <= viewport_rect.bottom() as f32- && bounds.bottom() >= viewport_rect.y as f32;- });- }- may_affect_viewport-}--// One frame's display list with the tree and scroll offsets it was replayed under.-#[derive(Clone, Copy)]-pub struct DisplayListFrame<'a> {- pub command_bytes: &'a [u8],- pub command_runs: &'a [DisplayListCommandRun],- pub chunks: &'a TapeChunks,- pub effect_clip_plan: &'a EffectClipPlan,- pub summary: &'a DisplayListSummary,- pub visual_context_tree: &'a VisualContextTree,- pub scroll_offsets: &'a [FloatPoint],-}--// The canvases, video sinks, image frames and frames of nested contexts whose pixels changed since the old frame.-// The lists draw them with commands that stay the same, so the diff cannot see the change.-#[derive(Clone, Copy, Default)]-pub struct LiveContentChanges<'a> {- pub canvases: &'a [CanvasId],- pub video_sinks: &'a [VideoSinkHandle],- pub image_frames: &'a [ImageFrameResourceId],- pub composited_contexts: &'a [CompositorContextId],- /// What the compositor repaints whatever the lists hold, such as a blinking caret.- pub forced_damage_rect: IntRect,- pub offsets_of_records_composited_as_media_layers: &'a [u32],-}--#[derive(Clone, Debug, PartialEq)]-pub struct DisplayListDamage {- pub rect: Option<IntRect>,- /// With the frames' layer plans, the damage of each layer, none where that has no bounds.- pub layer_rects: Vec<Option<IntRect>>,-}--impl DisplayListDamage {- pub fn unbounded(layer_count: usize) -> Self {- Self {- rect: None,- layer_rects: vec![None; layer_count],- }- }-}--impl LiveContentChanges<'_> {- fn is_empty(&self) -> bool {- self.canvases.is_empty()- && self.video_sinks.is_empty()- && self.image_frames.is_empty()- && self.composited_contexts.is_empty()- }-- fn includes(&self, content: LiveContent) -> bool {- match content {- LiveContent::Canvas(canvas_id) => self.canvases.contains(&canvas_id),- LiveContent::VideoFrame(video_sink_handle) => self.video_sinks.contains(&video_sink_handle),- LiveContent::ImageFrame(image_frame_id) => self.image_frames.contains(&image_frame_id),- LiveContent::CompositedContext(context_id) => self.composited_contexts.contains(&context_id),- }- }-}--// The viewport-space damage between two frames, or None when a change without bounds needs a-// full repaint. The diff pairs the chunks of the two lists by name in paint order: a chunk without-// a partner is damaged run by run, and a paired chunk only where its runs' visual contexts, its-// records' layers or what its records read outside it changed. The diff stops as soon as the-// damage covers the viewport, so a later unbounded change may then be reported as the viewport-// rect instead of None. Given the frames' layer plans, the damage of each layer is reported too.-pub fn compute_display_list_damage(- old_frame: DisplayListFrame<'_>,- new_frame: DisplayListFrame<'_>,- viewport_rect: IntRect,- live_content_changes: LiveContentChanges<'_>,- layer_plans: Option<LayerPlans<'_>>,-) -> DisplayListDamage {- let layer_count = layer_plans.map_or(0, |plans| plans.new.layers.len());- let old = DiffSide::new(old_frame, FrameSide::Old);- let new = DiffSide::new(new_frame, FrameSide::New);- let mut damage = DamageAccumulator {- damage_rect: None,- changed_unbounded_command: false,- viewport_rect,- layer_plans,- damage_of_layers: vec![LayerDamage::default(); layer_count],- };-- let same_chunk_list = std::ptr::eq(old_frame.chunks, new_frame.chunks);- let paired_by_name = if same_chunk_list {- Vec::new()- } else {- pair_chunks_by_name(old_frame.chunks, new_frame.chunks)- };- let pairings = || {- (0..if same_chunk_list { new_frame.chunks.len() } else { 0 })- .map(|index| ChunkPairing::Matched { old: index, new: index })- .chain(paired_by_name.iter().copied())- };- let scroll_offsets_differ = old_frame.scroll_offsets != new_frame.scroll_offsets;- let changed = ChangedVisualContextNodes::between(&old, &new, scroll_offsets_differ, pairings());- let nothing_in_paired_chunks_can_differ = same_chunk_list- && !changed.any_changed- && !scroll_offsets_differ- && layer_plans.is_none_or(|plans| plans.old.places_records_like(plans.new));- if !nothing_in_paired_chunks_can_differ {- for pairing in pairings() {- if damage.covers_viewport() {- break;- }- match pairing {- ChunkPairing::Matched {- old: old_chunk,- new: new_chunk,- } => damage.add_matched_chunk_damage(- (&old, old_chunk),- (&new, new_chunk),- &changed,- scroll_offsets_differ,- ),- ChunkPairing::OnlyOld(chunk) => damage.add_unmatched_chunk_damage(&old, chunk, &changed),- ChunkPairing::OnlyNew(chunk) => damage.add_unmatched_chunk_damage(&new, chunk, &changed),- }- }- }-- // A record that draws changed live content inside a group is damaged as the whole group.- if !live_content_changes.is_empty() {- for live_content_record in &new_frame.summary.live_content_records {- if damage.covers_viewport() {- break;- }- if !live_content_changes.includes(live_content_record.content)- || live_content_changes- .offsets_of_records_composited_as_media_layers- .contains(&live_content_record.record.record_offset)- {- continue;- }- damage.add_record_damage(- &new,- &RecordOnTape::at(- new_frame.command_bytes,- live_content_record.record.record_offset,- new_frame.command_runs[live_content_record.record.run_index as usize].context,- ),- );- }- }-- // NB: A backdrop filter reads more than the part of its region that is repainted, so forced damage goes through it too.- let forced_damage_rect = live_content_changes.forced_damage_rect;- if !forced_damage_rect.is_empty() {- damage.add_damage_rect(forced_damage_rect, DamagedLayers::All);- }- damage.add_backdrop_filter_damage(&new.geometry, new_frame.command_runs);-- let bounded_damage_rect = |is_unbounded: bool, damage_rect: Option<IntRect>| {- if is_unbounded {- return None;- }- Some(damage_rect.map_or(IntRect::default(), |damage_rect| {- intersect_like_gfx_int_rect(damage_rect.inflated_edges(1, 1, 1, 1), viewport_rect)- }))- };- DisplayListDamage {- rect: bounded_damage_rect(damage.changed_unbounded_command, damage.damage_rect),- layer_rects: damage- .damage_of_layers- .iter()- .map(|layer_damage| bounded_damage_rect(layer_damage.is_unbounded, layer_damage.rect))- .collect(),- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::display_list::builder::note_command;- use crate::display_list::chunks::{DisplayListChunk, chunk_id};- use crate::display_list::commands::{- BackdropFilterRegion, CanvasId, CompositorMainThreadWheelEventRegion, CompositorScrollbar, DeclareMaskContent,- DisplayListCommand, DisplayListDataSpan, DisplayListInlineClip, DrawCanvas, DrawCompositedContext,- DrawGlyphRun, DrawIsolatedGroup, DrawScaledDecodedImageFrame, DrawVideoFrame, FillRect, FontResourceId,- INLINE_CLIP_ENTRY_SIZE, InlineClipKind, OptionalColor, OptionalFloatRect, PaintScrollBar,- };- use crate::display_list::ffi_bytes::FfiBytes;- use crate::display_list::summary::summarize;- use crate::node_slot_id::NodeSlotId;- use crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT;- use crate::visual_context::{- BackdropFilterData, ClipData, ClipMode, ClipNodeData, ClipNodeIndex, ClipPathData, EffectNodeData,- EffectNodeIndex, EffectsData, MaskData, MaskLayerOrigin, ScrollData, SpatialData, TransformData,- TransformDataRole,- };- use libgfx_rust::filter::Filter;- use libgfx_rust::path::Path;- use libgfx_rust::{- Color, ColorFilterType, CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatPoint, MaskKind,- Orientation, ScalingMode, WindingRule, translation_matrix,- };-- const RED: Color = Color(0xffff0000);- const GREEN: Color = Color(0xff00ff00);- const BLUE: Color = Color(0xff0000ff);- const YELLOW: Color = Color(0xffffff00);- const CYAN: Color = Color(0xff00ffff);-- #[derive(Clone, Default)]- struct TestDisplayList {- bytes: Vec<u8>,- runs: Vec<DisplayListCommandRun>,- chunks: Vec<DisplayListChunk>,- }-- impl std::ops::Deref for TestDisplayList {- type Target = [u8];-- fn deref(&self) -> &Self::Target {- &self.bytes- }- }-- impl TestDisplayList {- fn first_run_of_open_chunk(&self) -> usize {- self.chunks.last().map_or(0, |chunk| chunk.run_end as usize)- }-- fn end_chunk(&mut self) {- let first_run = self.first_run_of_open_chunk();- if first_run == self.runs.len() {- return;- }- let chunk_start = self.chunks.last().map_or(0, |chunk| chunk.byte_end);- self.chunks.push(DisplayListChunk {- id: chunk_id(- &self.bytes[chunk_start as usize..],- &self.runs[first_run..],- chunk_start,- ),- byte_end: self.bytes.len() as u32,- run_end: self.runs.len() as u32,- });- }-- fn extend_from_slice(&mut self, source: &Self) {- let mut source = source.clone();- source.end_chunk();- self.end_chunk();- let (byte_base, run_base) = (self.bytes.len() as u32, self.runs.len() as u32);- self.bytes.extend_from_slice(&source.bytes);- self.runs.extend(source.runs.iter().map(|run| DisplayListCommandRun {- offset: run.offset + byte_base,- ..*run- }));- self.chunks.extend(source.chunks.iter().map(|chunk| DisplayListChunk {- byte_end: chunk.byte_end + byte_base,- run_end: chunk.run_end + run_base,- ..*chunk- }));- }-- fn prepared_against(&self, tree: &VisualContextTree) -> PreparedList<'_> {- let mut list = self.clone();- list.end_chunk();- PreparedList {- list: self,- chunks: TapeChunks::of_tape(&list.bytes, &list.runs, &list.chunks),- effect_clip_plan: EffectClipPlan::new(tree, &self.runs).unwrap(),- summary: summarize(&self.bytes, &self.runs),- }- }- }-- struct PreparedList<'a> {- list: &'a TestDisplayList,- chunks: TapeChunks,- effect_clip_plan: EffectClipPlan,- summary: DisplayListSummary,- }-- impl<'a> PreparedList<'a> {- fn frame(&'a self, tree: &'a VisualContextTree, scroll_offsets: &'a [FloatPoint]) -> DisplayListFrame<'a> {- DisplayListFrame {- command_bytes: &self.list.bytes,- command_runs: &self.list.runs,- chunks: &self.chunks,- effect_clip_plan: &self.effect_clip_plan,- summary: &self.summary,- visual_context_tree: tree,- scroll_offsets,- }- }- }-- // Appends one record the way the Rust builder writes it: header, payload, then zero padding up to- // the command alignment, but with the inline clip entries chosen by the test.- fn append_record<C: DisplayListCommand>(- display_list: &mut TestDisplayList,- command: &C,- inline_data: &[u8],- context: ContextRef,- inline_clips: &[DisplayListInlineClip],- ) {- let bytes = &mut display_list.bytes;- let unpadded_payload_size = std::mem::size_of::<C>() + inline_data.len();- let entries_size = inline_clips.len() * INLINE_CLIP_ENTRY_SIZE;- let padded_record_size = (HEADER_SIZE + unpadded_payload_size + entries_size).next_multiple_of(16);- let header = DisplayListCommandHeader {- command_type: C::COMMAND_TYPE,- inline_clip_count: inline_clips.len() as u8,- has_inline_transform: false,- payload_size: (padded_record_size - HEADER_SIZE) as u32,- };- let start = bytes.len();- bytes.resize(start + padded_record_size, 0);- header.write_ffi_bytes(&mut bytes[start..start + HEADER_SIZE]);- let payload_start = start + HEADER_SIZE;- command.write_ffi_bytes(&mut bytes[payload_start..payload_start + std::mem::size_of::<C>()]);- let inline_start = payload_start + std::mem::size_of::<C>();- bytes[inline_start..inline_start + inline_data.len()].copy_from_slice(inline_data);- let entries_start = start + padded_record_size - entries_size;- for (index, entry) in inline_clips.iter().enumerate() {- let entry_start = entries_start + index * INLINE_CLIP_ENTRY_SIZE;- entry.write_ffi_bytes(&mut bytes[entry_start..entry_start + INLINE_CLIP_ENTRY_SIZE]);- }- let bounding_rect =- bounding_rect_computed_from_payload(&header, &bytes[payload_start..start + padded_record_size]);- if display_list.runs.len() == display_list.first_run_of_open_chunk() {- display_list.runs.push(DisplayListCommandRun {- offset: start as u32,- context,- ..DisplayListCommandRun::default()- });- }- note_command(- &mut display_list.runs,- C::COMMAND_TYPE,- bounding_rect,- context,- start,- padded_record_size,- );- }-- fn command_bytes<C: DisplayListCommand>(command: &C, context: ContextRef) -> TestDisplayList {- let mut bytes = TestDisplayList::default();- append_record(&mut bytes, command, &[], context, &[]);- bytes.end_chunk();- bytes- }-- fn list_of(parts: &[&TestDisplayList]) -> TestDisplayList {- let mut list = TestDisplayList::default();- for part in parts {- list.extend_from_slice(part);- }- list- }-- fn fill_command_bytes(rect: IntRect, color: Color) -> TestDisplayList {- command_bytes(- &FillRect {- rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- ContextRef::default(),- )- }-- fn rect_inline_clip(rect: IntRect) -> DisplayListInlineClip {- DisplayListInlineClip {- clip_rect_or_path_device_bounds: rect.to_float(),- corner_radii: CornerRadii::default(),- path_data: DisplayListDataSpan::default(),- path_winding_rule: WindingRule::Nonzero,- kind: InlineClipKind::Rect,- mode: ClipMode::Intersect,- has_own_space: false,- space: SpatialNodeIndex::default(),- padding: 0,- }- }-- fn canvas_command_bytes(rect: IntRect) -> TestDisplayList {- let command = DrawCanvas {- dst_rect: rect,- canvas_id: CanvasId(1),- scaling_mode: ScalingMode::NearestNeighbor,- };- command_bytes(&command, ContextRef::default())- }-- fn transform(matrix: FloatMatrix4x4) -> TransformData {- TransformData {- matrix,- origin: FloatPoint::default(),- sorting_context_root_index: None,- flattens_inherited_transform: false,- role: TransformDataRole::CssTransform,- synthetic_plane: false,- establishes_sorting_context: false,- bounds: FloatRect::default(),- }- }-- fn identity_tree() -> VisualContextTree {- VisualContextTree::create(transform(FloatMatrix4x4::identity()))- }-- fn clip(rect: FloatRect) -> ClipNodeData {- ClipNodeData::Rect(ClipData {- rect,- corner_radii: CornerRadii::default(),- mode: ClipMode::Intersect,- })- }-- fn mask(rect: IntRect) -> EffectNodeData {- EffectNodeData::Mask(MaskData {- rect,- kind: MaskKind::Alpha,- origin: MaskLayerOrigin::CssMaskLayers,- masks_backdrop: false,- })- }-- fn effects(filter: Vec<u8>) -> EffectNodeData {- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 1.0,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: Some(std::sync::Arc::new(filter)),- backdrop_filter: None,- })- }-- // A context under a fresh root clip, or under a fresh root effect without an output clip.- fn clip_context(tree: &mut VisualContextTree, data: ClipNodeData) -> ContextRef {- let clip = tree.append_clip(data, ClipNodeIndex::NONE, VISUAL_VIEWPORT_NODE_INDEX);- ContextRef {- clip,- effect: EffectNodeIndex::NONE,- ..ContextRef::default()- }- }-- fn effect_context(tree: &mut VisualContextTree, data: EffectNodeData) -> ContextRef {- let effect = tree.append_effect(- data,- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- ClipNodeIndex::NONE,- );- ContextRef {- clip: ClipNodeIndex::NONE,- effect,- ..ContextRef::default()- }- }-- fn blur_filter(radius: f32) -> Vec<u8> {- Filter::blur(radius, radius, None).serialize()- }-- fn color_filter(amount: f32) -> Vec<u8> {- Filter::color(ColorFilterType::Brightness, amount, None).serialize()- }-- fn drop_shadow_filter(offset: f32, radius: f32) -> Vec<u8> {- Filter::drop_shadow(offset, offset, radius, RED, None).serialize()- }-- fn damage_for_filter_change(old_filter: Vec<u8>, new_filter: Vec<u8>) -> Option<IntRect> {- let mut old_tree = identity_tree();- let old_context = effect_context(&mut old_tree, effects(old_filter));- let mut new_tree = identity_tree();- let new_context = effect_context(&mut new_tree, effects(new_filter));- let rect = IntRect::new(10, 10, 20, 20);- let fill = FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let old_display_list = command_bytes(&fill, context_in(VISUAL_VIEWPORT_NODE_INDEX, old_context));- let new_display_list = command_bytes(&fill, context_in(VISUAL_VIEWPORT_NODE_INDEX, new_context));- damage(&old_display_list, &old_tree, &new_display_list, &new_tree)- }-- fn damage(- old_bytes: &TestDisplayList,- old_tree: &VisualContextTree,- new_bytes: &TestDisplayList,- new_tree: &VisualContextTree,- ) -> Option<IntRect> {- damage_with_scroll_offsets(- old_bytes,- old_tree,- &[],- new_bytes,- new_tree,- &[],- IntRect::new(0, 0, 100, 100),- )- }-- fn damage_with_scroll_offsets(- old_bytes: &TestDisplayList,- old_tree: &VisualContextTree,- old_scroll_offsets: &[FloatPoint],- new_bytes: &TestDisplayList,- new_tree: &VisualContextTree,- new_scroll_offsets: &[FloatPoint],- viewport_rect: IntRect,- ) -> Option<IntRect> {- let (old_list, new_list) = (- old_bytes.prepared_against(old_tree),- new_bytes.prepared_against(new_tree),- );- compute_display_list_damage(- old_list.frame(old_tree, old_scroll_offsets),- new_list.frame(new_tree, new_scroll_offsets),- viewport_rect,- LiveContentChanges::default(),- None,- )- .rect- }-- fn context_in(spatial: SpatialNodeIndex, context: ContextRef) -> ContextRef {- ContextRef { spatial, ..context }- }-- fn damage_for_live_content_changes(- bytes: &TestDisplayList,- tree: &VisualContextTree,- live_content_changes: LiveContentChanges<'_>,- ) -> Option<IntRect> {- let list = bytes.prepared_against(tree);- let frame = list.frame(tree, &[]);- compute_display_list_damage(frame, frame, IntRect::new(0, 0, 100, 100), live_content_changes, None).rect- }-- #[test]- fn a_record_composited_as_a_media_layer_is_not_damaged_by_its_live_content() {- let tree = identity_tree();- let mut list = canvas_command_bytes(IntRect::new(10, 10, 20, 20));- let media_layer_record_offset = 0;- list.extend_from_slice(&fill_command_bytes(IntRect::new(50, 50, 10, 10), RED));- list.extend_from_slice(&canvas_command_bytes(IntRect::new(60, 60, 10, 10)));- let changed_canvas = LiveContentChanges {- canvases: &[CanvasId(1)],- offsets_of_records_composited_as_media_layers: &[media_layer_record_offset],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&list, &tree, changed_canvas),- Some(IntRect::new(59, 59, 12, 12))- );- }-- #[test]- fn changed_live_content_damages_where_it_is_drawn() {- let tree = identity_tree();- let rect = IntRect::new(10, 10, 20, 20);- let canvas = canvas_command_bytes(rect);- let changed_canvas = LiveContentChanges {- canvases: &[CanvasId(1)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&canvas, &tree, changed_canvas),- Some(IntRect::new(9, 9, 22, 22))- );- let other_canvas = LiveContentChanges {- canvases: &[CanvasId(2)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&canvas, &tree, other_canvas),- Some(IntRect::default())- );-- let video = command_bytes(- &DrawVideoFrame {- dst_rect: rect,- video_sink_handle: VideoSinkHandle(1),- scaling_mode: ScalingMode::NearestNeighbor,- },- ContextRef::default(),- );- let changed_video = LiveContentChanges {- video_sinks: &[VideoSinkHandle(1)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&video, &tree, changed_video),- Some(IntRect::new(9, 9, 22, 22))- );- assert_eq!(- damage_for_live_content_changes(&video, &tree, changed_canvas),- Some(IntRect::default())- );-- let image = command_bytes(- &DrawScaledDecodedImageFrame {- dst_rect: FloatRect::new(10.0, 10.0, 20.0, 20.0),- src_rect: OptionalFloatRect::default(),- frame_id: ImageFrameResourceId(1),- scaling_mode: ScalingMode::NearestNeighbor,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- isolated_backdrop_color: OptionalColor::default(),- apply_force_dark: false,- },- ContextRef::default(),- );- let changed_image = LiveContentChanges {- image_frames: &[ImageFrameResourceId(1)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&image, &tree, changed_image),- Some(IntRect::new(9, 9, 22, 22))- );- assert_eq!(- damage_for_live_content_changes(&image, &tree, changed_video),- Some(IntRect::default())- );-- let nested_context = command_bytes(- &DrawCompositedContext {- dst_rect: FloatRect::new(10.0, 10.0, 20.0, 20.0),- child_context_id: CompositorContextId(7),- scaling_mode: ScalingMode::NearestNeighbor,- spatial_node_index: VISUAL_VIEWPORT_NODE_INDEX,- snap_origin_if_untransformed: true,- },- ContextRef::default(),- );- let changed_nested_context = LiveContentChanges {- composited_contexts: &[CompositorContextId(7)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&nested_context, &tree, changed_nested_context),- Some(IntRect::new(9, 9, 22, 22))- );- let other_nested_context = LiveContentChanges {- composited_contexts: &[CompositorContextId(8)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&nested_context, &tree, other_nested_context),- Some(IntRect::default())- );- }-- #[test]- fn changed_live_content_under_a_blur_damages_its_blurred_footprint() {- let mut tree = identity_tree();- let context = context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(&mut tree, effects(blur_filter(2.0))),- );- let rect = IntRect::new(10, 10, 20, 20);- let canvas = command_bytes(- &DrawCanvas {- dst_rect: rect,- canvas_id: CanvasId(1),- scaling_mode: ScalingMode::NearestNeighbor,- },- context,- );- let changed_canvas = LiveContentChanges {- canvases: &[CanvasId(1)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&canvas, &tree, changed_canvas),- Some(IntRect::new(3, 3, 34, 34))- );- }-- #[test]- fn changed_live_content_inside_a_group_damages_the_whole_group() {- let tree = identity_tree();- let group_rect = IntRect::new(5, 5, 40, 40);- let content = canvas_command_bytes(IntRect::new(10, 10, 20, 20));- let no_data = DisplayListDataSpan { offset: 0, size: 0 };- let mut group = TestDisplayList::default();- append_record(- &mut group,- &DrawIsolatedGroup {- clip_rect: group_rect.to_float(),- content: DisplayListDataSpan {- offset: std::mem::size_of::<DrawIsolatedGroup>() as u32,- size: content.len() as u32,- },- mask: no_data,- filter: no_data,- opacity: 1.0,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- mask_kind: MaskKind::Alpha,- },- &content,- ContextRef::default(),- &[],- );- let changed_canvas = LiveContentChanges {- canvases: &[CanvasId(1)],- ..LiveContentChanges::default()- };- assert_eq!(- damage_for_live_content_changes(&group, &tree, changed_canvas),- Some(IntRect::new(4, 4, 42, 42))- );- }-- #[test]- fn content_under_nested_fractional_scrolls_is_damaged_where_replay_draws_it() {- let mut tree = identity_tree();- let mut scroll_node = VISUAL_VIEWPORT_NODE_INDEX;- for _ in 0..3 {- scroll_node = tree.append_spatial(- SpatialData::Scroll(ScrollData {- state_slot: NO_SCROLL_STATE_SLOT,- owner_paintable: NodeSlotId::INVALID,- }),- scroll_node,- );- }- let mut scroll_offsets = vec![FloatPoint { x: 0.0, y: -0.9 }; 4];- scroll_offsets[0] = FloatPoint::default();- let rect = IntRect::new(10, 10, 20, 20);- let new_commands = command_bytes(- &FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- context_in(scroll_node, ContextRef::default()),- );- // Each of the three offsets rounds to a whole pixel, so the rect is drawn 3px above where it was recorded.- assert_eq!(- damage_with_scroll_offsets(- &TestDisplayList::default(),- &tree,- &scroll_offsets,- &new_commands,- &tree,- &scroll_offsets,- IntRect::new(0, 0, 100, 100),- ),- Some(IntRect::new(9, 6, 22, 22))- );- }-- #[test]- fn identical_display_lists_have_no_damage() {- let tree = identity_tree();- let display_list = fill_command_bytes(IntRect::new(10, 10, 20, 20), RED);- assert_eq!(- damage(&display_list, &tree, &display_list, &tree),- Some(IntRect::default())- );- }-- #[test]- fn removing_a_clip_escape_damages_unchanged_runs_whose_layer_placement_changes() {- let mut tree = identity_tree();- let local_clip = tree.append_clip(- clip(FloatRect::new(0.0, 0.0, 30.0, 30.0)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let effect = tree.append_effect(- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 0.5,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: None,- backdrop_filter: None,- }),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- local_clip,- );- let rect = IntRect::new(10, 10, 10, 10);- let fill = FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let remaining = command_bytes(- &fill,- ContextRef {- clip: local_clip,- effect,- ..ContextRef::default()- },- );- let escaped_rect = IntRect::new(70, 70, 10, 10);- let escaped = command_bytes(- &FillRect {- rect: escaped_rect,- ..fill- },- ContextRef {- clip: ClipNodeIndex::NONE,- effect,- ..ContextRef::default()- },- );- let mut before = remaining.clone();- before.extend_from_slice(&escaped);- let changed = damage(&before, &tree, &remaining, &tree).unwrap();- // Repaint both the removed drawing and the retained drawing whose layer moved- // inside the clip. Comparing only the unchanged AVC tree would miss the latter.- assert!(changed.x <= rect.x && changed.y <= rect.y);- assert!(changed.x + changed.width >= escaped_rect.x + escaped_rect.width);- assert!(changed.y + changed.height >= escaped_rect.y + escaped_rect.height);- }-- #[test]- fn changed_scroll_offset_damages_scrollbar() {- let tree = identity_tree();-- let scrollbar = PaintScrollBar {- scroll_node_index: SpatialNodeIndex(1),- gutter_rect: IntRect::default(),- thumb_rect: IntRect::new(10, 12, 20, 8),- track_rect: IntRect::new(10, 10, 80, 12),- expanded_gutter_rect: IntRect::default(),- scroll_size: 0.75,- thumb_color: RED,- thumb_outline_color: Color::TRANSPARENT,- track_color: Color::TRANSPARENT,- vertical: false,- };-- let display_list = command_bytes(&scrollbar, ContextRef::default());-- assert_eq!(- damage_with_scroll_offsets(- &display_list,- &tree,- &[FloatPoint::default(), FloatPoint::default()],- &display_list,- &tree,- &[FloatPoint::default(), FloatPoint { x: -40.0, y: 0.0 }],- IntRect::new(0, 0, 100, 100),- ),- Some(IntRect::new(9, 9, 82, 14))- );- }-- #[test]- fn changed_scroll_offset_damages_a_draw_with_an_inline_clip_in_another_space() {- let mut tree = identity_tree();- let scroll = tree.append_spatial(- SpatialData::Scroll(ScrollData {- state_slot: 1,- owner_paintable: NodeSlotId::INVALID,- }),- VISUAL_VIEWPORT_NODE_INDEX,- );- let rect = IntRect::new(10, 10, 20, 20);- let draw_with_clip = |clip: DisplayListInlineClip| {- let mut display_list = TestDisplayList::default();- append_record(- &mut display_list,- &FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- &[],- ContextRef::default(),- &[clip],- );- display_list- };- let damage_after_scroll = |display_list: &TestDisplayList| {- damage_with_scroll_offsets(- display_list,- &tree,- &[FloatPoint::default(), FloatPoint::default()],- display_list,- &tree,- &[FloatPoint::default(), FloatPoint { x: 0.0, y: -40.0 }],- IntRect::new(0, 0, 100, 100),- )- };-- let clip_in_space = |space: SpatialNodeIndex| DisplayListInlineClip {- has_own_space: true,- space,- ..rect_inline_clip(rect)- };-- assert!(damage_after_scroll(&draw_with_clip(rect_inline_clip(rect))).is_none_or(|damage| damage.is_empty()));- // A clip whose space does not move with the scroll leaves the draw as it was.- assert!(- damage_after_scroll(&draw_with_clip(clip_in_space(VISUAL_VIEWPORT_NODE_INDEX)))- .is_none_or(|damage| damage.is_empty())- );- // The scroll moves the clip off the draw, so only where it was changes.- assert_eq!(- damage_after_scroll(&draw_with_clip(clip_in_space(scroll))),- Some(IntRect::new(9, 9, 22, 22))- );- // A partial move changes only the part of the draw that the clip uncovers or covers.- let damage_after_small_scroll = |display_list: &TestDisplayList| {- damage_with_scroll_offsets(- display_list,- &tree,- &[FloatPoint::default(), FloatPoint::default()],- display_list,- &tree,- &[FloatPoint::default(), FloatPoint { x: 0.0, y: -5.0 }],- IntRect::new(0, 0, 100, 100),- )- };- let small_scroll_damage = damage_after_small_scroll(&draw_with_clip(DisplayListInlineClip {- has_own_space: true,- space: scroll,- ..rect_inline_clip(IntRect::new(10, 10, 20, 5))- }));- assert!(small_scroll_damage.is_some_and(|damage| damage.height < 22 && !damage.is_empty()));- }-- #[test]- fn a_new_tree_that_moves_the_space_of_an_inline_clip_damages_its_draw() {- let mut old_tree = identity_tree();- let old_space = old_tree.append_spatial(- SpatialData::Transform(transform(FloatMatrix4x4::identity())),- VISUAL_VIEWPORT_NODE_INDEX,- );- // The new tree gives the index of the clip's space to a node that sits elsewhere.- let mut new_tree = identity_tree();- let new_space = new_tree.append_spatial(- SpatialData::Transform(transform(translation_matrix(0.0, 40.0, 0.0))),- VISUAL_VIEWPORT_NODE_INDEX,- );- assert_eq!(old_space, new_space);- let rect = IntRect::new(10, 10, 20, 20);- let mut display_list = TestDisplayList::default();- append_record(- &mut display_list,- &FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- &[],- ContextRef::default(),- &[DisplayListInlineClip {- has_own_space: true,- space: old_space,- ..rect_inline_clip(rect)- }],- );- let offsets = [FloatPoint::default()];- let viewport = IntRect::new(0, 0, 100, 100);- assert!(- damage_with_scroll_offsets(- &display_list,- &old_tree,- &offsets,- &display_list,- &old_tree,- &offsets,- viewport- )- .is_none_or(|damage| damage.is_empty())- );- assert_eq!(- damage_with_scroll_offsets(- &display_list,- &old_tree,- &offsets,- &display_list,- &new_tree,- &offsets,- viewport- ),- Some(IntRect::new(9, 9, 22, 22))- );- }-- #[test]- fn animated_content_follows_inline_clips_in_spaces_of_their_own() {- let mut tree = identity_tree();- let scroll = tree.append_spatial(- SpatialData::Scroll(ScrollData {- state_slot: 1,- owner_paintable: NodeSlotId::INVALID,- }),- VISUAL_VIEWPORT_NODE_INDEX,- );- let rotating = tree.append_spatial(- SpatialData::Transform(transform(FloatMatrix4x4::identity())),- VISUAL_VIEWPORT_NODE_INDEX,- );- let effect = tree.append_effect(- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 0.5,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: None,- backdrop_filter: None,- }),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- ClipNodeIndex::NONE,- );- let viewport = IntRect::new(0, 0, 800, 600);- let draw_clipped_to = |clip_space: SpatialNodeIndex, clip_rect: IntRect, context: ContextRef| {- let mut display_list = TestDisplayList::default();- append_record(- &mut display_list,- &FillRect {- rect: viewport,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- &[],- context,- &[DisplayListInlineClip {- has_own_space: true,- space: clip_space,- ..rect_inline_clip(clip_rect)- }],- );- display_list- };- let may_affect_viewport = |display_list: &TestDisplayList, rotation_nodes: &[SpatialNodeIndex]| {- animated_content_may_affect_viewport(- display_list,- &display_list.runs,- &tree,- &[FloatPoint::default(), FloatPoint::default()],- rotation_nodes,- &[effect],- viewport,- )- };- let faded = ContextRef {- effect,- ..ContextRef::default()- };-- // An animated opacity only affects the viewport where the clip lets the draw show.- let box_on_screen = IntRect::new(0, 10, 10, 10);- let box_off_screen = IntRect::new(0, 2000, 10, 10);- assert!(may_affect_viewport(&draw_clipped_to(scroll, box_on_screen, faded), &[]));- assert!(!may_affect_viewport(- &draw_clipped_to(scroll, box_off_screen, faded),- &[]- ));-- // A clip in a rotating space moves the draw it clips, though the draw's own space stands still.- assert!(may_affect_viewport(- &draw_clipped_to(rotating, box_on_screen, ContextRef::default()),- &[rotating]- ));- }-- #[test]- fn damage_contains_old_and_new_command_bounds() {- let tree = identity_tree();- let old_display_list = fill_command_bytes(IntRect::new(10, 10, 20, 20), RED);- let new_display_list = fill_command_bytes(IntRect::new(40, 40, 20, 20), BLUE);- assert_eq!(- damage(&old_display_list, &tree, &new_display_list, &tree),- Some(IntRect::new(9, 9, 52, 52))- );- }-- #[test]- fn changed_compositor_metadata_has_no_raster_damage() {- let tree = identity_tree();- let old_display_list = command_bytes(- &CompositorMainThreadWheelEventRegion {- rect: FloatRect::new(0.0, 0.0, 10.0, 10.0),- },- ContextRef::default(),- );- let new_display_list = command_bytes(- &CompositorMainThreadWheelEventRegion {- rect: FloatRect::new(20.0, 20.0, 10.0, 10.0),- },- ContextRef::default(),- );- assert_eq!(- damage(&old_display_list, &tree, &new_display_list, &tree),- Some(IntRect::default())- );- }-- fn compositor_scrollbar(is_painted_by_compositor: bool) -> CompositorScrollbar {- CompositorScrollbar {- scroll_node_index: SpatialNodeIndex(1),- gutter_rect: IntRect::default(),- thumb_rect: IntRect::new(98, 0, 2, 20),- track_rect: IntRect::new(96, 0, 4, 100),- expanded_gutter_rect: IntRect::new(92, 0, 8, 100),- expanded_thumb_rect: IntRect::new(94, 0, 6, 20),- scroll_size: 0.8,- expanded_scroll_size: 0.8,- min_scroll_offset: 0.0,- max_scroll_offset: 100.0,- thumb_color: RED,- thumb_outline_color: Color::TRANSPARENT,- track_color: Color::TRANSPARENT,- vertical: true,- is_painted_by_compositor,- }- }-- fn compositor_scrollbar_bytes(is_painted_by_compositor: bool) -> TestDisplayList {- command_bytes(&compositor_scrollbar(is_painted_by_compositor), ContextRef::default())- }-- #[test]- fn moved_scrollbar_metadata_requires_full_repaint_only_when_the_compositor_paints_it() {- let old_tree = identity_tree();- let new_tree = VisualContextTree::create(transform(translation_matrix(10.0, 0.0, 0.0)));-- let painted_by_display_list = compositor_scrollbar_bytes(false);- assert_eq!(- damage(&painted_by_display_list, &old_tree, &painted_by_display_list, &new_tree),- Some(IntRect::default())- );-- let painted_by_compositor = compositor_scrollbar_bytes(true);- assert_eq!(- damage(&painted_by_compositor, &old_tree, &painted_by_compositor, &new_tree),- None- );- }-- #[test]- fn changed_visual_context_damages_affected_commands() {- let old_tree = identity_tree();- let new_tree = VisualContextTree::create(transform(translation_matrix(10.0, 0.0, 0.0)));- let display_list = fill_command_bytes(IntRect::new(10, 10, 20, 20), RED);- assert_eq!(- damage(&display_list, &old_tree, &display_list, &new_tree),- Some(IntRect::new(9, 9, 32, 22))- );- }-- #[test]- fn changed_extent_affecting_filter_damages_its_old_and_new_output() {- assert_eq!(- damage_for_filter_change(blur_filter(1.0), blur_filter(10.0)),- Some(IntRect::new(0, 0, 61, 61))- );- assert_eq!(- damage_for_filter_change(drop_shadow_filter(1.0, 1.0), drop_shadow_filter(10.0, 10.0)),- Some(IntRect::new(0, 0, 71, 71))- );- let flood = Filter::Flood {- color: RED,- opacity: 1.0,- }- .serialize();- assert_eq!(damage_for_filter_change(blur_filter(1.0), flood), None);- }-- #[test]- fn changed_filter_clipped_outside_viewport_has_no_damage() {- let make_scene = |radius, clip_y, clip_mode, clip_outside_filter| {- let mut tree = identity_tree();- let clip = tree.append_clip(- ClipNodeData::Rect(ClipData {- rect: FloatRect::new(0.0, clip_y, 100.0, 100.0),- corner_radii: CornerRadii::default(),- mode: clip_mode,- }),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let effect = tree.append_effect(- effects(blur_filter(radius)),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- if clip_outside_filter { clip } else { ClipNodeIndex::NONE },- );- let context = ContextRef {- clip,- effect,- ..ContextRef::default()- };- let rect = IntRect::new(0, 200, 20, 20);- let fill = FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- (command_bytes(&fill, context), tree)- };- let (old_bytes, old_tree) = make_scene(1.0, 200.0, ClipMode::Intersect, true);- let (new_bytes, new_tree) = make_scene(200.0, 200.0, ClipMode::Intersect, true);- assert_eq!(- damage(&old_bytes, &old_tree, &new_bytes, &new_tree),- Some(IntRect::default())- );-- let whole_viewport = Some(IntRect::new(0, 0, 100, 100));-- // The filter can expand an inner clip's output back into view.- let (old_bytes, old_tree) = make_scene(1.0, 200.0, ClipMode::Intersect, false);- let (new_bytes, new_tree) = make_scene(200.0, 200.0, ClipMode::Intersect, false);- assert_eq!(damage(&old_bytes, &old_tree, &new_bytes, &new_tree), whole_viewport);-- // Difference clips exclude their rect rather than bounding the effect's output.- let (old_bytes, old_tree) = make_scene(1.0, 200.0, ClipMode::Difference, true);- let (new_bytes, new_tree) = make_scene(200.0, 200.0, ClipMode::Difference, true);- assert_eq!(damage(&old_bytes, &old_tree, &new_bytes, &new_tree), whole_viewport);-- // Output inside the viewport on either side is damaged.- let (old_bytes, old_tree) = make_scene(100.0, 0.0, ClipMode::Intersect, true);- let (new_bytes, new_tree) = make_scene(200.0, 200.0, ClipMode::Intersect, true);- assert_eq!(damage(&old_bytes, &old_tree, &new_bytes, &new_tree), whole_viewport);- assert_eq!(damage(&new_bytes, &new_tree, &old_bytes, &old_tree), whole_viewport);-- // An outer filter can expand the clipped inner filter back into the viewport.- let (old_bytes, mut old_tree) = make_scene(1.0, 200.0, ClipMode::Intersect, true);- let (new_bytes, mut new_tree) = make_scene(200.0, 200.0, ClipMode::Intersect, true);- for tree in [&mut old_tree, &mut new_tree] {- let parent = tree.append_effect(- effects(blur_filter(300.0)),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- ClipNodeIndex::NONE,- );- tree.effect_nodes[0].parent = parent;- }- assert_eq!(damage(&old_bytes, &old_tree, &new_bytes, &new_tree), whole_viewport);-- // A descendant escaping the clip widens the effect's output clip in the replay plan.- let (mut old_bytes, old_tree) = make_scene(1.0, 200.0, ClipMode::Intersect, true);- let (mut new_bytes, new_tree) = make_scene(200.0, 200.0, ClipMode::Intersect, true);- let rect = IntRect::new(0, 0, 20, 20);- let escaped = command_bytes(- &FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- ContextRef {- effect: EffectNodeIndex(0),- ..ContextRef::default()- },- );- old_bytes.extend_from_slice(&escaped);- new_bytes.extend_from_slice(&escaped);- assert_eq!(damage(&old_bytes, &old_tree, &new_bytes, &new_tree), whole_viewport);- }-- fn damage_for_fill_color_change_under(- context_of: impl Fn(&mut VisualContextTree) -> ContextRef,- ) -> Option<IntRect> {- let mut tree = identity_tree();- let context = context_of(&mut tree);- let rect = IntRect::new(10, 10, 20, 20);- let fill = |color| FillRect {- rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let old_bytes = command_bytes(&fill(RED), context);- let new_bytes = command_bytes(&fill(BLUE), context);- damage(&old_bytes, &tree, &new_bytes, &tree)- }-- #[test]- fn a_changed_command_damages_where_the_filters_above_it_spread_it() {- let under_filter = |filter: Vec<u8>| {- move |tree: &mut VisualContextTree| {- context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(tree, effects(filter.clone())),- )- }- };- assert_eq!(- damage_for_fill_color_change_under(under_filter(blur_filter(2.0))),- Some(IntRect::new(3, 3, 34, 34))- );- assert_eq!(- damage_for_fill_color_change_under(under_filter(drop_shadow_filter(30.0, 0.0))),- Some(IntRect::new(9, 9, 52, 52))- );- assert_eq!(- damage_for_fill_color_change_under(under_filter(color_filter(0.5))),- Some(IntRect::new(9, 9, 22, 22))- );- let flood = Filter::Flood {- color: RED,- opacity: 1.0,- }- .serialize();- assert_eq!(damage_for_fill_color_change_under(under_filter(flood.clone())), None);-- // Spread content cannot show past the clips outside its filters.- let under_clipped_filter = |filter: Vec<u8>, clip_rect: FloatRect| {- move |tree: &mut VisualContextTree| {- let clip = tree.append_clip(- ClipNodeData::rect_clip(clip_rect),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let effect = tree.append_effect(- effects(filter.clone()),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- clip,- );- ContextRef {- clip,- effect,- ..ContextRef::default()- }- }- };- assert_eq!(- damage_for_fill_color_change_under(under_clipped_filter(- blur_filter(200.0),- FloatRect::new(0.0, 0.0, 50.0, 50.0)- )),- Some(IntRect::new(0, 0, 52, 52))- );- assert_eq!(- damage_for_fill_color_change_under(under_clipped_filter(- flood.clone(),- FloatRect::new(20.0, 20.0, 30.0, 30.0)- )),- Some(IntRect::new(18, 18, 34, 34))- );- assert_eq!(- damage_for_fill_color_change_under(under_clipped_filter(flood, FloatRect::new(0.0, 200.0, 100.0, 100.0))),- Some(IntRect::default())- );- }-- // A filter that keeps only where its source overlaps a shifted copy of itself shows a change to- // one part of the source wherever the copy of an unchanged part overlaps it.- #[test]- fn a_change_masked_by_a_shifted_copy_of_the_source_damages_both_copies() {- let mut tree = identity_tree();- let masked_by_shifted_copy = Filter::Blend {- background: Some(Box::new(Filter::Offset {- dx: 40.0,- dy: 0.0,- input: None,- })),- foreground: None,- mode: CompositingAndBlendingOperator::SourceIn,- }- .serialize();- let context = context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(&mut tree, effects(masked_by_shifted_copy)),- );- let scene = |right_color| {- let fill = |x, color| {- let rect = IntRect::new(x, 10, 20, 20);- command_bytes(- &FillRect {- rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- context,- )- };- let mut bytes = fill(10, RED);- bytes.extend_from_slice(&fill(50, right_color));- bytes- };- assert_eq!(- damage(&scene(RED), &tree, &scene(BLUE), &tree),- Some(IntRect::new(49, 9, 51, 22))- );- }-- #[test]- fn damage_beneath_a_backdrop_filter_spreads_into_its_region() {- let region = IntRect::new(25, 0, 50, 50);- let mut tree = identity_tree();- let backdrop_context = context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(&mut tree, backdrop_effects(blur_filter(4.0), region)),- );- let scene = |fill_rect, color| {- let mut bytes = command_bytes(- &FillRect {- rect: fill_rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- ContextRef::default(),- );- bytes.extend_from_slice(&command_bytes(&BackdropFilterRegion { rect: region }, backdrop_context));- bytes- };- let within_reach = IntRect::new(0, 10, 30, 20);- assert_eq!(- damage(&scene(within_reach, RED), &tree, &scene(within_reach, BLUE), &tree),- Some(IntRect::new(0, 0, 76, 51))- );- let out_of_reach = IntRect::new(0, 10, 10, 20);- assert_eq!(- damage(&scene(out_of_reach, RED), &tree, &scene(out_of_reach, BLUE), &tree),- Some(IntRect::new(0, 9, 11, 22))- );- }-- #[test]- fn forced_damage_at_a_backdrop_filter_repaints_its_whole_region() {- let region = IntRect::new(25, 0, 50, 50);- let mut tree = identity_tree();- let backdrop_context = context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(&mut tree, backdrop_effects(blur_filter(4.0), region)),- );- let bytes = command_bytes(&BackdropFilterRegion { rect: region }, backdrop_context);- let forced_damage = |forced_damage_rect| {- damage_for_live_content_changes(- &bytes,- &tree,- LiveContentChanges {- forced_damage_rect,- ..LiveContentChanges::default()- },- )- };- assert_eq!(forced_damage(IntRect::default()), Some(IntRect::default()));- assert_eq!(- forced_damage(IntRect::new(40, 10, 3, 20)),- Some(IntRect::new(24, 0, 52, 51))- );- assert_eq!(- forced_damage(IntRect::new(0, 10, 3, 20)),- Some(IntRect::new(0, 9, 4, 22))- );- }-- #[test]- fn a_damaged_backdrop_region_is_spread_by_the_filters_of_its_effect() {- let region = IntRect::new(25, 0, 50, 50);- let mut tree = identity_tree();- let shadowed_backdrop_context = context_in(- VISUAL_VIEWPORT_NODE_INDEX,- effect_context(- &mut tree,- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 1.0,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: Some(std::sync::Arc::new(drop_shadow_filter(20.0, 0.0))),- backdrop_filter: Some(BackdropFilterData {- filter: std::sync::Arc::new(blur_filter(4.0)),- region,- corner_radii: CornerRadii::default(),- }),- }),- ),- );- let fill_rect = IntRect::new(0, 10, 30, 20);- let scene = |color| {- let mut bytes = command_bytes(- &FillRect {- rect: fill_rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- ContextRef::default(),- );- bytes.extend_from_slice(&command_bytes(- &BackdropFilterRegion { rect: region },- shadowed_backdrop_context,- ));- bytes- };- // The region and its shadow, 20 pixels down and right.- assert_eq!(- damage(&scene(RED), &tree, &scene(BLUE), &tree),- Some(IntRect::new(0, 0, 96, 71))- );- }-- #[test]- fn changed_color_filter_has_bounded_damage() {- assert_eq!(- damage_for_filter_change(color_filter(0.5), color_filter(1.0)),- Some(IntRect::new(9, 9, 22, 22))- );- }-- fn backdrop_effects(filter: Vec<u8>, region: IntRect) -> EffectNodeData {- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 1.0,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: None,- backdrop_filter: Some(BackdropFilterData {- filter: std::sync::Arc::new(filter),- region,- corner_radii: CornerRadii::default(),- }),- })- }-- // A backdrop filter's output is limited to its region, which the region command records, so a- // changed backdrop filter damages that region even when it widens the filter's extent.- #[test]- fn changed_backdrop_filter_damages_its_region() {- let region = IntRect::new(10, 10, 20, 20);- let mut old_tree = identity_tree();- let old_context = effect_context(&mut old_tree, backdrop_effects(blur_filter(1.0), region));- let mut new_tree = identity_tree();- let new_context = effect_context(&mut new_tree, backdrop_effects(blur_filter(10.0), region));- let mut unchanged_tree = identity_tree();- let unchanged_context = effect_context(&mut unchanged_tree, backdrop_effects(blur_filter(1.0), region));- let marker = BackdropFilterRegion { rect: region };- let old_display_list = command_bytes(&marker, context_in(VISUAL_VIEWPORT_NODE_INDEX, old_context));- let new_display_list = command_bytes(&marker, context_in(VISUAL_VIEWPORT_NODE_INDEX, new_context));- let unchanged_display_list = command_bytes(&marker, context_in(VISUAL_VIEWPORT_NODE_INDEX, unchanged_context));- assert_eq!(- damage(&old_display_list, &old_tree, &new_display_list, &new_tree),- Some(IntRect::new(9, 9, 22, 22))- );- assert_eq!(- damage(&old_display_list, &old_tree, &unchanged_display_list, &unchanged_tree),- Some(IntRect::default())- );- }-- #[test]- fn commands_under_an_empty_effective_clip_do_not_damage() {- let mut old_tree = identity_tree();- let old_context = clip_context(&mut old_tree, clip(FloatRect::default()));- let mut new_tree = identity_tree();- let new_context = clip_context(&mut new_tree, clip(FloatRect::default()));- let old_display_list = command_bytes(- &FillRect {- rect: IntRect::new(10, 10, 20, 20),- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- context_in(VISUAL_VIEWPORT_NODE_INDEX, old_context),- );- let new_display_list = command_bytes(- &FillRect {- rect: IntRect::new(30, 30, 20, 20),- color: BLUE,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- },- context_in(VISUAL_VIEWPORT_NODE_INDEX, new_context),- );- assert_eq!(- damage(&old_display_list, &old_tree, &new_display_list, &new_tree),- Some(IntRect::default())- );- }-- #[test]- fn a_clip_growing_from_empty_damages_the_commands_it_reveals() {- let mut old_tree = identity_tree();- let old_context = clip_context(&mut old_tree, clip(FloatRect::default()));- let mut new_tree = identity_tree();- let new_context = clip_context(&mut new_tree, clip(FloatRect::new(0.0, 0.0, 100.0, 100.0)));- let fill = FillRect {- rect: IntRect::new(10, 10, 20, 20),- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let old_display_list = command_bytes(&fill, context_in(VISUAL_VIEWPORT_NODE_INDEX, old_context));- let new_display_list = command_bytes(&fill, context_in(VISUAL_VIEWPORT_NODE_INDEX, new_context));- assert_eq!(- damage(&old_display_list, &old_tree, &new_display_list, &new_tree),- Some(IntRect::new(9, 9, 22, 22))- );- }-- #[test]- fn unrelated_inserted_visual_context_does_not_damage_commands() {- let mut old_tree = identity_tree();- let old_command_spatial = old_tree.append_spatial(- SpatialData::Transform(transform(FloatMatrix4x4::identity())),- VISUAL_VIEWPORT_NODE_INDEX,- );- let mut new_tree = identity_tree();- effect_context(- &mut new_tree,- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 0.5,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: None,- backdrop_filter: None,- }),- );- let new_command_spatial = new_tree.append_spatial(- SpatialData::Transform(transform(FloatMatrix4x4::identity())),- VISUAL_VIEWPORT_NODE_INDEX,- );- let fill = FillRect {- rect: IntRect::new(10, 10, 20, 20),- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let old_display_list = command_bytes(&fill, context_in(old_command_spatial, ContextRef::default()));- let new_display_list = command_bytes(&fill, context_in(new_command_spatial, ContextRef::default()));- assert_eq!(- damage(&old_display_list, &old_tree, &new_display_list, &new_tree),- Some(IntRect::default())- );- }-- #[test]- fn canvas_without_new_content_is_not_damaged() {- let tree = identity_tree();- let canvas = canvas_command_bytes(IntRect::new(10, 10, 20, 20));- let old_fill = fill_command_bytes(IntRect::new(50, 50, 10, 10), RED);- let new_fill = fill_command_bytes(IntRect::new(50, 50, 10, 10), BLUE);- let mut old_display_list = canvas.clone();- old_display_list.extend_from_slice(&old_fill);- let mut new_display_list = canvas;- new_display_list.extend_from_slice(&new_fill);- assert_eq!(- damage(&old_display_list, &tree, &new_display_list, &tree),- Some(IntRect::new(49, 49, 12, 12))- );- }-- #[test]- fn inserted_and_removed_chunks_do_not_damage_shifted_chunks() {- let tree = identity_tree();- let first = fill_command_bytes(IntRect::new(10, 10, 10, 10), RED);- let second = fill_command_bytes(IntRect::new(30, 10, 10, 10), GREEN);- let third = fill_command_bytes(IntRect::new(50, 10, 10, 10), BLUE);- let removed = fill_command_bytes(IntRect::new(70, 10, 10, 10), YELLOW);- let inserted = fill_command_bytes(IntRect::new(20, 40, 10, 10), CYAN);- let mut old_display_list = first.clone();- old_display_list.extend_from_slice(&second);- old_display_list.extend_from_slice(&third);- old_display_list.extend_from_slice(&removed);- let mut new_display_list = first;- new_display_list.extend_from_slice(&inserted);- new_display_list.extend_from_slice(&second);- new_display_list.extend_from_slice(&third);- assert_eq!(- damage(&old_display_list, &tree, &new_display_list, &tree),- Some(IntRect::new(19, 9, 62, 42))- );- }-- #[test]- fn clip_paths_are_compared_by_content_across_allocations() {- let rect = IntRect::new(10, 10, 20, 20);- let scene = |apex_x: f32| {- let mut path = Path::new();- path.move_to(FloatPoint { x: 10.0, y: 30.0 });- path.line_to(FloatPoint { x: apex_x, y: 10.0 });- path.line_to(FloatPoint { x: 30.0, y: 30.0 });- path.close();- let mut tree = identity_tree();- let context = clip_context(- &mut tree,- ClipNodeData::Path(ClipPathData {- path: std::sync::Arc::new(path),- bounding_rect: rect,- fill_rule: WindingRule::Nonzero,- }),- );- let fill = FillRect {- rect,- color: RED,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- (- command_bytes(&fill, context_in(VISUAL_VIEWPORT_NODE_INDEX, context)),- tree,- )- };- let (old_display_list, old_tree) = scene(20.0);- let (same_display_list, same_tree) = scene(20.0);- assert_eq!(- damage(&old_display_list, &old_tree, &same_display_list, &same_tree),- Some(IntRect::default())- );- let (changed_display_list, changed_tree) = scene(25.0);- assert_eq!(- damage(&old_display_list, &old_tree, &changed_display_list, &changed_tree),- Some(IntRect::new(9, 9, 22, 22))- );- }-- #[test]- fn damage_covering_the_viewport_ends_the_diff() {- let viewport = IntRect::new(0, 0, 100, 100);- // The cover's run comes first, and moving it damages the whole viewport.- let scene = |cover_offset, filter| {- let mut tree = identity_tree();- let cover_spatial = tree.append_spatial(- SpatialData::Transform(transform(translation_matrix(cover_offset, 0.0, 0.0))),- VISUAL_VIEWPORT_NODE_INDEX,- );- let filtered_context = context_in(VISUAL_VIEWPORT_NODE_INDEX, effect_context(&mut tree, effects(filter)));- let fill = |rect| FillRect {- rect,- color: BLUE,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };- let filtered_rect = IntRect::new(10, 10, 20, 20);- let mut bytes = command_bytes(&fill(viewport), context_in(cover_spatial, ContextRef::default()));- bytes.extend_from_slice(&command_bytes(&fill(filtered_rect), filtered_context));- (bytes, tree)- };- let flood = || {- Filter::Flood {- color: RED,- opacity: 1.0,- }- .serialize()- };- let (old_bytes, old_tree) = scene(0.0, blur_filter(1.0));- let (flood_bytes, flood_tree) = scene(0.0, flood());- let (flood_and_moved_cover_bytes, flood_and_moved_cover_tree) = scene(1.0, flood());- // A flood alone requires a full repaint; a covering change reported first means the same- // thing.- assert_eq!(damage(&old_bytes, &old_tree, &flood_bytes, &flood_tree), None);- assert_eq!(- damage(- &old_bytes,- &old_tree,- &flood_and_moved_cover_bytes,- &flood_and_moved_cover_tree- ),- Some(viewport)- );- }-- fn fill(rect: IntRect, color: Color) -> FillRect {- FillRect {- rect,- color,- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- }- }-- fn fill_in(rect: IntRect, color: Color, context: ContextRef) -> TestDisplayList {- command_bytes(&fill(rect, color), context)- }-- fn scroll_data() -> SpatialData {- SpatialData::Scroll(ScrollData {- state_slot: NO_SCROLL_STATE_SLOT,- owner_paintable: NodeSlotId::INVALID,- })- }-- fn identity_transform() -> SpatialData {- SpatialData::Transform(transform(FloatMatrix4x4::identity()))- }-- #[test]- fn a_replaced_chunk_between_unchanged_ones_damages_only_what_both_versions_draw() {- let tree = identity_tree();- let unchanged = |x| fill_command_bytes(IntRect::new(x, 60, 10, 10), GREEN);- let scene = |color| {- list_of(&[- &unchanged(0),- &unchanged(20),- &fill_command_bytes(IntRect::new(10, 10, 10, 10), color),- &unchanged(40),- &unchanged(60),- ])- };- assert_eq!(- damage(&scene(RED), &tree, &scene(BLUE), &tree),- Some(IntRect::new(9, 9, 12, 12))- );- }-- #[test]- fn unchanged_chunks_between_two_changed_ones_are_not_damaged() {- let tree = identity_tree();- let unchanged: Vec<TestDisplayList> = (0..8)- .map(|index| fill_command_bytes(IntRect::new(10 * index, 60, 10, 10), GREEN))- .collect();- let scene = |color| {- let mut list = fill_command_bytes(IntRect::new(0, 0, 10, 10), color);- for chunk in &unchanged {- list.extend_from_slice(chunk);- }- list.extend_from_slice(&fill_command_bytes(IntRect::new(10, 0, 10, 10), color));- list- };- assert_eq!(- damage(&scene(RED), &tree, &scene(BLUE), &tree),- Some(IntRect::new(0, 0, 21, 11))- );- }-- #[test]- fn a_chunk_moved_past_others_is_damaged_where_it_is_drawn_and_the_others_are_not() {- let tree = identity_tree();- let moved = fill_command_bytes(IntRect::new(10, 10, 10, 10), RED);- let first = fill_command_bytes(IntRect::new(50, 50, 10, 10), GREEN);- let second = fill_command_bytes(IntRect::new(70, 50, 10, 10), BLUE);- let moved_damage = Some(IntRect::new(9, 9, 12, 12));- assert_eq!(- damage(- &list_of(&[&moved, &first, &second]),- &tree,- &list_of(&[&first, &second, &moved]),- &tree- ),- moved_damage- );- assert_eq!(- damage(- &list_of(&[&first, &second, &moved]),- &tree,- &list_of(&[&moved, &first, &second]),- &tree- ),- moved_damage- );- assert_eq!(- damage(&list_of(&[&moved, &first]), &tree, &list_of(&[&first, &moved]), &tree),- moved_damage- );- }-- #[test]- fn chunks_of_one_name_pair_up_in_paint_order() {- let tree = identity_tree();- let repeated = fill_command_bytes(IntRect::new(50, 50, 10, 10), GREEN);- let between = fill_command_bytes(IntRect::new(70, 50, 10, 10), BLUE);- let edge = |x, color| fill_command_bytes(IntRect::new(x, 10, 10, 10), color);- assert_eq!(- damage(- &list_of(&[&edge(0, RED), &repeated, &between, &repeated, &edge(20, RED)]),- &tree,- &list_of(&[&edge(0, YELLOW), &repeated, &between, &repeated, &edge(20, CYAN)]),- &tree- ),- Some(IntRect::new(0, 9, 31, 12))- );- assert_eq!(- damage(- &list_of(&[&repeated, &between, &repeated]),- &tree,- &list_of(&[&repeated, &repeated]),- &tree- ),- Some(IntRect::new(69, 49, 12, 12))- );- assert_eq!(- damage(- &list_of(&[&repeated, &between]),- &tree,- &list_of(&[&repeated, &between, &repeated]),- &tree- ),- Some(IntRect::new(49, 49, 12, 12))- );- }-- #[test]- fn a_scroll_offset_change_damages_what_the_scroller_moves_and_nothing_else() {- let mut tree = identity_tree();- let scroller = tree.append_spatial(scroll_data(), VISUAL_VIEWPORT_NODE_INDEX);- let scrolled = tree.append_spatial(identity_transform(), scroller);- let list = list_of(&[- &fill_in(- IntRect::new(10, 10, 10, 10),- RED,- context_in(scrolled, ContextRef::default()),- ),- &fill_command_bytes(IntRect::new(60, 60, 10, 10), GREEN),- ]);- let unscrolled = vec![FloatPoint::default(); tree.spatial_nodes.len()];- let mut scrolled_down = unscrolled.clone();- scrolled_down[scroller.0 as usize] = FloatPoint { x: 0.0, y: 20.0 };- let viewport = IntRect::new(0, 0, 100, 100);- assert_eq!(- damage_with_scroll_offsets(&list, &tree, &unscrolled, &list, &tree, &unscrolled, viewport),- Some(IntRect::default())- );- assert_eq!(- damage_with_scroll_offsets(&list, &tree, &unscrolled, &list, &tree, &scrolled_down, viewport),- Some(IntRect::new(9, 9, 12, 32))- );- }-- #[test]- fn a_change_reaches_a_child_stored_below_its_parent() {- let mut tree = identity_tree();- let child = tree.append_spatial(identity_transform(), VISUAL_VIEWPORT_NODE_INDEX);- let scroller = tree.append_spatial(scroll_data(), VISUAL_VIEWPORT_NODE_INDEX);- tree.spatial_nodes[child.0 as usize].parent = scroller;- let list = fill_in(- IntRect::new(10, 10, 10, 10),- RED,- context_in(child, ContextRef::default()),- );- let unscrolled = vec![FloatPoint::default(); tree.spatial_nodes.len()];- let mut scrolled_down = unscrolled.clone();- scrolled_down[scroller.0 as usize] = FloatPoint { x: 0.0, y: 20.0 };- assert_eq!(- damage_with_scroll_offsets(- &list,- &tree,- &unscrolled,- &list,- &tree.clone(),- &scrolled_down,- IntRect::new(0, 0, 100, 100)- ),- Some(IntRect::new(9, 9, 12, 32))- );- }-- #[test]- fn a_node_given_another_parent_damages_what_it_draws() {- let tree_with_child_of_shifted_node = |child_of_shifted_node: bool| {- let mut tree = identity_tree();- let shifted = tree.append_spatial(- SpatialData::Transform(transform(translation_matrix(30.0, 0.0, 0.0))),- VISUAL_VIEWPORT_NODE_INDEX,- );- let child = tree.append_spatial(- identity_transform(),- if child_of_shifted_node {- shifted- } else {- VISUAL_VIEWPORT_NODE_INDEX- },- );- (tree, child)- };- let (old_tree, child) = tree_with_child_of_shifted_node(false);- let (new_tree, _) = tree_with_child_of_shifted_node(true);- let list = fill_in(- IntRect::new(10, 10, 10, 10),- RED,- context_in(child, ContextRef::default()),- );- assert_eq!(- damage(&list, &old_tree, &list, &new_tree),- Some(IntRect::new(9, 9, 42, 12))- );- }-- #[test]- fn a_slot_that_holds_another_kind_of_node_damages_what_it_draws_even_where_it_draws_alike() {- let mut old_tree = identity_tree();- let node = old_tree.append_spatial(identity_transform(), VISUAL_VIEWPORT_NODE_INDEX);- let mut new_tree = identity_tree();- new_tree.append_spatial(scroll_data(), VISUAL_VIEWPORT_NODE_INDEX);- let list = fill_in(- IntRect::new(10, 10, 10, 10),- RED,- context_in(node, ContextRef::default()),- );- assert_eq!(- damage(&list, &old_tree, &list, &new_tree),- Some(IntRect::new(9, 9, 12, 12))- );- }-- #[test]- fn a_clip_placed_in_another_space_damages_what_it_clips() {- let tree_with_clip_in_shifted_space = |in_shifted_space: bool| {- let mut tree = identity_tree();- let shifted = tree.append_spatial(- SpatialData::Transform(transform(translation_matrix(0.0, 5.0, 0.0))),- VISUAL_VIEWPORT_NODE_INDEX,- );- clip_context(&mut tree, clip(FloatRect::new(0.0, 0.0, 100.0, 100.0)));- if in_shifted_space {- tree.clip_nodes[0].spatial = shifted;- }- tree- };- let (old_tree, new_tree) = (- tree_with_clip_in_shifted_space(false),- tree_with_clip_in_shifted_space(true),- );- let list = fill_in(- IntRect::new(10, 10, 10, 10),- RED,- ContextRef {- clip: ClipNodeIndex(0),- ..ContextRef::default()- },- );- assert_eq!(- damage(&list, &old_tree, &list, &tree_with_clip_in_shifted_space(false)),- Some(IntRect::default())- );- assert_eq!(- damage(&list, &old_tree, &list, &new_tree),- Some(IntRect::new(9, 9, 12, 12))- );- }-- #[test]- fn an_effect_that_starts_in_another_clip_damages_its_content() {- let tree_with_effect_starting_in_second_clip = |starts_in_second_clip: bool| {- let mut tree = identity_tree();- let first_clip = tree.append_clip(- clip(FloatRect::new(0.0, 0.0, 100.0, 100.0)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let second_clip = tree.append_clip(- clip(FloatRect::new(0.0, 0.0, 100.0, 100.0)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let effect = tree.append_effect(- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity: 0.5,- blend_mode: CompositingAndBlendingOperator::Normal,- filter: None,- backdrop_filter: None,- }),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- if starts_in_second_clip { second_clip } else { first_clip },- );- (tree, effect)- };- let (old_tree, effect) = tree_with_effect_starting_in_second_clip(false);- let (new_tree, _) = tree_with_effect_starting_in_second_clip(true);- let list = fill_in(- IntRect::new(10, 10, 10, 10),- RED,- ContextRef {- effect,- ..ContextRef::default()- },- );- assert_eq!(- damage(&list, &old_tree, &list, &new_tree),- Some(IntRect::new(9, 9, 12, 12))- );- }-- fn mask_content_declaration(content: &TestDisplayList, rect: IntRect, context: ContextRef) -> TestDisplayList {- let mut bytes = TestDisplayList::default();- append_record(- &mut bytes,- &DeclareMaskContent {- rect,- effect: context.effect,- content: DisplayListDataSpan {- offset: std::mem::size_of::<DeclareMaskContent>() as u32,- size: content.len() as u32,- },- },- content,- context,- &[],- );- bytes.end_chunk();- bytes- }-- #[test]- fn a_mask_whose_declaring_chunk_changed_damages_everything_it_masks() {- let mut tree = identity_tree();- let masked = effect_context(&mut tree, mask(IntRect::new(0, 0, 100, 100)));- let declared_rect = IntRect::new(10, 10, 10, 10);- let scene = |declared_color| {- list_of(&[- &mask_content_declaration(&fill_in(declared_rect, declared_color, masked), declared_rect, masked),- &fill_in(IntRect::new(60, 60, 10, 10), BLUE, masked),- &fill_command_bytes(IntRect::new(80, 10, 10, 10), GREEN),- ])- };- assert_eq!(- damage(&scene(RED), &tree, &scene(RED), &tree.clone()),- Some(IntRect::default())- );- assert_eq!(- damage(&scene(RED), &tree, &scene(GREEN), &tree),- Some(IntRect::new(9, 9, 62, 62))- );- }-- #[test]- fn a_mask_holding_text_is_unchanged_while_its_declaring_chunk_is() {- let tree_with_mask = || {- let mut tree = identity_tree();- let masked = effect_context(&mut tree, mask(IntRect::new(0, 0, 100, 100)));- (tree, masked)- };- let (old_tree, masked) = tree_with_mask();- let (new_tree, _) = tree_with_mask();- let text_rect = IntRect::new(10, 10, 20, 20);- let text = command_bytes(- &DrawGlyphRun {- stroke_width: 0.0,- font_smoothing: 0,- font_id: FontResourceId(1),- glyphs: DisplayListDataSpan::default(),- rect: text_rect,- glyph_bounding_rect: text_rect,- translation: FloatPoint { x: 10.0, y: 10.0 },- scale: 1.0,- color: RED,- orientation: Orientation::Horizontal,- },- masked,- );- let list = list_of(&[- &mask_content_declaration(&text, text_rect, masked),- &fill_in(IntRect::new(60, 60, 10, 10), BLUE, masked),- ]);- assert_eq!(damage(&list, &old_tree, &list, &new_tree), Some(IntRect::default()));- }-- #[test]- fn a_mask_whose_declaration_moved_damages_everything_it_masks() {- let tree_with_declaration_shifted_by = |shift: f32| {- let mut tree = identity_tree();- let declaration_space = tree.append_spatial(- SpatialData::Transform(transform(translation_matrix(shift, 0.0, 0.0))),- VISUAL_VIEWPORT_NODE_INDEX,- );- let masked = effect_context(&mut tree, mask(IntRect::new(0, 0, 100, 100)));- (tree, declaration_space, masked)- };- let (old_tree, declaration_space, masked) = tree_with_declaration_shifted_by(0.0);- let (new_tree, _, _) = tree_with_declaration_shifted_by(5.0);- let declared_rect = IntRect::new(10, 10, 10, 10);- let declaration_context = context_in(declaration_space, masked);- let list = list_of(&[- &mask_content_declaration(- &fill_in(declared_rect, RED, declaration_context),- declared_rect,- declaration_context,- ),- &fill_in(IntRect::new(60, 60, 10, 10), BLUE, masked),- ]);- assert_eq!(- damage(&list, &old_tree, &list, &new_tree),- Some(IntRect::new(9, 9, 62, 62))- );- }-- #[test]- fn a_changed_chunk_with_a_scrollbar_the_compositor_paints_needs_a_full_repaint_only_where_it_moved() {- let rect = IntRect::new(10, 10, 20, 20);- let scene = |color| {- let mut list = TestDisplayList::default();- append_record(&mut list, &compositor_scrollbar(true), &[], ContextRef::default(), &[]);- append_record(&mut list, &fill(rect, color), &[], ContextRef::default(), &[]);- list- };- let moved_tree = VisualContextTree::create(transform(translation_matrix(10.0, 0.0, 0.0)));- assert_eq!(- damage(&scene(RED), &identity_tree(), &scene(BLUE), &identity_tree()),- Some(IntRect::new(9, 9, 22, 22))- );- assert_eq!(damage(&scene(RED), &identity_tree(), &scene(BLUE), &moved_tree), None);- }-- #[test]- fn a_frame_of_the_same_list_tree_and_scroll_offsets_is_damaged_only_where_that_is_forced() {- let tree = identity_tree();- let list = list_of(&[- &fill_command_bytes(IntRect::new(10, 10, 20, 20), RED),- &fill_command_bytes(IntRect::new(50, 50, 20, 20), BLUE),- ]);- assert_eq!(- damage_for_live_content_changes(&list, &tree, LiveContentChanges::default()),- Some(IntRect::default())- );- assert_eq!(- damage_for_live_content_changes(- &list,- &tree,- LiveContentChanges {- forced_damage_rect: IntRect::new(5, 5, 5, 5),- ..LiveContentChanges::default()- }- ),- Some(IntRect::new(4, 4, 7, 7))- );- }-}diff --git a/Libraries/LibCompositing/Rust/src/display_list/depth_sorted_plan.rs b/Libraries/LibCompositing/Rust/src/display_list/depth_sorted_plan.rsindex e3eaa69ddf2..bdea9766dc8 100644--- a/Libraries/LibCompositing/Rust/src/display_list/depth_sorted_plan.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/depth_sorted_plan.rs@@ -20,16 +20,16 @@ struct LeafBounds {unbounded: bool,}-struct CommandChunk {+struct PlaneRunSpan {first_run: u32,run_count: u32,leaf: SpatialNodeIndex,context: SpatialNodeIndex,- bounds_by_level: Vec<LeafBounds>,+ bounds_in_leaf_of_each_enclosing_context: Vec<LeafBounds>,}#[derive(Clone, Copy)]-struct ChunkPlacement {+struct RunSpanPlacement {child_context: SpatialNodeIndex,leaf: SpatialNodeIndex,}@@ -66,11 +66,11 @@ struct DepthSortedPlanBuilder<'a> {}impl DepthSortedPlanBuilder<'_> {- fn append_run_span(&mut self, chunk: &CommandChunk) {+ fn append_run_span(&mut self, run_span: &PlaneRunSpan) {self.steps.push(DepthSortedReplayStep {kind: DepthSortedReplayStepKind::RunSpan,- first_run: chunk.first_run,- run_count: chunk.run_count,+ first_run: run_span.first_run,+ run_count: run_span.run_count,vertex_offset: 0,vertex_count: 0,});@@ -99,31 +99,37 @@ impl DepthSortedPlanBuilder<'_> {});}- fn emit_chunks(&mut self, chunks: &[CommandChunk], enclosing_context: SpatialNodeIndex) {+ fn emit_run_spans(&mut self, run_spans: &[PlaneRunSpan], enclosing_context: SpatialNodeIndex) {let mut index = 0;- while index < chunks.len() {- let child_context = place_chunk_within(&chunks[index], enclosing_context, self.contexts).child_context;+ while index < run_spans.len() {+ let child_context =+ place_run_span_within(&run_spans[index], enclosing_context, self.contexts).child_context;if child_context == NO_SORTING_CONTEXT {- self.append_run_span(&chunks[index]);+ self.append_run_span(&run_spans[index]);index += 1;continue;}- let mut run_end = index + 1;- while run_end < chunks.len()- && place_chunk_within(&chunks[run_end], enclosing_context, self.contexts).child_context == child_context+ let mut end_of_spans_in_child_context = index + 1;+ while end_of_spans_in_child_context < run_spans.len()+ && place_run_span_within(+ &run_spans[end_of_spans_in_child_context],+ enclosing_context,+ self.contexts,+ )+ .child_context+ == child_context{- run_end += 1;+ end_of_spans_in_child_context += 1;}- self.sort_and_emit_context(&chunks[index..run_end], child_context);- index = run_end;+ self.sort_and_emit_context(&run_spans[index..end_of_spans_in_child_context], child_context);+ index = end_of_spans_in_child_context;}}- fn sort_and_emit_context(&mut self, chunks: &[CommandChunk], sorting_context: SpatialNodeIndex) {- // The unit of sorting is a run of consecutive chunks sharing a plane, not the whole plane. Coplanar planes render- // in painting order, and separate runs of one plane interleaved with a coplanar sibling must keep their recorded- // positions relative to it.- struct PlaneRun {+ fn sort_and_emit_context(&mut self, run_spans: &[PlaneRunSpan], sorting_context: SpatialNodeIndex) {+ // Not whole planes: separate spans of one plane interleaved with a coplanar sibling keep their recorded+ // positions relative to it, as coplanar planes render in painting order.+ struct ConsecutiveSpansOfOnePlane {leaf: SpatialNodeIndex,begin: usize,end: usize,@@ -131,11 +137,11 @@ impl DepthSortedPlanBuilder<'_> {unbounded: bool,}- let mut runs: Vec<PlaneRun> = Vec::new();- for (index, chunk) in chunks.iter().enumerate() {- let leaf = place_chunk_within(chunk, sorting_context, self.contexts).leaf;- if runs.last().is_none_or(|run| run.leaf != leaf) {- runs.push(PlaneRun {+ let mut sorting_units: Vec<ConsecutiveSpansOfOnePlane> = Vec::new();+ for (index, run_span) in run_spans.iter().enumerate() {+ let leaf = place_run_span_within(run_span, sorting_context, self.contexts).leaf;+ if sorting_units.last().is_none_or(|unit| unit.leaf != leaf) {+ sorting_units.push(ConsecutiveSpansOfOnePlane {leaf,begin: index,end: index + 1,@@ -143,25 +149,25 @@ impl DepthSortedPlanBuilder<'_> {unbounded: false,});} else {- runs.last_mut().unwrap().end = index + 1;+ sorting_units.last_mut().unwrap().end = index + 1;}- for entry in &chunk.bounds_by_level {- if entry.leaf == leaf {- let run = runs.last_mut().unwrap();- run.bounds = run.bounds.united(entry.bounds);- run.unbounded |= entry.unbounded;+ for leaf_bounds in &run_span.bounds_in_leaf_of_each_enclosing_context {+ if leaf_bounds.leaf == leaf {+ let unit = sorting_units.last_mut().unwrap();+ unit.bounds = unit.bounds.united(leaf_bounds.bounds);+ unit.unbounded |= leaf_bounds.unbounded;}}}- if runs.iter().any(|run| run.unbounded) {- self.emit_chunks(chunks, sorting_context);+ if sorting_units.iter().any(|unit| unit.unbounded) {+ self.emit_run_spans(run_spans, sorting_context);return;}let context_to_device = self.transform_palette[sorting_context.0 as usize];let Some(device_to_context) = context_to_device.inverse() else {- self.emit_chunks(chunks, sorting_context);+ self.emit_run_spans(run_spans, sorting_context);return;};let mut eye = device_to_context.map_vector4([0.0, 0.0, 1.0, 0.0]);@@ -169,25 +175,31 @@ impl DepthSortedPlanBuilder<'_> {eye = [-eye[0], -eye[1], -eye[2], -eye[3]];}- // Runs that are fully backface-culled, that lie entirely behind the eye, or whose content bounds are empty- // draw nothing and are dropped rather than sorted. The bounds are inflated so a split piece's clip stays clear of- // the anti-aliased fringe of the content's own edges.+ const MARGIN_KEEPING_SPLIT_CLIPS_CLEAR_OF_ANTIALIASED_EDGES: f32 = 4.0;let mut polygons = Vec::new();- for (run_index, run) in runs.iter().enumerate() {- if run.bounds.is_empty() {+ for (unit_index, unit) in sorting_units.iter().enumerate() {+ if unit.bounds.is_empty() {continue;}- let leaf_to_context = self.leaf_to_context_palette[run.leaf.0 as usize];- let vertices = map_rect_through_projection(leaf_to_context, run.bounds.inflated(4.0, 4.0));- if vertices.len() < 3 {+ let leaf_to_context = self.leaf_to_context_palette[unit.leaf.0 as usize];+ let vertices = map_rect_through_projection(+ leaf_to_context,+ unit.bounds.inflated(+ MARGIN_KEEPING_SPLIT_CLIPS_CLEAR_OF_ANTIALIASED_EDGES,+ MARGIN_KEEPING_SPLIT_CLIPS_CLEAR_OF_ANTIALIASED_EDGES,+ ),+ );+ let lies_behind_eye_in_context = vertices.len() < 3;+ if lies_behind_eye_in_context {continue;}- if map_polygon_through_projection(context_to_device, &vertices).len() < 3 {+ let lies_behind_eye_on_device = map_polygon_through_projection(context_to_device, &vertices).len() < 3;+ if lies_behind_eye_on_device {continue;}polygons.push(BspPolygon {vertices,- plane_index: run_index,+ plane_index: unit_index,clipped: false,});}@@ -195,17 +207,17 @@ impl DepthSortedPlanBuilder<'_> {// FIXME: Pieces of a split plane whose content carries filter effects render incorrectly: each piece filters its// clipped content independently, truncating filter output at the piece boundary and seaming it along the cut.for polygon in split_and_sort_polygons_back_to_front(polygons, eye, context_to_device) {- let run = &runs[polygon.plane_index];+ let unit = &sorting_units[polygon.plane_index];if polygon.clipped || polygon_crosses_eye_plane(context_to_device, &polygon.vertices) {let clip_vertices = map_polygon_through_projection(context_to_device, &polygon.vertices);if clip_vertices.len() < 3 {continue;}self.append_plane_clip(clip_vertices);- self.emit_chunks(&chunks[run.begin..run.end], sorting_context);+ self.emit_run_spans(&run_spans[unit.begin..unit.end], sorting_context);self.append_pop_plane_clip();} else {- self.emit_chunks(&chunks[run.begin..run.end], sorting_context);+ self.emit_run_spans(&run_spans[unit.begin..unit.end], sorting_context);}}}@@ -225,7 +237,7 @@ struct LeafMappingsKey {spatial_node: SpatialNodeIndex,}-fn ensure_mappings(+fn ensure_mappings_to_enclosing_leaves(key: LeafMappingsKey,mappings_key: &mut Option<LeafMappingsKey>,mappings: &mut Vec<LeafMapping>,@@ -293,37 +305,36 @@ fn bounds_of_mapped_rect(matrix: FloatMatrix4x4, rect: FloatRect) -> FloatRect {FloatRect::new(min_x, min_y, max_x - min_x, max_y - min_y)}-fn partition_command_runs_into_plane_chunks(- command_runs: &[DisplayListCommandRun],+fn partition_command_runs_into_plane_run_spans<'a>(+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun>,contexts: &SortingContexts,transform_palette: &[FloatMatrix4x4],draw_space: &[SpatialNodeIndex],backface_culled: &[bool],culling: &TreeCullingScratch,-) -> Vec<CommandChunk> {+) -> Vec<PlaneRunSpan> {let mut mappings = Vec::new();let mut mappings_key = None;- // A run's ink bounds already leave out clips; mapping their union once per level is- // conservative, as it can only widen a plane's bounds.- let mut chunks: Vec<CommandChunk> = Vec::new();- for (run_index, run) in command_runs.iter().enumerate() {+ // Ink bounds leave out clips, so mapping their union once per enclosing context only widens a plane's bounds.+ let mut run_spans: Vec<PlaneRunSpan> = Vec::new();+ for (run_index, run) in command_runs.into_iter().enumerate() {let spatial = run.context.spatial;let leaf = contexts.leaf_by_node[spatial.0 as usize];let sorting_context = contexts.context_by_node[spatial.0 as usize];- if chunks+ if run_spans.last()- .is_none_or(|chunk| chunk.leaf != leaf || chunk.context != sorting_context)+ .is_none_or(|run_span| run_span.leaf != leaf || run_span.context != sorting_context){- chunks.push(CommandChunk {+ run_spans.push(PlaneRunSpan {first_run: run_index as u32,run_count: 1,leaf,context: sorting_context,- bounds_by_level: Vec::new(),+ bounds_in_leaf_of_each_enclosing_context: Vec::new(),});} else {- chunks.last_mut().unwrap().run_count += 1;+ run_spans.last_mut().unwrap().run_count += 1;}if run.ink_bounds.is_empty() || sorting_context == NO_SORTING_CONTEXT || backface_culled[spatial.0 as usize] {@@ -332,7 +343,7 @@ fn partition_command_runs_into_plane_chunks(if culling.context_culls_everything(run.context) {continue;}- ensure_mappings(+ ensure_mappings_to_enclosing_leaves(LeafMappingsKey {leaf,context: sorting_context,@@ -344,58 +355,60 @@ fn partition_command_runs_into_plane_chunks(transform_palette,);let rect = run.ink_bounds.to_float();- let level_entries = &mut chunks.last_mut().unwrap().bounds_by_level;+ let bounds_in_enclosing_leaves = &mut run_spans.last_mut().unwrap().bounds_in_leaf_of_each_enclosing_context;for mapping in &mappings {- let entry_index = level_entries.iter().position(|entry| entry.leaf == mapping.leaf);- let entry = if let Some(index) = entry_index {- &mut level_entries[index]+ let existing_index = bounds_in_enclosing_leaves+ .iter()+ .position(|leaf_bounds| leaf_bounds.leaf == mapping.leaf);+ let leaf_bounds = if let Some(index) = existing_index {+ &mut bounds_in_enclosing_leaves[index]} else {- level_entries.push(LeafBounds {+ bounds_in_enclosing_leaves.push(LeafBounds {leaf: mapping.leaf,bounds: FloatRect::default(),unbounded: false,});- level_entries.last_mut().unwrap()+ bounds_in_enclosing_leaves.last_mut().unwrap()};if mapping.unbounded {- entry.unbounded = true;+ leaf_bounds.unbounded = true;} else if let Some(to_leaf) = mapping.to_leaf {- entry.bounds = entry.bounds.united(bounds_of_mapped_rect(to_leaf, rect));+ leaf_bounds.bounds = leaf_bounds.bounds.united(bounds_of_mapped_rect(to_leaf, rect));} else {- entry.bounds = entry.bounds.united(rect);+ leaf_bounds.bounds = leaf_bounds.bounds.united(rect);}}}- chunks+ run_spans}-fn place_chunk_within(- chunk: &CommandChunk,+fn place_run_span_within(+ run_span: &PlaneRunSpan,enclosing_context: SpatialNodeIndex,contexts: &SortingContexts,-) -> ChunkPlacement {- if chunk.context == enclosing_context {- return ChunkPlacement {+) -> RunSpanPlacement {+ if run_span.context == enclosing_context {+ return RunSpanPlacement {child_context: NO_SORTING_CONTEXT,- leaf: chunk.leaf,+ leaf: run_span.leaf,};}- let mut current = chunk.context;+ let mut current = run_span.context;while current != NO_SORTING_CONTEXT {let Some(link) = contexts.links.get(¤t.0) else {break;};if link.parent_context == enclosing_context {- return ChunkPlacement {+ return RunSpanPlacement {child_context: current,leaf: link.parent_leaf,};}current = link.parent_context;}- ChunkPlacement {+ RunSpanPlacement {child_context: NO_SORTING_CONTEXT,- leaf: chunk.leaf,+ leaf: run_span.leaf,}}@@ -405,12 +418,12 @@ fn place_chunk_within(// according to Newell's algorithm, with the planes transformed by the accumulated 3D transformation matrix.// Coplanar 3D transformed elements are rendered in painting order.//-// The command run table is partitioned into contiguous chunks that share a plane. Each 3D rendering context's+// The command runs are partitioned into contiguous run spans that share a plane. Each 3D rendering context's// planes are ordered back to front with a BSP tree over their content bounds; a plane cut by another's plane is-// replayed once per piece under a device-space polygon clip. Chunks in a nested context sort among themselves+// replayed once per piece under a device-space polygon clip. Run spans in a nested context sort among themselves// inside the plane of the outer context they render into.-pub fn build_depth_sorted_replay_plan(- command_runs: &[DisplayListCommandRun],+pub fn build_depth_sorted_replay_plan<'a>(+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun>,contexts: &SortingContexts,transform_palette: &[FloatMatrix4x4],leaf_to_context_palette: &[FloatMatrix4x4],@@ -418,7 +431,7 @@ pub fn build_depth_sorted_replay_plan(backface_culled: &[bool],culling: &TreeCullingScratch,) -> DepthSortedReplayPlan {- let chunks = partition_command_runs_into_plane_chunks(+ let run_spans = partition_command_runs_into_plane_run_spans(command_runs,contexts,transform_palette,@@ -433,7 +446,7 @@ pub fn build_depth_sorted_replay_plan(steps: Vec::new(),vertices: Vec::new(),};- builder.emit_chunks(&chunks, NO_SORTING_CONTEXT);+ builder.emit_run_spans(&run_spans, NO_SORTING_CONTEXT);DepthSortedReplayPlan {steps: builder.steps,vertices: builder.vertices,diff --git a/Libraries/LibCompositing/Rust/src/display_list/effect_clip_plan.rs b/Libraries/LibCompositing/Rust/src/display_list/effect_clip_plan.rsindex f620bec1319..bb5a6e83742 100644--- a/Libraries/LibCompositing/Rust/src/display_list/effect_clip_plan.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/effect_clip_plan.rs@@ -17,14 +17,17 @@ pub struct EffectClipPlan {}impl EffectClipPlan {- pub fn new(tree: &VisualContextTree, runs: &[DisplayListCommandRun]) -> Option<Self> {- Self::from_contexts(tree, runs.iter().map(|run| run.context))+ pub fn new<'a>(+ tree: &VisualContextTree,+ runs: impl IntoIterator<Item = &'a DisplayListCommandRun>,+ ) -> Option<Self> {+ Self::from_contexts(tree, runs.into_iter().map(|run| run.context))}pub fn from_contexts(tree: &VisualContextTree, contexts: impl IntoIterator<Item = ContextRef>) -> Option<Self> {let mut output_clips = vec![None; tree.effect_nodes.len()];let clip_depths = std::cell::OnceCell::new();- let common_clip = |a: ClipNodeIndex, b: ClipNodeIndex| {+ let lowest_common_clip = |a: ClipNodeIndex, b: ClipNodeIndex| {if a == b {return a;}@@ -45,15 +48,16 @@ impl EffectClipPlan {b,)};- let activate = |mut effect: EffectNodeIndex, clips: &mut [Option<ClipNodeIndex>]| {- while !effect.is_none() && clips[effect.0 as usize].is_none() {- let node = &tree.effect_nodes[effect.0 as usize];- clips[effect.0 as usize] = Some(node.local_clip);- effect = node.parent;- }- };+ let mark_effect_and_ancestors_participating =+ |mut effect: EffectNodeIndex, clips: &mut [Option<ClipNodeIndex>]| {+ while !effect.is_none() && clips[effect.0 as usize].is_none() {+ let node = &tree.effect_nodes[effect.0 as usize];+ clips[effect.0 as usize] = Some(node.local_clip);+ effect = node.parent;+ }+ };if let Some(effect) = tree.root_isolation_effect {- activate(effect, &mut output_clips);+ mark_effect_and_ancestors_participating(effect, &mut output_clips);}for context in contexts {if !tree.context_is_valid(context) {@@ -62,18 +66,18 @@ impl EffectClipPlan {if context.effect.is_none() {continue;}- activate(context.effect, &mut output_clips);- let output = &mut output_clips[context.effect.0 as usize];- *output = Some(common_clip(output.unwrap(), context.clip));+ mark_effect_and_ancestors_participating(context.effect, &mut output_clips);+ let output_clip = &mut output_clips[context.effect.0 as usize];+ *output_clip = Some(lowest_common_clip(output_clip.unwrap(), context.clip));}// A parent's layer must be outside every participating child's output clip.for &index in tree.effect_dependency_order().iter().rev() {let parent = tree.effect_nodes[index as usize].parent;if !parent.is_none()- && let Some(clip) = output_clips[index as usize]+ && let Some(child_output_clip) = output_clips[index as usize]{- let parent_output = &mut output_clips[parent.0 as usize];- *parent_output = Some(common_clip(parent_output.unwrap(), clip));+ let parent_output_clip = &mut output_clips[parent.0 as usize];+ *parent_output_clip = Some(lowest_common_clip(parent_output_clip.unwrap(), child_output_clip));}}Some(Self { output_clips })@@ -86,6 +90,16 @@ impl EffectClipPlan {pub fn output_clip_if_participating(&self, effect: EffectNodeIndex) -> Option<ClipNodeIndex> {self.output_clips.get(effect.0 as usize).copied().flatten()}++ /// Whether the two plans give every effect the same output clip, or leave it out alike, whatever nodes past the+ /// last participating effect their trees hold.+ pub fn places_effects_as(&self, other: &Self) -> bool {+ let effect_count = self.output_clips.len().max(other.output_clips.len());+ (0..effect_count as u32).all(|index| {+ self.output_clip_if_participating(EffectNodeIndex(index))+ == other.output_clip_if_participating(EffectNodeIndex(index))+ })+ }}#[cfg(test)]@@ -194,6 +208,29 @@ mod tests {assert_eq!(first.output_clip(effect), ClipNodeIndex::NONE);}+ #[test]+ fn a_plan_holds_under_a_tree_that_places_its_effects_alike() {+ let mut tree = tree();+ let outer = clip(&mut tree, ClipNodeIndex::NONE);+ let inner = clip(&mut tree, outer);+ let parent = effect(&mut tree, EffectNodeIndex::NONE, outer);+ let child = effect(&mut tree, parent, inner);+ let contexts = [context(child, inner)];+ let plan = EffectClipPlan::from_contexts(&tree, contexts).unwrap();++ let mut tree_with_unused_effect = tree.clone();+ effect(&mut tree_with_unused_effect, child, ClipNodeIndex::NONE);+ let plan_with_unused_effect = EffectClipPlan::from_contexts(&tree_with_unused_effect, contexts).unwrap();+ assert!(plan.places_effects_as(&plan_with_unused_effect));+ assert!(plan_with_unused_effect.places_effects_as(&plan));++ let mut tree_with_other_parent = tree.clone();+ let other_parent = effect(&mut tree_with_other_parent, EffectNodeIndex::NONE, inner);+ tree_with_other_parent.effect_nodes[child.0 as usize].parent = other_parent;+ let plan_with_other_parent = EffectClipPlan::from_contexts(&tree_with_other_parent, contexts).unwrap();+ assert!(!plan.places_effects_as(&plan_with_other_parent));+ }+#[test]fn root_isolation_participates_even_without_drawing_runs() {let mut tree = tree();diff --git a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rsindex 120370043a3..78b7dbd45f2 100644--- a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs@@ -11,36 +11,100 @@//! subtree. Content is therefore mapped into each effect's space before that effect's filter//! spreads it, and an effect's output becomes part of its parent's content.+use crate::display_list::animated_transform_spaces::easing_stays_within_unit_interval;use crate::display_list::commands::{DisplayListCommandRun, EffectNodeIndex, SpatialNodeIndex};-use crate::filter_bytes;+use crate::display_list::placement::{+ ANTIALIASING_MARGIN_IN_DEVICE_PIXELS, RasterSpaceGeometry, enclosing_int_rect_within_extent_limit, is_finite_rect,+};+use crate::display_list::reach::Reach;+use crate::filter_bytes::{self, filter_functions_graph};+use crate::host::FfiVisualAnimationTargetKind;+use crate::visual_animation::VisualAnimationValue;use crate::visual_context::{EffectNode, EffectNodeData, VisualContextTree, WorldTransforms};-use libgfx_rust::FloatRect;+use libgfx_rust::filter::Filter;+use libgfx_rust::{FloatMatrix4x4, FloatRect, IntRect};+use std::collections::HashMap;-#[derive(Clone, Copy, Debug, PartialEq)]-pub enum Extent {- Nothing,- Within(FloatRect),- /// Reaches anywhere, through a filter that paints everywhere or through a space that does not- /// map onto the effect's as a two-dimensional transform.- Anywhere,+/// Where content lies in an effect's space. It reaches anywhere through a filter that paints everywhere or through a+/// space that does not map onto the effect's as a two-dimensional transform.+pub type Extent = Reach<FloatRect>;++pub(crate) const LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS: f32 = 2048.0;++pub(crate) fn filter_read_reach_in_device_pixels(filter: &[u8], effect_to_device: &FloatMatrix4x4) -> Option<i32> {+ if !effect_to_device.is_2d_affine() {+ return None;+ }+ let probe = FloatRect::new(0.0, 0.0, 1.0, 1.0);+ let changed_output_bounds_of_probe = filter_bytes::changed_output_bounds(filter, probe)?;+ let reach_in_effect_space = [+ probe.x - changed_output_bounds_of_probe.x,+ changed_output_bounds_of_probe.right() - probe.right(),+ probe.y - changed_output_bounds_of_probe.y,+ changed_output_bounds_of_probe.bottom() - probe.bottom(),+ ]+ .into_iter()+ .fold(0.0f32, f32::max);+ let affine = effect_to_device.extract_2d_affine();+ let largest_stretch = affine.a().abs() + affine.b().abs() + affine.c().abs() + affine.d().abs();+ let reach_in_device_pixels =+ (reach_in_effect_space * largest_stretch).ceil() + ANTIALIASING_MARGIN_IN_DEVICE_PIXELS as f32;+ (reach_in_device_pixels.is_finite() && reach_in_device_pixels <= LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS)+ .then_some(reach_in_device_pixels as i32)}-impl Extent {- pub fn united(self, other: Self) -> Self {- match (self, other) {- (Self::Nothing, extent) | (extent, Self::Nothing) => extent,- (Self::Within(rect), Self::Within(other)) => Self::Within(rect.united(other)),- _ => Self::Anywhere,- }+/// How far past each pixel the filter of an effect the compositor composites reads what is composited inside it, in+/// device pixels. Placing a list composites no filter that reads farther than is followed, so that limit stands in only+/// while a transform the compositor animates scales a filter past what placing saw.+pub fn composited_filter_read_reach_in_device_pixels(filter: &[u8], effect_to_device: &FloatMatrix4x4) -> i32 {+ filter_read_reach_in_device_pixels(filter, effect_to_device)+ .unwrap_or(LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS as i32)+}++/// Where a backdrop filter reads, in the raster coordinates of the space: its region, and how far its filter reaches+/// past it.+pub fn backdrop_filter_read_reach(+ tree: &VisualContextTree,+ geometry: &RasterSpaceGeometry,+ effect: EffectNodeIndex,+) -> Reach<IntRect> {+ let effect_node = &tree.effect_nodes[effect.0 as usize];+ let EffectNodeData::Effects(effects) = &effect_node.data else {+ return Reach::Anywhere;+ };+ let Some(backdrop) = &effects.backdrop_filter else {+ return Reach::Anywhere;+ };+ let effect_to_device = geometry.world.draw_matrix(effect_node.spatial);+ let Some(read_reach_in_device_pixels) = filter_read_reach_in_device_pixels(&backdrop.filter, &effect_to_device)+ else {+ return Reach::Anywhere;+ };+ let backdrop_region = geometry+ .world+ .map_rect_to_root(effect_node.spatial, backdrop.region.to_float());+ if !is_finite_rect(backdrop_region) {+ return Reach::Anywhere;}+ Reach::Within(enclosing_int_rect_within_extent_limit(backdrop_region).inflated_edges(+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ ))+}- fn mapped_between_spaces(self, world: &WorldTransforms, from: SpatialNodeIndex, to: SpatialNodeIndex) -> Self {- match self {- Self::Within(rect) => world- .map_rect_between_spaces(rect, from, to)- .map_or(Self::Anywhere, Self::Within),- extent => extent,- }+fn extent_mapped_between_spaces(+ extent: Extent,+ world: &WorldTransforms,+ from: SpatialNodeIndex,+ to: SpatialNodeIndex,+) -> Extent {+ match extent {+ Extent::Within(rect) => world+ .map_rect_between_spaces(rect, from, to)+ .map_or(Extent::Anywhere, Extent::Within),+ extent => extent,}}@@ -61,29 +125,140 @@ pub fn effect_output_extent(node: &EffectNode, content: Extent) -> Extent {filter_bytes::output_bounds(filter, rect).map_or(Extent::Anywhere, Extent::Within)}-// Where an effect's filter can show a change to its content, given that change in the effect's space.-fn changed_output_extent(node: &EffectNode, change: Extent) -> Extent {- let Extent::Within(rect) = change else {- return change;+fn output_extent_of_content_change(node: &EffectNode, content_change_in_effect_space: Extent) -> Extent {+ let Extent::Within(rect) = content_change_in_effect_space else {+ return content_change_in_effect_space;};let EffectNodeData::Effects(effects) = &node.data else {- return change;+ return content_change_in_effect_space;};let Some(filter) = effects.filter.as_deref() else {- return change;+ return content_change_in_effect_space;};filter_bytes::changed_output_bounds(filter, rect).map_or(Extent::Anywhere, Extent::Within)}-/// Per effect, the nearest effect at or above it whose filter can spread content outside its-/// bounds, or `EffectNodeIndex::NONE`.-pub fn nearest_spreading_effects(tree: &VisualContextTree) -> Vec<EffectNodeIndex> {+/// The effect's filter, where it can spread its content outside its bounds.+pub fn spreading_filter_of(node: &EffectNode) -> Option<&[u8]> {+ let EffectNodeData::Effects(effects) = &node.data else {+ return None;+ };+ effects+ .filter+ .as_deref()+ .map(|filter| &filter[..])+ .filter(|filter| filter_bytes::may_affect_output_bounds(filter))+}++/// Whether the filter can show its content away from where the content is drawn, as an offset does.+pub fn filter_moves_what_it_filters(node: &EffectNode) -> bool {+ matches!(&node.data, EffectNodeData::Effects(effects)+ if effects.filter.as_deref().is_some_and(|filter| filter_bytes::may_move_what_it_filters(filter)))+}++/// Whether the effect's filter can spread its content outside its bounds at some sample of the animations of the tree:+/// the filter the tree holds or one a keyframe of a filter animation of the effect gives it can.+pub fn filter_may_spread_at_some_sample(tree: &VisualContextTree, effect: EffectNodeIndex) -> bool {+ spreading_filter_of(&tree.effect_nodes[effect.0 as usize]).is_some()+ || tree.some_keyframe_filter_of_effect_spreads(effect)+}++/// The filters the keyframes of the filter animations of a tree give the effects they animate, which placing follows+/// along with the filters the tree holds, so that what it decides of a filter holds for every sample.+pub struct KeyframeFiltersOfEffects {+ by_effect_index: HashMap<u32, KeyframeFilters>,+}++#[derive(Default)]+struct KeyframeFilters {+ /// One per keyframe that gives the effect a filter.+ filters: Vec<Vec<u8>>,+ /// Whether a sample can take a value past those of the two keyframes it is between, as an easing that overshoots+ /// does.+ samples_can_pass_keyframes: bool,+}++impl KeyframeFiltersOfEffects {+ pub fn of(tree: &VisualContextTree) -> Self {+ let mut by_effect_index: HashMap<u32, KeyframeFilters> = HashMap::new();+ for animation in tree+ .visual_animations()+ .iter()+ .filter(|animation| animation.target_kind == FfiVisualAnimationTargetKind::Filter)+ {+ let samples_can_pass_keyframes = !easing_stays_within_unit_interval(&animation.easing)+ || animation+ .keyframes+ .iter()+ .any(|keyframe| !easing_stays_within_unit_interval(&keyframe.easing));+ let filters: Vec<Vec<u8>> = animation+ .keyframes+ .iter()+ .filter_map(|keyframe| match &keyframe.value {+ VisualAnimationValue::Filter(functions) => {+ filter_functions_graph(functions.iter().copied().map(Filter::from))+ .map(|graph| graph.serialize())+ }+ _ => None,+ })+ .collect();+ for &effect_index in &animation.node_indices {+ let keyframe_filters = by_effect_index.entry(effect_index).or_default();+ keyframe_filters.filters.extend(filters.iter().cloned());+ keyframe_filters.samples_can_pass_keyframes |= samples_can_pass_keyframes;+ }+ }+ Self { by_effect_index }+ }++ /// Whether the effect's filter can show its content away from where the content is drawn at some sample.+ pub fn filter_may_move_what_it_filters(&self, tree: &VisualContextTree, effect: EffectNodeIndex) -> bool {+ filter_moves_what_it_filters(&tree.effect_nodes[effect.0 as usize])+ || self.by_effect_index.get(&effect.0).is_some_and(|keyframe_filters| {+ keyframe_filters+ .filters+ .iter()+ .any(|filter| filter_bytes::may_move_what_it_filters(filter))+ })+ }++ /// How far past each pixel the effect's filter reads at any sample, in device pixels where `effect_to_device` maps+ /// the space of the effect, or none where that is not known or is farther than tiles are followed.+ pub fn filter_read_reach_in_device_pixels(+ &self,+ tree: &VisualContextTree,+ effect: EffectNodeIndex,+ effect_to_device: &FloatMatrix4x4,+ ) -> Option<i32> {+ let keyframe_filters = self.by_effect_index.get(&effect.0);+ let spreading_keyframe_filters = keyframe_filters+ .into_iter()+ .flat_map(|keyframe_filters| keyframe_filters.filters.iter())+ .map(|filter| &filter[..])+ .filter(|filter| filter_bytes::may_affect_output_bounds(filter));+ if keyframe_filters.is_some_and(|keyframe_filters| keyframe_filters.samples_can_pass_keyframes)+ && spreading_keyframe_filters.clone().next().is_some()+ {+ return None;+ }+ spreading_filter_of(&tree.effect_nodes[effect.0 as usize])+ .into_iter()+ .chain(spreading_keyframe_filters)+ .try_fold(0, |read_reach, filter| {+ Some(read_reach.max(filter_read_reach_in_device_pixels(filter, effect_to_device)?))+ })+ }+}++/// Per effect, the nearest effect at or above it for which `holds` holds, or `EffectNodeIndex::NONE`.+pub(crate) fn nearest_effects_at_or_above_where(+ tree: &VisualContextTree,+ holds: impl Fn(EffectNodeIndex, &EffectNode) -> bool,+) -> Vec<EffectNodeIndex> {let mut nearest = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];tree.visit_effect_nodes_parents_first(|index| {let node = &tree.effect_nodes[index];- let spreads = matches!(&node.data, EffectNodeData::Effects(effects)- if effects.filter.as_deref().is_some_and(|filter| filter_bytes::may_affect_output_bounds(filter)));- nearest[index] = if spreads {+ nearest[index] = if holds(EffectNodeIndex(index as u32), node) {EffectNodeIndex(index as u32)} else if node.parent.is_none() {EffectNodeIndex::NONE@@ -94,32 +269,124 @@ pub fn nearest_spreading_effects(tree: &VisualContextTree) -> Vec<EffectNodeIndenearest}-/// Where a change to content drawn within `rect` in `space` under `effect` can show once every-/// filter above it has spread it, in the space of the outermost of those filters. Changes to-/// separate parts of the content can be followed one at a time and united.+/// Per effect, the effects at and above it whose filters a raster of content under it draws: the nearest of them whose+/// filter spreads its content, and, where any does, the outermost of them that holds a filter or a backdrop filter,+/// whose output clip bounds how far they spread it.+#[derive(Default)]+pub struct FiltersOfEffects {+ nearest_spreading_effect_by_effect_index: Vec<EffectNodeIndex>,+ outermost_effect_with_filter_if_spread_by_effect_index: Vec<EffectNodeIndex>,+}++impl FiltersOfEffects {+ /// With `innermost_composited_effect_by_effect_index`, only the filters inside the innermost composited effect at or+ /// above each effect, which a raster leaves out with the effects around it. With `at_some_sample`, the filters of+ /// every sample of the animations of the tree: a filter that may spread at some sample spreads, and an effect whose+ /// filter an animation animates holds a filter.+ pub fn of(+ tree: &VisualContextTree,+ innermost_composited_effect_by_effect_index: Option<&[EffectNodeIndex]>,+ at_some_sample: bool,+ ) -> Self {+ let effect_count = tree.effect_nodes.len();+ let mut nearest_spreading_effect_by_effect_index = vec![EffectNodeIndex::NONE; effect_count];+ let mut outermost_effect_with_filter_by_effect_index = vec![EffectNodeIndex::NONE; effect_count];+ tree.visit_effect_nodes_parents_first(|index| {+ let node = &tree.effect_nodes[index];+ let effect = EffectNodeIndex(index as u32);+ let innermost_composited_effect = innermost_composited_effect_by_effect_index+ .map_or(EffectNodeIndex::NONE, |innermost_composited_effects| {+ innermost_composited_effects[index]+ });+ if innermost_composited_effect == effect {+ return;+ }+ let parent_is_inside_same_composited_effect =+ !node.parent.is_none() && node.parent != innermost_composited_effect;+ let value_of_parent = |values: &[EffectNodeIndex]| {+ if parent_is_inside_same_composited_effect {+ values[node.parent.0 as usize]+ } else {+ EffectNodeIndex::NONE+ }+ };+ let spreads = if at_some_sample {+ filter_may_spread_at_some_sample(tree, effect)+ } else {+ spreading_filter_of(node).is_some()+ };+ let holds_filter = matches!(&node.data, EffectNodeData::Effects(effects)+ if effects.filter.is_some() || effects.backdrop_filter.is_some())+ || (at_some_sample+ && matches!(node.data, EffectNodeData::Effects(_))+ && tree.effect_filter_is_animated(effect));+ nearest_spreading_effect_by_effect_index[index] = if spreads {+ effect+ } else {+ value_of_parent(&nearest_spreading_effect_by_effect_index)+ };+ let outermost_effect_with_filter_above = value_of_parent(&outermost_effect_with_filter_by_effect_index);+ outermost_effect_with_filter_by_effect_index[index] = if !outermost_effect_with_filter_above.is_none() {+ outermost_effect_with_filter_above+ } else if holds_filter {+ effect+ } else {+ EffectNodeIndex::NONE+ };+ });+ let outermost_effect_with_filter_if_spread_by_effect_index = outermost_effect_with_filter_by_effect_index+ .into_iter()+ .zip(&nearest_spreading_effect_by_effect_index)+ .map(|(outermost, nearest_spreading)| {+ if nearest_spreading.is_none() {+ EffectNodeIndex::NONE+ } else {+ outermost+ }+ })+ .collect();+ Self {+ nearest_spreading_effect_by_effect_index,+ outermost_effect_with_filter_if_spread_by_effect_index,+ }+ }++ pub(crate) fn nearest_spreading_effect_at_or_above(&self, effect: EffectNodeIndex) -> EffectNodeIndex {+ self.nearest_spreading_effect_by_effect_index+ .get(effect.0 as usize)+ .copied()+ .unwrap_or(EffectNodeIndex::NONE)+ }++ /// The effect whose output clip bounds how far the filters at and above `effect` spread its content, if any does.+ pub(crate) fn effect_bounding_spread_of(&self, effect: EffectNodeIndex) -> Option<EffectNodeIndex> {+ self.outermost_effect_with_filter_if_spread_by_effect_index+ .get(effect.0 as usize)+ .copied()+ .filter(|effect| !effect.is_none())+ }+}++/// Where a change to content drawn within `rect` in `space` under `effect` can show once every filter of `filters` above+/// it has spread it, in the space of the outermost of those filters. Changes to separate parts of the content can be+/// followed one at a time and united.pub fn changed_extent_through_filters(tree: &VisualContextTree,- nearest_spreading_effects: &[EffectNodeIndex],+ filters: &FiltersOfEffects,space: SpatialNodeIndex,rect: FloatRect,effect: EffectNodeIndex,world: &WorldTransforms,) -> (SpatialNodeIndex, Extent) {- let nearest_at_or_above = |effect: EffectNodeIndex| {- if effect.is_none() {- EffectNodeIndex::NONE- } else {- nearest_spreading_effects[effect.0 as usize]- }- };let mut space = space;let mut extent = Extent::Within(rect);- let mut effect = nearest_at_or_above(effect);+ let mut effect = filters.nearest_spreading_effect_at_or_above(effect);while !effect.is_none() && extent != Extent::Anywhere {let node = &tree.effect_nodes[effect.0 as usize];- extent = changed_output_extent(node, extent.mapped_between_spaces(world, space, node.spatial));+ extent =+ output_extent_of_content_change(node, extent_mapped_between_spaces(extent, world, space, node.spatial));space = node.spatial;- effect = nearest_at_or_above(node.parent);+ effect = filters.nearest_spreading_effect_at_or_above(node.parent);}(space, extent)}@@ -132,10 +399,9 @@ pub struct EffectGeometry {pub output: Extent,}-/// Fills `geometry` with every effect's geometry, indexed by effect.-pub fn compute_effect_geometry(+pub fn compute_effect_geometry<'a>(tree: &VisualContextTree,- command_runs: &[DisplayListCommandRun],+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun>,world: &WorldTransforms,geometry: &mut Vec<EffectGeometry>,) {@@ -148,36 +414,38 @@ pub fn compute_effect_geometry(},);- // Neighboring runs mostly differ only in their clip, so their ink is united before it is- // mapped into the effect's space.- let mut pending: Option<(DisplayListCommandRun, FloatRect)> = None;- let add_ink = |geometry: &mut Vec<EffectGeometry>, run: &DisplayListCommandRun, ink: FloatRect| {- let node = &tree.effect_nodes[run.context.effect.0 as usize];- let landed = Extent::Within(ink).mapped_between_spaces(world, run.context.spatial, node.spatial);- let content = &mut geometry[run.context.effect.0 as usize].content;- *content = content.united(landed);- };+ let mut ink_of_consecutive_runs_in_one_effect_and_space: Option<(DisplayListCommandRun, FloatRect)> = None;+ let add_ink_to_effect_content =+ |geometry: &mut Vec<EffectGeometry>, run: &DisplayListCommandRun, ink: FloatRect| {+ let node = &tree.effect_nodes[run.context.effect.0 as usize];+ let ink_in_effect_space =+ extent_mapped_between_spaces(Extent::Within(ink), world, run.context.spatial, node.spatial);+ let content = &mut geometry[run.context.effect.0 as usize].content;+ *content = content.united(ink_in_effect_space);+ };for run in command_runs {if run.ink_bounds.is_empty() || run.context.effect.is_none() {continue;}let ink = run.ink_bounds.to_float();- match &mut pending {- Some((pending_run, pending_ink))- if pending_run.context.effect == run.context.effect- && pending_run.context.spatial == run.context.spatial =>+ match &mut ink_of_consecutive_runs_in_one_effect_and_space {+ Some((first_run, united_ink))+ if first_run.context.effect == run.context.effect+ && first_run.context.spatial == run.context.spatial =>{- *pending_ink = pending_ink.united(ink);+ *united_ink = united_ink.united(ink);}_ => {- if let Some((pending_run, pending_ink)) = pending.replace((*run, ink)) {- add_ink(geometry, &pending_run, pending_ink);+ if let Some((first_run, united_ink)) =+ ink_of_consecutive_runs_in_one_effect_and_space.replace((*run, ink))+ {+ add_ink_to_effect_content(geometry, &first_run, united_ink);}}}}- if let Some((pending_run, pending_ink)) = pending {- add_ink(geometry, &pending_run, pending_ink);+ if let Some((first_run, united_ink)) = ink_of_consecutive_runs_in_one_effect_and_space {+ add_ink_to_effect_content(geometry, &first_run, united_ink);}let mut effects_parents_first = Vec::with_capacity(tree.effect_nodes.len());@@ -190,9 +458,9 @@ pub fn compute_effect_geometry(continue;}let parent_spatial = tree.effect_nodes[node.parent.0 as usize].spatial;- let landed = output.mapped_between_spaces(world, node.spatial, parent_spatial);+ let output_in_parent_space = extent_mapped_between_spaces(output, world, node.spatial, parent_spatial);let parent_content = &mut geometry[node.parent.0 as usize].content;- *parent_content = parent_content.united(landed);+ *parent_content = parent_content.united(output_in_parent_space);}}@@ -372,17 +640,20 @@ mod tests {scaled,);let plain = effect(&mut tree, None, EffectNodeIndex::NONE, VISUAL_VIEWPORT_NODE_INDEX);- let nearest = nearest_spreading_effects(&tree);- assert_eq!(nearest[opacity.0 as usize], blur);- assert_eq!(nearest[plain.0 as usize], EffectNodeIndex::NONE);+ let filters = FiltersOfEffects::of(&tree, None, false);+ assert_eq!(filters.nearest_spreading_effect_at_or_above(opacity), blur);+ assert_eq!(+ filters.nearest_spreading_effect_at_or_above(plain),+ EffectNodeIndex::NONE+ );let content = FloatRect::new(10.0, 20.0, 30.0, 40.0);let world = WorldTransforms::new(&tree, &[], Some(FloatMatrix4x4::identity()));assert_eq!(- changed_extent_through_filters(&tree, &nearest, scaled, content, shadow, &world),+ changed_extent_through_filters(&tree, &filters, scaled, content, shadow, &world),(VISUAL_VIEWPORT_NODE_INDEX, within(-10.0, 10.0, 120.0, 160.0)));assert_eq!(- changed_extent_through_filters(&tree, &nearest, scaled, content, plain, &world),+ changed_extent_through_filters(&tree, &filters, scaled, content, plain, &world),(scaled, Extent::Within(content)));}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers.rs b/Libraries/LibCompositing/Rust/src/display_list/layers.rsindex 609e477b544..e4e77156fca 100644--- a/Libraries/LibCompositing/Rust/src/display_list/layers.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/layers.rs@@ -4,45 +4,62 @@* SPDX-License-Identifier: BSD-2-Clause*/-use crate::display_list::builder::{- HEADER_SIZE, bounding_rect_computed_from_payload, for_each_command, read_command, read_header,+//! The layers a display list is painted in, bottom to top: the stack, what the compositor and tile keying read of it,+//! and its wire form.+//!+//! Content is rastered in the space of the scroll node, sticky box or node whose transform the compositor animates+//! that it moves with, and its raster is composited within the clips it leaves to apply then (its composite clips), and+//! inside the effects the compositor applies to it: content of one space, one set of composite clips and at most one+//! composited effect makes a placement node. The records of a node are cut into bands. Within a band, a canvas, video+//! or nested context that is a layer of its own, and each band of a node nested in it, sits between the band's records+//! as a barrier. A barrier cuts the band's tiles that it can show in, or for an effect that reads what is composited+//! below it, that it reads, at its paint position: there, the band's records painted before the barrier go into the+//! layer below the cut and those painted after it into the layer above the cut. Elsewhere it cuts nothing.++use crate::display_list::commands::{EffectNodeIndex, SpatialNodeIndex};+use crate::display_list::effect_geometry::{+ LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS, filter_may_spread_at_some_sample,};-use crate::display_list::commands::{- ClipMode, ClipNodeIndex, DeclareMaskContent, DisplayListCommandRun, DisplayListCommandType, EffectNodeIndex,+pub use crate::display_list::placement::{+ CompositeClip, RasterSpace, RasterSpaceAnchorKind, RasterSpaceIndex, RunGroupIndex, raster_space_anchors,};-use crate::display_list::effect_clip_plan::EffectClipPlan;-use crate::display_list::effect_geometry::{Extent, compute_effect_geometry};-use crate::display_list::summary::{DisplayListSummary, IndexedRecord, LiveContent};-use crate::display_list::window_server_placement::{- WindowServerPlacement, WindowServerRejection, window_server_placement,+use crate::display_list::placement::{+ EXTENT_LIMIT_IN_DEVICE_PIXELS, enclosing_int_rect_within_extent_limit, space_and_ancestors_below_viewport,+ spatial_nodes_that_move_on_their_own,};-use crate::host::RecordSpan;-use crate::visual_context::queries::TreeCullingScratch;-use crate::visual_context::{ClipNodeData, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms};-use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect, enclosing_int_rect};+use crate::display_list::reach::Reach;+use crate::display_list::storage::{DisplayListStorage, ListPosition, ListSpan};+use crate::display_list::summary::LiveContent;+use crate::display_list::window_server_placement::{WhyWindowServerCannotShowMedia, WindowServerPlacement};+use crate::visual_context::queries::{NestingOfLiveEffects, backdrop_reader_by_reading_effect_index};+use crate::visual_context::{VisualContextTree, WorldTransforms, device_offset_for_index};+use libgfx_rust::{AffineTransform, CornerRadii, FloatMatrix4x4, FloatPoint, IntPoint, IntRect};+use std::hash::{BuildHasher, Hash, Hasher};+use std::rc::Rc;++pub mod planning;+mod wire;++pub use wire::{LayerPlan, UnvalidatedLayerPlan, compositor_takes_plans_within};++// Twice the extent limit of a plan, which leaves room for the margins that planning adds past the extent of a space.+// The rects of a stack from another process are within it, and so are the offsets a frame composites spaces at, so that+// a rect offset by such an offset still fits in an `IntRect`.+const COORDINATE_LIMIT_IN_DEVICE_PIXELS: i32 = 2 * EXTENT_LIMIT_IN_DEVICE_PIXELS as i32;pub const MAXIMUM_MEDIA_LAYER_COUNT: usize = 8;-const BOUNDS_MARGIN_IN_DEVICE_PIXELS: i32 = 3;-const MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS: i64 = 2;-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum LayerKind {- Base,- Painted,- Media { content: LiveContent },-}+/// The most composited effects that nest around a layer of a plan: the effects a frame composites the layer inside,+/// each inside the next. Pages nest far fewer, as the compositor composites only an effect that it animates, or one+/// around a layer of its own, such as of a scroller, a sticky box or a canvas.+pub const MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS: usize = 32;-impl std::fmt::Display for LayerKind {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- LayerKind::Base => formatter.write_str("base"),- LayerKind::Painted => formatter.write_str("painted"),- LayerKind::Media { content } => formatter.write_str(media_name(*content)),- }- }-}+/// The farthest that the filters of the effects a frame composites around a layer read past each pixel of it, summed, in+/// device pixels. A frame keys the tiles of a layer that far past what it shows, and a larger sum is cut to this.+pub const LARGEST_SUMMED_READ_REACH_OF_COMPOSITED_FILTERS_IN_DEVICE_PIXELS: i32 =+ 4 * LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS as i32;-fn media_name(content: LiveContent) -> &'static str {+pub(crate) fn media_name(content: LiveContent) -> &'static str {match content {LiveContent::Canvas(_) => "canvas",LiveContent::VideoFrame(_) => "video",@@ -51,1835 +68,1329 @@ fn media_name(content: LiveContent) -> &'static str {}}+/// Why the compositor cannot composite an effect, which keeps what it holds from having layers of its own.#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum MediaLayerRejection {- DrawnInsideAnotherCommand,- InsideGroupEffect,- UnderTransformThatIsNot2DAffine,- DrawsNothingVisible,- BetweenRunsOfOneGroupEffect,- UnderBackdropFilterReadingRootGroup,+pub enum WhyCompositorCannotCompositeEffect {+ FilterMovesWhatItFilters,+ FilterReadsFartherThanTilesAreFollowed,}-impl std::fmt::Display for MediaLayerRejection {+impl std::fmt::Display for WhyCompositorCannotCompositeEffect {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter.write_str(match self {- MediaLayerRejection::DrawnInsideAnotherCommand => "drawn inside another command",- MediaLayerRejection::InsideGroupEffect => "inside a group effect",- MediaLayerRejection::UnderTransformThatIsNot2DAffine => "under a transform that is not 2D affine",- MediaLayerRejection::DrawsNothingVisible => "draws nothing visible",- MediaLayerRejection::BetweenRunsOfOneGroupEffect => "between the runs of one group effect",- MediaLayerRejection::UnderBackdropFilterReadingRootGroup => {- "under a backdrop filter that reads the root group"+ WhyCompositorCannotCompositeEffect::FilterMovesWhatItFilters => "filter that moves what it filters",+ WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed => {+ "filter that reads farther than tiles are followed"}})}}+/// Why a list is painted in a single layer that replays all of it.#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum UnlayeredReason {- NoMedia,+pub enum WhyListIsOneLayer {EmptyViewport,EmptyDisplayList,SortingContext3D,RootIsolationEffectIsNotPlainGroup,- BlendModeReadsRootGroup,- CommandBlendsWithRootGroup,- MaskDeclaredOutsideItsMask,- NoMediaCanBeLayer {- first_rejected_media: LiveContent,- rejection: MediaLayerRejection,- },- UpperPaintedLayersTooLarge,+ MaskDeclaredUnderEffectsItsMaskIsNotUnder,+ RecordsBlendWithWhatOtherLayersHoldBelowThem,+ EffectTheCompositorCannotCompositeIsComposited(WhyCompositorCannotCompositeEffect),+ CompositedEffectsNestTooDeep,+ PlanHoldsMoreThanCompositorDecodes,+ /// The frame draws the list otherwise than a plan of its layers is made for, as through a raster transform or a+ /// visual viewport transform the plan does not know.+ FrameIsNotDrawnAsPlanned,+ /// A frame drawn as the plan was made for shows more tiles than the compositor holds for a frame.+ PlanShowsTooManyTiles,+ /// The plan the planner made fails the checks the compositor runs on a plan it receives.+ PlanFailsChecksOfCompositor,}-impl std::fmt::Display for UnlayeredReason {+impl std::fmt::Display for WhyListIsOneLayer {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let text = match self {- UnlayeredReason::NoMediaCanBeLayer {- first_rejected_media,- rejection,- } => return write!(formatter, "{} {rejection}", media_name(*first_rejected_media)),- UnlayeredReason::UpperPaintedLayersTooLarge => {+ formatter.write_str(match self {+ WhyListIsOneLayer::EmptyViewport => "empty viewport",+ WhyListIsOneLayer::EmptyDisplayList => "empty display list",+ WhyListIsOneLayer::SortingContext3D => "3D sorting context holding an effect that reads or is composited",+ WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup => "root isolation effect is not a plain group",+ WhyListIsOneLayer::MaskDeclaredUnderEffectsItsMaskIsNotUnder => {+ "mask content declared under effects its mask is not under"+ }+ WhyListIsOneLayer::RecordsBlendWithWhatOtherLayersHoldBelowThem => {+ "records blend with what other layers hold below them"+ }+ WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(why) => {+ return write!(formatter, "{why} is composited");+ }+ WhyListIsOneLayer::CompositedEffectsNestTooDeep => {return write!(formatter,- "painted layers larger than {MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS} viewports"+ "composited effects nest deeper than {MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS}");}- UnlayeredReason::NoMedia => "no canvas, video or nested context is drawn",- UnlayeredReason::EmptyViewport => "empty viewport",- UnlayeredReason::EmptyDisplayList => "empty display list",- UnlayeredReason::SortingContext3D => "3D sorting context",- UnlayeredReason::RootIsolationEffectIsNotPlainGroup => "root isolation effect is not a plain group",- UnlayeredReason::BlendModeReadsRootGroup => "blend mode reads the root group",- UnlayeredReason::CommandBlendsWithRootGroup => "command blends with the root group",- UnlayeredReason::MaskDeclaredOutsideItsMask => "mask content declared outside its mask",- };- formatter.write_str(text)+ WhyListIsOneLayer::PlanHoldsMoreThanCompositorDecodes => {+ "plan holds more nodes, bands, cuts or spans than the compositor decodes"+ }+ WhyListIsOneLayer::FrameIsNotDrawnAsPlanned => "frame is not drawn as the plan was made for",+ WhyListIsOneLayer::PlanShowsTooManyTiles => "plan shows more tiles than a frame holds",+ WhyListIsOneLayer::PlanFailsChecksOfCompositor => "plan fails the checks of the compositor",+ })}}-#[derive(Clone, Debug, PartialEq)]-pub struct Layer {- pub kind: LayerKind,- pub rect: IntRect,- pub record_spans: Vec<RecordSpan>,- /// For a canvas or video layer, where the window server can show its content by itself, or why it cannot.- pub window_server_placement: Option<Result<WindowServerPlacement, WindowServerRejection>>,-}--// The records from `begin_offset` up to the next range's start are drawn into the layer at `layer`.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-struct LayerRecordRange {- begin_offset: u32,- layer: u8,-}--#[derive(Clone, Debug, PartialEq)]-pub struct LayerPlan {- pub layers: Vec<Layer>,- record_ranges_in_tape_order: Vec<LayerRecordRange>,+/// How the lines that describe a stack name the visual context nodes they mention.+pub trait VisualContextNodeNamer {+ fn name_of_spatial_node(&self, index: SpatialNodeIndex) -> String;+ fn name_of_effect_node(&self, index: EffectNodeIndex) -> String;}-impl LayerPlan {- pub fn media_record_offsets(&self) -> impl Iterator<Item = u32> + '_ {- self.layers.iter().filter_map(|layer| match layer.kind {- LayerKind::Media { .. } => Some(layer.record_spans[0].begin_offset),- _ => None,- })- }-- /// Whether the plan has the same layers as `other` in the same order, so that a raster kept for a layer of one- /// plan holds the content of the same layer of the other plan wherever no damage says otherwise.- pub fn has_same_layers_as(&self, other: &LayerPlan) -> bool {- self.layers.len() == other.layers.len()- && self- .layers- .iter()- .zip(&other.layers)- .all(|(layer, other_layer)| layer.kind == other_layer.kind)- }+/// Names visual context nodes by their indices in the tree.+pub struct NodeNamesFromIndices;- /// One line per layer, bottom to top: `[L<index>] <kind> rect=[<x>,<y> <width>x<height>]` after `indent`, with the- /// records the layer draws where `describe_records` describes them.- pub fn write_layer_lines(- &self,- output: &mut impl std::fmt::Write,- indent: &str,- describe_records: impl Fn(&[RecordSpan]) -> Option<String>,- ) -> std::fmt::Result {- for (index, layer) in self.layers.iter().enumerate() {- let rect = layer.rect;- write!(- output,- "{indent}[L{index}] {} rect=[{},{} {}x{}]",- layer.kind, rect.x, rect.y, rect.width, rect.height- )?;- if let Some(records) = describe_records(&layer.record_spans) {- write!(output, " records={records}")?;- }- match &layer.window_server_placement {- Some(Ok(placement)) => writeln!(output, " shown by the window server: {placement}")?,- Some(Err(rejection)) => writeln!(output, " replayed: {rejection}")?,- None => writeln!(output)?,- }- }- Ok(())+impl VisualContextNodeNamer for NodeNamesFromIndices {+ fn name_of_spatial_node(&self, index: SpatialNodeIndex) -> String {+ format!("s{}", index.0)}- pub fn layer_of_record(&self, record_offset: u32) -> usize {- let range_index = self- .record_ranges_in_tape_order- .partition_point(|range| range.begin_offset <= record_offset)- .saturating_sub(1);- self.record_ranges_in_tape_order[range_index].layer as usize- }-- pub fn layers_drawing_records_of(&self, run: &DisplayListCommandRun) -> impl Iterator<Item = usize> + '_ {- self.layers_of_records_in(run).map(|(_, layer)| usize::from(layer))- }-- pub fn places_records_like(&self, other: &LayerPlan) -> bool {- self.record_ranges_in_tape_order == other.record_ranges_in_tape_order- }-- /// Whether the records of `run` go into the same layers as those of `other_run`, an identical run of the list- /// that `other` plans, at the same offsets in the run.- pub fn places_run_like(- &self,- run: &DisplayListCommandRun,- other: &LayerPlan,- other_run: &DisplayListCommandRun,- ) -> bool {- self.layers_of_records_in(run).eq(other.layers_of_records_in(other_run))+ fn name_of_effect_node(&self, index: EffectNodeIndex) -> String {+ format!("e{}", index.0)}+}- // Where in the run the records of each layer start, as offsets in the run.- fn layers_of_records_in(&self, run: &DisplayListCommandRun) -> impl Iterator<Item = (u32, u8)> + '_ {- let first_range_index = self- .record_ranges_in_tape_order- .partition_point(|range| range.begin_offset <= run.offset)- .saturating_sub(1);- let (run_offset, run_end) = (run.offset, run.offset + run.size);- std::iter::once((0, self.record_ranges_in_tape_order[first_range_index].layer)).chain(- self.record_ranges_in_tape_order[first_range_index + 1..]- .iter()- .take_while(move |range| range.begin_offset < run_end)- .map(move |range| (range.begin_offset - run_offset, range.layer)),- )- }+/// Names a placement node by the identity of its space, the clips its rasters are composited within, and the effects+/// they are composited inside, which outlive the tree and the list.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct PlacementNodeIdentity(pub u64);++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum BarrierIdentity {+ /// The `ordinal`th drawing of a canvas, video or nested context in paint order.+ Media { content: LiveContent, ordinal: u32 },+ /// The `band_ordinal_in_node`th band of content of a node, counted over the whole list.+ NestedNodeBand {+ node: PlacementNodeIdentity,+ band_ordinal_in_node: u32,+ },}-pub struct LayerPlanInputs<'a> {- pub tape: &'a [u8],- pub command_runs: &'a [DisplayListCommandRun],- pub summary: &'a DisplayListSummary,- pub effect_clips: &'a EffectClipPlan,- pub tree: &'a VisualContextTree,- pub scroll_offsets: &'a [FloatPoint],- pub viewport_rect: IntRect,+/// Names a layer from one list to the next, so that its tiles outlive both.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum LayerIdentity {+ Painted {+ node: PlacementNodeIdentity,+ band_ordinal_in_node: u32,+ above_barrier: Option<BarrierIdentity>,+ },+ Media {+ content: LiveContent,+ ordinal: u32,+ },}-fn tree_has_sorting_contexts(tree: &VisualContextTree) -> bool {- tree.spatial_nodes.iter().any(|node| {- matches!(&node.data, SpatialData::Transform(transform) if transform.sorting_context_root_index.is_some())- })+/// How the frame composites the rasters of a space.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum SpaceToFrame {+ /// Translated by whole device pixels.+ Offset(IntPoint),+ /// Through a transform from the space's raster pixels to the frame's, for a space whose anchor the compositor+ /// animates.+ Transform(AffineTransform),}-fn root_isolation_effect_is_plain_group(tree: &VisualContextTree) -> bool {- let Some(root) = tree.root_isolation_effect else {- return true;- };- match &tree.effect_nodes[root.0 as usize].data {- EffectNodeData::Effects(effects) => {- effects.opacity == 1.0- && effects.blend_mode == libgfx_rust::CompositingAndBlendingOperator::Normal- && effects.filter.is_none()- && effects.backdrop_filter.is_none()+impl Eq for SpaceToFrame {}++// A rect that a transform maps past the extent limit shows nothing there, and is kept within the limit so that the+// arithmetic of the rect does not overflow.+impl SpaceToFrame {+ /// The frame's pixels that `rect_in_space` covers, or the bounds of them.+ pub fn rect_in_frame(self, rect_in_space: IntRect) -> IntRect {+ match self {+ SpaceToFrame::Offset(offset) => rect_in_space.translated(offset.x, offset.y),+ SpaceToFrame::Transform(_) if rect_in_space.is_empty() => IntRect::default(),+ SpaceToFrame::Transform(transform) => transform_and_inverse_that_show_space(transform)+ .map_or(IntRect::default(), |(transform, _)| {+ enclosing_int_rect_within_extent_limit(transform.map_rect(rect_in_space.to_float()))+ }),}- _ => false,}-}-fn effect_chain_contains(tree: &VisualContextTree, mut effect: EffectNodeIndex, wanted: EffectNodeIndex) -> bool {- while !effect.is_none() {- if effect == wanted {- return true;+ /// The space's pixels that `rect_in_frame` covers, or the bounds of them.+ pub fn rect_in_space(self, rect_in_frame: IntRect) -> IntRect {+ match self {+ SpaceToFrame::Offset(offset) => rect_in_frame.translated(-offset.x, -offset.y),+ SpaceToFrame::Transform(_) if rect_in_frame.is_empty() => IntRect::default(),+ SpaceToFrame::Transform(transform) => transform_and_inverse_that_show_space(transform)+ .map_or(IntRect::default(), |(_, inverse)| {+ enclosing_int_rect_within_extent_limit(inverse.map_rect(rect_in_frame.to_float()))+ }),}- effect = tree.effect_nodes[effect.0 as usize].parent;}- false}-fn what_reads_root_group(inputs: &LayerPlanInputs<'_>) -> Option<UnlayeredReason> {- if inputs.tree.has_blend_mode_reading_root_group() {- return Some(UnlayeredReason::BlendModeReadsRootGroup);- }- let command_blends_with_root_group = inputs.summary.destination_blending_records.iter().any(|record| {- let effect = inputs.command_runs[record.run_index as usize].context.effect;- inputs.tree.content_under_effect_composites_into_root_group(effect)- });- command_blends_with_root_group.then_some(UnlayeredReason::CommandBlendsWithRootGroup)+/// A transform of a space and its inverse, or none for a transform that shows nothing of the space: one with a value+/// that is not finite, or one without an inverse of finite values.+fn transform_and_inverse_that_show_space(transform: AffineTransform) -> Option<(AffineTransform, AffineTransform)> {+ let is_finite = |transform: AffineTransform| transform.values.iter().all(|value| value.is_finite());+ let inverse = transform.inverse()?;+ (is_finite(transform) && is_finite(inverse)).then_some((transform, inverse))}-fn mask_declarations_sit_under_their_masks(inputs: &LayerPlanInputs<'_>) -> bool {- inputs.summary.mask_declarations.iter().all(|record| {- let offset = record.record_offset as usize;- let header = read_header(&inputs.tape[offset..]);- let payload = &inputs.tape[offset + HEADER_SIZE..offset + HEADER_SIZE + header.payload_size as usize];- let declaration = read_command::<DeclareMaskContent>(payload);- let run_effect = inputs.command_runs[record.run_index as usize].context.effect;- effect_chain_contains(inputs.tree, run_effect, declaration.effect)- })-}+/// The index of a node in `LayerStack::nodes`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct PlacementNodeIndex(pub usize);-// The structure decides the grouping effect rather than the effect values, so chunks stay put while an opacity animates.-fn outermost_grouping_effects(tree: &VisualContextTree) -> Vec<EffectNodeIndex> {- let mut outermost = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];- tree.visit_effect_nodes_parents_first(|index| {- let node = &tree.effect_nodes[index];- let from_parent = if node.parent.is_none() {- EffectNodeIndex::NONE- } else {- outermost[node.parent.0 as usize]- };- let is_grouping = node.data.pushes_layer() && tree.root_isolation_effect != Some(EffectNodeIndex(index as u32));- outermost[index] = if !from_parent.is_none() {- from_parent- } else if is_grouping {- EffectNodeIndex(index as u32)- } else {- EffectNodeIndex::NONE- };- });- outermost-}+/// The index of a band in `LayerStack::bands`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct BandIndex(pub usize);-// A chain holds at most one such effect, since the layer of its backdrop filter isolates every effect under it.-fn backdrop_filter_reading_root_group_on_chain(tree: &VisualContextTree) -> Vec<EffectNodeIndex> {- let mut on_chain = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];- tree.visit_effect_nodes_parents_first(|index| {- let node = &tree.effect_nodes[index];- let effect = EffectNodeIndex(index as u32);- let own = matches!(&node.data, EffectNodeData::Effects(effects) if effects.backdrop_filter.is_some())- && tree.effect_backdrop_is_root_group(effect);- on_chain[index] = if own {- effect- } else if node.parent.is_none() {- EffectNodeIndex::NONE- } else {- on_chain[node.parent.0 as usize]- };- });- on_chain-}+/// The index of a layer in `LayerStack::layers`, bottom to top.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct LayerIndex(pub usize);-fn clip_chain_bounds(tree: &VisualContextTree, world: &WorldTransforms) -> Vec<Option<FloatRect>> {- let mut bounds: Vec<Option<FloatRect>> = vec![None; tree.clip_nodes.len()];- tree.visit_clip_nodes_parents_first(|index| {- let node = &tree.clip_nodes[index];- let own = match &node.data {- ClipNodeData::Rect(data) if data.mode == ClipMode::Intersect => Some(data.rect),- ClipNodeData::Path(path) => Some(path.bounding_rect.to_float()),- _ => None,- }- .map(|rect| world.map_rect_to_root(node.spatial, rect))- .filter(|rect| rect.x.is_finite() && rect.y.is_finite() && rect.width.is_finite() && rect.height.is_finite());- let from_parent = if node.parent.is_none() {- None- } else {- bounds[node.parent.0 as usize]- };- bounds[index] = match (own, from_parent) {- (Some(own), Some(from_parent)) => Some(own.intersected(from_parent)),- (own, from_parent) => own.or(from_parent),- };- });- bounds+/// Content rastered in one space, composited within one set of clips, and inside at most one effect that the+/// compositor applies, which a replay of the list would apply around it.+#[derive(Clone, Debug, PartialEq)]+pub struct PlacementNode {+ pub identity: PlacementNodeIdentity,+ pub raster_space_index: RasterSpaceIndex,+ /// At most one per space, ordered by space.+ pub composite_clips: Vec<CompositeClip>,+ /// The effect the compositor composites the rasters of the node inside, within those it composites the parent+ /// node inside. The rasters leave it out, with the effects around it and the clips it is entered within.+ pub composited_effect: Option<EffectNodeIndex>,+ pub parent_index: Option<PlacementNodeIndex>,+ /// Where content of the node and of the nodes in it can show, or a composited effect read.+ pub reach_in_parent_node: Reach<IntRect>,}-struct BoundsContext<'a> {- world: WorldTransforms,- culling: TreeCullingScratch,- clip_bounds: Vec<Option<FloatRect>>,- viewport_rect: IntRect,- tree: &'a VisualContextTree,+/// Where a barrier cuts the tiles of a band.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct BarrierCut {+ pub barrier_first_record_position: ListPosition,+ /// The barrier cuts the tiles of the band's space this reaches.+ pub cut_reach: Reach<IntRect>,+ pub layer_above_cut: LayerIndex,}-impl BoundsContext<'_> {- fn device_rect(&self, rect: Option<FloatRect>, clip: ClipNodeIndex) -> IntRect {- let clip_bounds = if clip.is_none() {- None- } else {- self.clip_bounds[clip.0 as usize]- };- let rect = match (rect, clip_bounds) {- (Some(rect), Some(clip_bounds)) => rect.intersected(clip_bounds),- (Some(rect), None) => rect,- (None, Some(clip_bounds)) => clip_bounds,- (None, None) => return self.viewport_rect,- };- if !(rect.x.is_finite() && rect.y.is_finite() && rect.width.is_finite() && rect.height.is_finite()) {- return self.viewport_rect;- }- if rect.is_empty() {- return IntRect::default();- }- let viewport = self.viewport_rect.to_float();- let rect = rect.intersected(viewport.inflated(- 2.0 * BOUNDS_MARGIN_IN_DEVICE_PIXELS as f32,- 2.0 * BOUNDS_MARGIN_IN_DEVICE_PIXELS as f32,- ));- if rect.is_empty() {- return IntRect::default();- }- enclosing_int_rect(rect)- .inflated_edges(- BOUNDS_MARGIN_IN_DEVICE_PIXELS,- BOUNDS_MARGIN_IN_DEVICE_PIXELS,- BOUNDS_MARGIN_IN_DEVICE_PIXELS,- BOUNDS_MARGIN_IN_DEVICE_PIXELS,- )- .intersected(self.viewport_rect)- }-- fn ink_device_rect(&self, run: &DisplayListCommandRun, ink: IntRect) -> IntRect {- if ink.is_empty()- || self.world.backface_culled[run.context.spatial.0 as usize]- || self.culling.context_culls_everything(run.context)- {- return IntRect::default();- }- let rect = self.world.map_rect_to_root(run.context.spatial, ink.to_float());- self.device_rect(Some(rect), run.context.clip)- }-- fn backdrop_filter_reads_device_rect(&self, effect: EffectNodeIndex, rect: IntRect) -> bool {- let node = &self.tree.effect_nodes[effect.0 as usize];- let EffectNodeData::Effects(effects) = &node.data else {- return false;- };- let Some(backdrop_filter) = &effects.backdrop_filter else {- return false;- };- if rect.is_empty() {- return false;- }- let to_device = self.world.draw_matrix(node.spatial);- if !to_device.is_2d_affine() {- return true;- }- let Some(from_device) = to_device.extract_2d_affine().inverse() else {- return true;- };- let rect_in_effect_space = from_device.map_rect(rect.to_float());- crate::filter_bytes::changed_output_bounds(&backdrop_filter.filter, rect_in_effect_space)- .is_none_or(|reached| !reached.intersected(backdrop_filter.region.to_float()).is_empty())- }-- fn group_device_rect(&self, effect: EffectNodeIndex, output: Extent, effect_clips: &EffectClipPlan) -> IntRect {- let node = &self.tree.effect_nodes[effect.0 as usize];- let output_clip = effect_clips.output_clip(effect);- match output {- Extent::Nothing => IntRect::default(),- Extent::Within(rect) => {- self.device_rect(Some(self.world.map_rect_to_root(node.spatial, rect)), output_clip)- }- Extent::Anywhere => self.device_rect(None, output_clip),- }+impl BarrierCut {+ pub fn cuts_cell(&self, cell: IntRect) -> bool {+ self.cut_reach.touches(cell)}}-// Bit `n` stands for the media layer of the `n`th canvas or video that the plan tries to give a layer.-type MediaLayerSet = u32;-const _: () = assert!(MAXIMUM_MEDIA_LAYER_COUNT <= MediaLayerSet::BITS as usize);--// The media layers that a backdrop filter reading the root group would read through, so that dropping them lets-// the backdrop filter go into the base layer.-struct MediaLayersUnderBackdropFilter(MediaLayerSet);--struct LayersBeingPlanned {- layers: Vec<Layer>,- // A media layer exists for itself, and a painted layer for the media layers that its content is drawn over.- media_layers_each_layer_exists_for: Vec<MediaLayerSet>,- record_ranges_in_tape_order: Vec<LayerRecordRange>,+/// One band of a placement node: the records placed in the node while the band lasts, and the barriers that cut them.+#[derive(Clone, Debug, PartialEq)]+pub struct PlacementNodeBand {+ pub placement_node_index: PlacementNodeIndex,+ pub band_ordinal_in_node: u32,+ pub parent_band_holding_this_band_as_barrier: Option<BandIndex>,+ /// In paint order.+ pub record_spans: Vec<ListSpan>,+ /// In paint order.+ pub cuts: Vec<BarrierCut>,+ pub layer_below_all_cuts: LayerIndex,}-impl LayersBeingPlanned {- const BASE_LAYER_INDEX: usize = 0;+/// The barriers of a band that cut the tile at one cell, in paint order, worked out once for the cell. A band of a+/// received stack can have too many barriers to look through for each record of the cell.+pub struct CutsOfCell<'a> {+ band: &'a PlacementNodeBand,+ cut_indices: Vec<u32>,+}- fn new(viewport_rect: IntRect) -> Self {+impl<'a> CutsOfCell<'a> {+ pub fn of(band: &'a PlacementNodeBand, cell: IntRect) -> Self {Self {- layers: vec![Layer {- kind: LayerKind::Base,- rect: viewport_rect,- record_spans: Vec::new(),- window_server_placement: None,- }],- media_layers_each_layer_exists_for: vec![0],- record_ranges_in_tape_order: Vec::new(),+ band,+ cut_indices: (0..band.cuts.len() as u32)+ .filter(|&cut_index| band.cuts[cut_index as usize].cuts_cell(cell))+ .collect(),}}- fn media_layers_that_layers_above_base_exist_for(&self, touches_layer: impl Fn(&Layer) -> bool) -> MediaLayerSet {- (Self::BASE_LAYER_INDEX + 1..self.layers.len())- .filter(|&index| touches_layer(&self.layers[index]))- .fold(0, |media_layers, index| {- media_layers | self.media_layers_each_layer_exists_for[index]- })- }-- // A backdrop filter reading the root group reads the base layer, so its content has to go there, clear of the- // layers above it both where it draws and where it reads.- fn check_backdrop_filters_can_go_into_base_layer(- &self,- bounds: IntRect,- backdrop_filter_reads_layer: impl Fn(&Layer) -> bool,- ) -> Result<(), MediaLayersUnderBackdropFilter> {- let media_layers = self.media_layers_that_layers_above_base_exist_for(|layer| {- !layer.rect.intersected(bounds).is_empty() || backdrop_filter_reads_layer(layer)- });- if media_layers == 0 {- return Ok(());- }- Err(MediaLayersUnderBackdropFilter(media_layers))- }-- fn topmost_layer_above_base_touching(&self, bounds: IntRect) -> Option<usize> {- if bounds.is_empty() {- return None;- }- (Self::BASE_LAYER_INDEX + 1..self.layers.len())- .rev()- .find(|&index| !self.layers[index].rect.intersected(bounds).is_empty())+ /// The barriers that cut the tile, in paint order.+ pub fn cuts(&self) -> impl Iterator<Item = &'a BarrierCut> + '_ {+ let band = self.band;+ self.cut_indices+ .iter()+ .map(move |&cut_index| &band.cuts[cut_index as usize])}- fn add_media_layer(- &mut self,- media_index: usize,- content: LiveContent,- span: RecordSpan,- bounds: IntRect,- window_server_placement: Option<Result<WindowServerPlacement, WindowServerRejection>>,- ) {- self.layers.push(Layer {- kind: LayerKind::Media { content },- rect: bounds,- record_spans: Vec::new(),- window_server_placement,+ /// The layer the band's record at `record_position` goes into within the tile: the one above the last barrier+ /// painted before it that cuts the tile. Answers too how many of the barriers that cut the tile are below it.+ pub fn layer_of_record(&self, record_position: ListPosition) -> (LayerIndex, usize) {+ // The cuts of a band are in paint order.+ let count_of_cuts_below = self.cut_indices.partition_point(|&cut_index| {+ self.band.cuts[cut_index as usize].barrier_first_record_position <= record_position});- self.media_layers_each_layer_exists_for.push(1 << media_index);- self.append_records_to_layer(self.layers.len() - 1, span);- }-- // Records drawn within `bounds` go into the lowest painted layer that is above every layer they touch, or into- // the base layer when they touch none above it.- fn place_painted_records(&mut self, span: RecordSpan, bounds: IntRect) -> usize {- let layer_index = match self.topmost_layer_above_base_touching(bounds) {- None => Self::BASE_LAYER_INDEX,- Some(touched) => {- let layer_index = (touched..self.layers.len())- .find(|&index| self.layers[index].kind == LayerKind::Painted)- .unwrap_or_else(|| {- self.layers.push(Layer {- kind: LayerKind::Painted,- rect: IntRect::default(),- record_spans: Vec::new(),- window_server_placement: None,- });- self.media_layers_each_layer_exists_for.push(0);- self.layers.len() - 1- });- self.media_layers_each_layer_exists_for[layer_index] |= self- .media_layers_that_layers_above_base_exist_for(|layer| !layer.rect.intersected(bounds).is_empty());- self.layers[layer_index].rect = self.layers[layer_index].rect.united(bounds);- layer_index- }+ let layer = match count_of_cuts_below {+ 0 => self.band.layer_below_all_cuts,+ count => self.band.cuts[self.cut_indices[count - 1] as usize].layer_above_cut,};- self.append_records_to_layer(layer_index, span);- layer_index+ (layer, count_of_cuts_below)}- fn append_records_to_layer(&mut self, layer_index: usize, span: RecordSpan) {- let spans = &mut self.layers[layer_index].record_spans;- match spans.last_mut() {- Some(last) if last.end_offset == span.begin_offset => last.end_offset = span.end_offset,- _ => spans.push(span),- }- if self- .record_ranges_in_tape_order- .last()- .is_none_or(|range| range.layer as usize != layer_index)- {- self.record_ranges_in_tape_order.push(LayerRecordRange {- begin_offset: span.begin_offset,- layer: layer_index as u8,- });+ /// Which barriers cut the tile: tiles that answer alike place every record alike.+ pub fn barrier_cuts(&self) -> BarrierCutsOfCell {+ if self.band.cuts.len() <= u64::BITS as usize {+ BarrierCutsOfCell::BitPerCut(+ self.cut_indices+ .iter()+ .fold(0, |bits, &cut_index| bits | (1u64 << cut_index)),+ )+ } else {+ BarrierCutsOfCell::CutIndices(self.cut_indices.as_slice().into())}}}-struct MediaCandidate {- content: LiveContent,- run_index: u32,- record_offset: u32,+/// Which barriers of a band cut a tile.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum BarrierCutsOfCell {+ /// A bit per barrier, in paint order, of a band with no more barriers than bits.+ BitPerCut(u64),+ /// The indices of the barriers, in paint order, of a band with more.+ CutIndices(Rc<[u32]>),}-fn media_layer_rejection(- inputs: &LayerPlanInputs<'_>,- grouping_effects: &[EffectNodeIndex],- bounds: &BoundsContext<'_>,- run_is_a_chunk_of_its_own: impl Fn(u32) -> bool,- record_offsets_of_media_under_backdrop_filters: &[u32],- run_index: u32,- record_offset: u32,-) -> Option<MediaLayerRejection> {- let header = read_header(&inputs.tape[record_offset as usize..]);- if !matches!(- header.command_type,- DisplayListCommandType::DrawCanvas- | DisplayListCommandType::DrawVideoFrame- | DisplayListCommandType::DrawCompositedContext- ) {- return Some(MediaLayerRejection::DrawnInsideAnotherCommand);- }- let run = &inputs.command_runs[run_index as usize];- if !run.context.effect.is_none() && !grouping_effects[run.context.effect.0 as usize].is_none() {- return Some(MediaLayerRejection::InsideGroupEffect);- }- if !bounds.world.draw_matrix(run.context.spatial).is_2d_affine() {- return Some(MediaLayerRejection::UnderTransformThatIsNot2DAffine);- }- let payload_start = record_offset as usize + HEADER_SIZE;- let payload = &inputs.tape[payload_start..payload_start + header.payload_size as usize];- let bounding_rect = bounding_rect_computed_from_payload(&header, payload).unwrap_or_default();- if bounds.ink_device_rect(run, bounding_rect).is_empty() {- return Some(MediaLayerRejection::DrawsNothingVisible);- }- if !run_is_a_chunk_of_its_own(run_index) {- return Some(MediaLayerRejection::BetweenRunsOfOneGroupEffect);- }- if record_offsets_of_media_under_backdrop_filters.contains(&record_offset) {- return Some(MediaLayerRejection::UnderBackdropFilterReadingRootGroup);- }- None+#[derive(Clone, Debug, PartialEq)]+pub enum LayerContent {+ /// The records of a band that the layer holds in some of its tiles.+ Painted,+ /// A canvas, video or nested context, replayed or shown by the window server, whose content the identity of the+ /// layer names.+ Media { record_span: ListSpan },}-fn media_candidates(- inputs: &LayerPlanInputs<'_>,- grouping_effects: &[EffectNodeIndex],- bounds: &BoundsContext<'_>,- run_is_a_chunk_of_its_own: impl Fn(u32) -> bool,- record_offsets_of_media_under_backdrop_filters: &[u32],-) -> Result<Vec<MediaCandidate>, UnlayeredReason> {- let mut candidates = Vec::new();- let mut first_rejection = None;- for live_content_record in &inputs.summary.live_content_records {- let content = live_content_record.content;- if matches!(content, LiveContent::ImageFrame(_)) {- continue;- }- let IndexedRecord {- run_index,- record_offset,- } = live_content_record.record;- match media_layer_rejection(- inputs,- grouping_effects,- bounds,- &run_is_a_chunk_of_its_own,- record_offsets_of_media_under_backdrop_filters,- run_index,- record_offset,- ) {- None => candidates.push(MediaCandidate {- content,- run_index,- record_offset,- }),- Some(rejection) => {- first_rejection.get_or_insert(UnlayeredReason::NoMediaCanBeLayer {- first_rejected_media: content,- rejection,- });- }- }- }- if candidates.is_empty() {- return Err(first_rejection.unwrap_or(UnlayeredReason::NoMedia));- }- Ok(candidates)+#[derive(Clone, Debug, PartialEq)]+pub struct StackLayer {+ pub identity: LayerIdentity,+ pub placement_node_index: PlacementNodeIndex,+ /// The band the layer holds the records of, or the one it is a barrier in.+ pub band_index: BandIndex,+ pub content: LayerContent,+ /// Whether any record can go into the layer anywhere; a layer that holds nothing has no tiles.+ pub may_hold_content: bool,+ /// Where what the layer holds can show, in the raster coordinates of its space.+ pub reach: IntRect,}-fn keep_canvases_and_videos_ahead_of_nested_contexts_within_layer_limit(media: &mut Vec<MediaCandidate>) {- if media.len() <= MAXIMUM_MEDIA_LAYER_COUNT {- return;- }- media.sort_by_key(|candidate| matches!(candidate.content, LiveContent::CompositedContext(_)));- media.truncate(MAXIMUM_MEDIA_LAYER_COUNT);- media.sort_by_key(|candidate| candidate.record_offset);+/// An effect that the compositor composites the layers of its content inside.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CompositedEffect {+ pub effect: EffectNodeIndex,+ pub placement_node_index: PlacementNodeIndex,+ /// Whether the effect reads what is composited below it: it reads the backdrop of a backdrop filter, or it blends.+ pub reads_what_is_composited_below_it: bool,+ /// Whether its filter moves what it composites past where it is drawn, so that it reads what is drawn inside it+ /// past each of its pixels.+ pub filter_spreads_what_it_composites: bool,}-fn run_ranges_holding_whole_grouping_effects(- command_runs: &[DisplayListCommandRun],- grouping_of_run: &[EffectNodeIndex],-) -> Vec<(u32, u32)> {- let mut last_run_of_group = std::collections::HashMap::new();- for (run_index, group) in grouping_of_run.iter().enumerate() {- if !group.is_none() {- last_run_of_group.insert(group.0, run_index);- }- }- let mut ranges = Vec::new();- let mut run_index = 0;- while run_index < command_runs.len() {- let first = run_index;- let mut last = run_index;- let mut next = run_index;- while next <= last {- let group = grouping_of_run[next];- if !group.is_none() {- last = last.max(last_run_of_group[&group.0]);- }- next += 1;+impl CompositedEffect {+ /// The effects the compositor composites the nodes of a stack inside, one per composited node in the order of the+ /// nodes, with what the tree tells of how each reads. Each of those effects is a node of `tree`.+ fn of_nodes(nodes: &[PlacementNode], tree: &VisualContextTree) -> Vec<CompositedEffect> {+ if nodes.iter().all(|node| node.composited_effect.is_none()) {+ return Vec::new();}- ranges.push((first as u32, last as u32));- run_index = last + 1;+ let backdrop_reader_by_effect_index = backdrop_reader_by_reading_effect_index(tree);+ nodes+ .iter()+ .enumerate()+ .filter_map(|(index, node)| {+ let effect = node.composited_effect?;+ Some(CompositedEffect {+ effect,+ placement_node_index: PlacementNodeIndex(index),+ reads_what_is_composited_below_it: backdrop_reader_by_effect_index[effect.0 as usize].is_some(),+ filter_spreads_what_it_composites: filter_may_spread_at_some_sample(tree, effect),+ })+ })+ .collect()}- ranges}-// Runs that go into one layer together, as they hold all runs of the group effects among them.-struct Chunk {- first_run: u32,- last_run: u32,- device_rect: IntRect,- backdrop_filters_reading_root_group: Vec<EffectNodeIndex>,+/// The layers of a list bottom to top, with the base layer, which is rastered over the surface's clear color and+/// replaces what is below it. Layers below the base layer hold nothing. A stack does not change once it is planned:+/// what a frame works out of it is kept apart from it.+#[derive(Clone, Debug, PartialEq)]+pub struct LayerStack {+ /// The viewport's space, and for a stack of more than one layer, the spaces `RasterSpaces::spaces_at_anchors` makes+ /// at the anchors `raster_space_anchors` gives for the tree, without the extent of each space but the viewport's.+ pub spaces: Vec<RasterSpace>,+ pub nodes: Vec<PlacementNode>,+ pub bands: Vec<PlacementNodeBand>,+ pub layers: Vec<StackLayer>,+ /// In the order of their nodes, which is paint order.+ pub composited_effects: Vec<CompositedEffect>,+ pub base_layer: LayerIndex,+ /// Why the stack is one layer that replays the whole list, if it is.+ pub why_list_is_one_layer: Option<WhyListIsOneLayer>,+ pub layering_obstacles: LayeringObstacles,+ /// Per raster space, whether records its tiles hold move within it as nodes that move on their own, or that the+ /// compositor scrolls without the space following them, do. Canvases, videos and nested contexts with layers of+ /// their own hold none of those records.+ pub tiles_hold_content_moving_within_space_by_space_index: Vec<bool>,+ /// Per raster space whose anchor the compositor animates and that holds content, where that content can show in+ /// the raster coordinates of the space it is in wherever the animation takes it.+ pub swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>>,+ /// Per band, the innermost band at or around it whose node the compositor composites inside its effect.+ innermost_composited_band_at_or_around_band: Vec<Option<BandIndex>>,}-fn place_records_in_layers(- inputs: &LayerPlanInputs<'_>,- bounds: &BoundsContext<'_>,- chunks: &[Chunk],- grouping_of_run: &[EffectNodeIndex],- media: &[MediaCandidate],-) -> Result<LayersBeingPlanned, MediaLayersUnderBackdropFilter> {- let command_runs = inputs.command_runs;- let mut planned = LayersBeingPlanned::new(inputs.viewport_rect);- let mut media_iter = media.iter().enumerate().peekable();- for chunk in chunks {- let (first, last) = (chunk.first_run, chunk.last_run);- let first_run = &command_runs[first as usize];- let last_run = &command_runs[last as usize];- if !chunk.backdrop_filters_reading_root_group.is_empty() {- planned.check_backdrop_filters_can_go_into_base_layer(chunk.device_rect, |layer| {- chunk- .backdrop_filters_reading_root_group- .iter()- .any(|&effect| bounds.backdrop_filter_reads_device_rect(effect, layer.rect))- })?;- }-- let run_draws_media_layer = media_iter- .peek()- .is_some_and(|(_, candidate)| candidate.run_index == first);- // The rect of a record under a perspective transform is an estimate, so such a run stays whole.- let run_can_be_split_between_layers = first == last- && grouping_of_run[first as usize].is_none()- && bounds.world.draw_matrix(first_run.context.spatial).is_2d_affine();- let places_each_record_of_run = run_draws_media_layer- || (run_can_be_split_between_layers- && planned.topmost_layer_above_base_touching(chunk.device_rect).is_some());- if !places_each_record_of_run {- let chunk_span = RecordSpan {- begin_offset: first_run.offset,- end_offset: last_run.offset + last_run.size,- };- planned.place_painted_records(chunk_span, chunk.device_rect);- continue;- }+/// Where the window server can show each canvas and video layer of a stack under the values of one frame, or why it+/// cannot, by layer index. A stack is kept while its spaces scroll and its media move with them, so each frame works+/// this out anew.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct WindowServerPlacementsOfMedia {+ placement_by_layer_index: Vec<Option<Result<WindowServerPlacement, WhyWindowServerCannotShowMedia>>>,+}- let run = first_run;- let records = &inputs.tape[run.offset as usize..(run.offset + run.size) as usize];- let mut layer_of_previous_painted_record = LayersBeingPlanned::BASE_LAYER_INDEX;- for_each_command(records, |header, offset, payload| {- let begin_offset = run.offset + offset as u32;- let span = RecordSpan {- begin_offset,- end_offset: begin_offset + (HEADER_SIZE + payload.len()) as u32,- };- if let Some((media_index, candidate)) =- media_iter.next_if(|(_, candidate)| candidate.record_offset == begin_offset)- {- let bounding_rect = bounding_rect_computed_from_payload(header, payload).unwrap_or_default();- let media_bounds = bounds.ink_device_rect(run, bounding_rect);- let window_server_shows_content = !matches!(candidate.content, LiveContent::CompositedContext(_));- let placement = window_server_shows_content.then(|| {- window_server_placement(inputs.tree, &bounds.world, inputs.viewport_rect, run, header, payload)- });- planned.add_media_layer(media_index, candidate.content, span, media_bounds, placement);- layer_of_previous_painted_record = LayersBeingPlanned::BASE_LAYER_INDEX;- } else if header.command_type.is_compositor_metadata() {- planned.append_records_to_layer(layer_of_previous_painted_record, span);- } else {- let bounding_rect = bounding_rect_computed_from_payload(header, payload).unwrap_or_default();- let record_bounds = bounds.ink_device_rect(run, bounding_rect);- layer_of_previous_painted_record = planned.place_painted_records(span, record_bounds);- }- });+impl WindowServerPlacementsOfMedia {+ /// Where the window server can show the canvas or video of the layer, or why it cannot. None for a layer that holds+ /// no canvas or video.+ pub fn of_layer(+ &self,+ layer_index: LayerIndex,+ ) -> Option<&Result<WindowServerPlacement, WhyWindowServerCannotShowMedia>> {+ self.placement_by_layer_index.get(layer_index.0)?.as_ref()}- Ok(planned)}-pub fn build_layer_plan(inputs: &LayerPlanInputs<'_>) -> Result<LayerPlan, UnlayeredReason> {- let tree = inputs.tree;- let command_runs = inputs.command_runs;- let draws_media = inputs- .summary- .live_content_records- .iter()- .any(|record| !matches!(record.content, LiveContent::ImageFrame(_)));- if !draws_media {- return Err(UnlayeredReason::NoMedia);- }- if inputs.viewport_rect.is_empty() {- return Err(UnlayeredReason::EmptyViewport);- }- if command_runs.is_empty() {- return Err(UnlayeredReason::EmptyDisplayList);- }- if tree_has_sorting_contexts(tree) {- return Err(UnlayeredReason::SortingContext3D);- }- if !root_isolation_effect_is_plain_group(tree) {- return Err(UnlayeredReason::RootIsolationEffectIsNotPlainGroup);- }- if let Some(reason) = what_reads_root_group(inputs) {- return Err(reason);- }- if !mask_declarations_sit_under_their_masks(inputs) {- return Err(UnlayeredReason::MaskDeclaredOutsideItsMask);+/// Where the window server can show the canvases and videos of a stack under the values of one frame, and which layers+/// it shows above the frame where it can show every canvas and video it has a placement for, as the dump tells them.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct WindowServerPresentationOfMedia {+ pub placements: WindowServerPlacementsOfMedia,+ /// By layer index.+ pub shown_by_window_server_by_layer_index: Vec<bool>,+}++impl WindowServerPresentationOfMedia {+ fn layer_is_shown_by_window_server(&self, layer_index: LayerIndex) -> bool {+ self.shown_by_window_server_by_layer_index+ .get(layer_index.0)+ .copied()+ .unwrap_or(false)}+}- let mut culling = TreeCullingScratch::default();- tree.fill_culling_scratch(&mut culling);- let world = WorldTransforms::new(tree, inputs.scroll_offsets, Some(FloatMatrix4x4::identity()));- let clip_bounds = clip_chain_bounds(tree, &world);- let bounds = BoundsContext {- world,- culling,- clip_bounds,- viewport_rect: inputs.viewport_rect,- tree,- };-- let grouping_effects = outermost_grouping_effects(tree);- let grouping_of_run: Vec<EffectNodeIndex> = command_runs- .iter()- .map(|run| {- if run.context.effect.is_none() {- EffectNodeIndex::NONE- } else {- grouping_effects[run.context.effect.0 as usize]- }- })- .collect();- let chunk_ranges = run_ranges_holding_whole_grouping_effects(command_runs, &grouping_of_run);- let mut chunk_of_run = vec![0usize; command_runs.len()];- for (chunk_index, &(first, last)) in chunk_ranges.iter().enumerate() {- chunk_of_run[first as usize..=last as usize].fill(chunk_index);+// A band comes after the band it is in.+fn innermost_composited_band_at_or_around_each_band(+ nodes: &[PlacementNode],+ bands: &[PlacementNodeBand],+) -> Vec<Option<BandIndex>> {+ let mut innermost_composited_band_by_band_index: Vec<Option<BandIndex>> = Vec::with_capacity(bands.len());+ for (band_index, band) in bands.iter().enumerate() {+ let innermost_composited_band = if nodes[band.placement_node_index.0].composited_effect.is_some() {+ Some(BandIndex(band_index))+ } else {+ band.parent_band_holding_this_band_as_barrier+ .and_then(|band_around| innermost_composited_band_by_band_index.get(band_around.0).copied())+ .flatten()+ };+ innermost_composited_band_by_band_index.push(innermost_composited_band);}+ innermost_composited_band_by_band_index+}- let run_is_a_chunk_of_its_own = |run_index: u32| {- let (first, last) = chunk_ranges[chunk_of_run[run_index as usize]];- first == last- };-- let mut effect_geometry = Vec::new();- compute_effect_geometry(tree, command_runs, &bounds.world, &mut effect_geometry);- let backdrop_filter_reading_root_group_on_chain = backdrop_filter_reading_root_group_on_chain(tree);- let mut group_rects: std::collections::HashMap<u32, IntRect> = std::collections::HashMap::new();- let mut run_device_rect = |run_index: usize| -> IntRect {- let run = &command_runs[run_index];- let group = grouping_of_run[run_index];- if group.is_none() {- return bounds.ink_device_rect(run, run.ink_bounds);+fn identity_of_node(+ spaces: &[RasterSpace],+ raster_space_index: RasterSpaceIndex,+ composite_clips: &[CompositeClip],+) -> PlacementNodeIdentity {+ let mut hasher = foldhash::fast::FixedState::with_seed(0x706c_6163_656d_656e).build_hasher();+ hasher.write_u64(spaces[raster_space_index.0].identity);+ for clip in composite_clips {+ hasher.write_u64(spaces[clip.raster_space_index.0].identity);+ for value in [clip.rect.x, clip.rect.y, clip.rect.width, clip.rect.height] {+ hasher.write_i32(value);}- *group_rects.entry(group.0).or_insert_with(|| {- bounds.group_device_rect(group, effect_geometry[group.0 as usize].output, inputs.effect_clips)- })- };- let chunks: Vec<Chunk> = chunk_ranges- .iter()- .map(|&(first_run, last_run)| {- let mut device_rect = IntRect::default();- let mut backdrop_filters_reading_root_group = Vec::new();- for (run_index, run) in command_runs- .iter()- .enumerate()- .take(last_run as usize + 1)- .skip(first_run as usize)- {- device_rect = device_rect.united(run_device_rect(run_index));- let effect = run.context.effect;- if effect.is_none() {- continue;- }- let backdrop_filter = backdrop_filter_reading_root_group_on_chain[effect.0 as usize];- if !backdrop_filter.is_none() && !backdrop_filters_reading_root_group.contains(&backdrop_filter) {- backdrop_filters_reading_root_group.push(backdrop_filter);- }- }- Chunk {- first_run,- last_run,- device_rect,- backdrop_filters_reading_root_group,- }- })- .collect();-- // Each try leaves out at least one more canvas or video, so this ends.- let mut record_offsets_of_media_under_backdrop_filters = Vec::new();- let planned = loop {- let mut media = media_candidates(- inputs,- &grouping_effects,- &bounds,- run_is_a_chunk_of_its_own,- &record_offsets_of_media_under_backdrop_filters,- )?;- keep_canvases_and_videos_ahead_of_nested_contexts_within_layer_limit(&mut media);- match place_records_in_layers(inputs, &bounds, &chunks, &grouping_of_run, &media) {- Ok(planned) => break planned,- Err(MediaLayersUnderBackdropFilter(media_layers)) => {- record_offsets_of_media_under_backdrop_filters.extend(- media- .iter()- .enumerate()- .filter(|(media_index, _)| media_layers & (1 << media_index) != 0)- .map(|(_, candidate)| candidate.record_offset),- );- }- }- };- let LayersBeingPlanned {- layers,- record_ranges_in_tape_order,- ..- } = planned;-- let viewport_area = i64::from(inputs.viewport_rect.width) * i64::from(inputs.viewport_rect.height);- let upper_painted_area: i64 = layers- .iter()- .filter(|layer| layer.kind == LayerKind::Painted)- .map(|layer| i64::from(layer.rect.width) * i64::from(layer.rect.height))- .sum();- if upper_painted_area > MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS * viewport_area {- return Err(UnlayeredReason::UpperPaintedLayersTooLarge);+ clip.corner_radii.hash(&mut hasher);}-- Ok(LayerPlan {- layers,- record_ranges_in_tape_order,- })+ PlacementNodeIdentity(hasher.finish())}-#[cfg(test)]-mod tests {- use super::*;- use crate::display_list::builder::{DisplayListBuilder, PendingInlineClip};- use crate::display_list::chunks::TapeChunks;- use crate::display_list::commands::{- CanvasId, CompositorBlockingWheelEventRegion, CompositorContextId, ContextRef, DisplayListCommand, DrawCanvas,- DrawCompositedContext, FillRect, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,- };- use crate::display_list::damage::{- DisplayListDamage, DisplayListFrame, LayerPlans, LiveContentChanges, compute_display_list_damage,- };- use crate::display_list::summary::summarize;- use crate::node_slot_id::NodeSlotId;- use crate::visual_context::{EffectsData, ScrollData, TransformData, TransformDataRole};- use libgfx_rust::{- AffineTransform, Color, CompositingAndBlendingOperator, CornerRadii, ScalingMode, rotation_matrix, scale_matrix,- };-- const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);- const CANVAS: LiveContent = LiveContent::Canvas(CanvasId(1));- const NESTED_CONTEXT: LiveContent = LiveContent::CompositedContext(CompositorContextId(7));-- fn identity_tree() -> VisualContextTree {- VisualContextTree::create(TransformData {- matrix: FloatMatrix4x4::identity(),- origin: FloatPoint::default(),- sorting_context_root_index: None,- flattens_inherited_transform: false,- role: TransformDataRole::CssTransform,- synthetic_plane: false,- establishes_sorting_context: false,- bounds: FloatRect::default(),- })- }+// An effect index names the effect for as long as the tree keeps the node, which outlives lists and scrolls.+fn identity_of_composited_node(+ parent_identity: PlacementNodeIdentity,+ effect: EffectNodeIndex,+) -> PlacementNodeIdentity {+ let mut hasher = foldhash::fast::FixedState::with_seed(0x636f_6d70_6f73_6974).build_hasher();+ hasher.write_u64(parent_identity.0);+ hasher.write_u32(effect.0);+ PlacementNodeIdentity(hasher.finish())+}- fn tree_with_root_isolation_effect() -> VisualContextTree {- let mut tree = identity_tree();- let root = tree.append_effect(- effects(1.0, CompositingAndBlendingOperator::Normal),- EffectNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- ClipNodeIndex::NONE,- );- tree.root_isolation_effect = Some(root);- tree+fn node_covers_viewport(nodes: &[PlacementNode], spaces: &[RasterSpace], node_index: PlacementNodeIndex) -> bool {+ let mut node_on_way_out = Some(node_index);+ while let Some(index) = node_on_way_out {+ let node = &nodes[index.0];+ if !node.composite_clips.is_empty()+ || node.composited_effect.is_some()+ || node.reach_in_parent_node != Reach::Anywhere+ || (node.parent_index.is_some()+ && spaces[node.raster_space_index.0].anchor_kind != RasterSpaceAnchorKind::ViewportScroller)+ {+ return false;+ }+ node_on_way_out = node.parent_index;}+ true+}- fn effects(opacity: f32, blend_mode: CompositingAndBlendingOperator) -> EffectNodeData {- EffectNodeData::Effects(EffectsData {- isolation: false,- opacity,- blend_mode,- filter: None,- backdrop_filter: None,- })- }+/// What a plan says of a stack of more than one layer, each thing once: the nodes without their identities, and the+/// bands in the order of a walk that enters the first band, and at each cut whose barrier is a nested band, the next+/// band, each band with what only it knows of its layers. `LayerStack::of_layered_plan` works out the rest.+#[derive(Clone, Debug)]+struct LayeredPlan {+ nodes: Vec<NodeOfPlan>,+ bands: Vec<BandOfPlan>,+ tiles_hold_content_moving_within_space_by_space_index: Vec<bool>,+ swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>>,+}- fn separate_clip(tree: &mut VisualContextTree, parent: ContextRef) -> ContextRef {- let clip = tree.append_clip(- ClipNodeData::rect_clip(VIEWPORT.to_float()),- parent.clip,- parent.spatial,- );- ContextRef { clip, ..parent }- }+/// A placement node without its identity, which the stack works out of the node, the node it is in and the spaces.+#[derive(Clone, Debug)]+struct NodeOfPlan {+ raster_space_index: RasterSpaceIndex,+ composite_clips: Vec<CompositeClip>,+ composited_effect: Option<EffectNodeIndex>,+ parent_index: Option<PlacementNodeIndex>,+ reach_in_parent_node: Reach<IntRect>,+}- fn fill(rect: IntRect) -> FillRect {- FillRect {- rect,- color: Color::from_rgb(0, 128, 0),- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- }- }+#[derive(Clone, Debug)]+struct BandOfPlan {+ placement_node_index: PlacementNodeIndex,+ /// In paint order.+ record_spans: Vec<ListSpan>,+ reach_of_layer_below_all_cuts: IntRect,+ /// In paint order.+ cuts: Vec<CutOfPlan>,+}- fn nested_context(rect: IntRect) -> DrawCompositedContext {- nested_context_with_id(rect, CompositorContextId(7))- }+#[derive(Clone, Copy, Debug)]+struct CutOfPlan {+ barrier: BarrierOfPlan,+ reach_of_layer_above_cut: IntRect,+}- fn nested_context_with_id(rect: IntRect, child_context_id: CompositorContextId) -> DrawCompositedContext {- DrawCompositedContext {- dst_rect: rect.to_float(),- child_context_id,- scaling_mode: ScalingMode::NearestNeighbor,- spatial_node_index: VISUAL_VIEWPORT_NODE_INDEX,- snap_origin_if_untransformed: true,- }- }+#[derive(Clone, Copy, Debug)]+enum BarrierOfPlan {+ /// A canvas, video or nested context that is a layer of its own, the `ordinal`th drawing of its content in paint+ /// order, which cuts the tiles its reach touches.+ Media {+ content: LiveContent,+ ordinal: u32,+ record_span: ListSpan,+ reach: IntRect,+ },+ /// The next band of the walk, which is of a node in the band's node and cuts the tiles that node reaches.+ NestedBand,+}- fn canvas(rect: IntRect) -> DrawCanvas {- DrawCanvas {- dst_rect: rect,- canvas_id: CanvasId(1),- scaling_mode: ScalingMode::NearestNeighbor,- }- }+// A band the walk of the bands of a plan is in, with the cuts of it that the walk has yet to pass, and the reach of the+// layer above the cut whose nested band the walk is in.+struct BandOfWalk {+ band_index: BandIndex,+ cuts_to_pass: std::vec::IntoIter<CutOfPlan>,+ reach_of_layer_above_nested_band: IntRect,+}- struct TestList {- builder: DisplayListBuilder,+fn painted_layer_of_band(+ nodes: &[PlacementNode],+ bands: &[PlacementNodeBand],+ band_index: BandIndex,+ above_barrier: Option<BarrierIdentity>,+ reach: IntRect,+) -> StackLayer {+ let band = &bands[band_index.0];+ StackLayer {+ identity: LayerIdentity::Painted {+ node: nodes[band.placement_node_index.0].identity,+ band_ordinal_in_node: band.band_ordinal_in_node,+ above_barrier,+ },+ placement_node_index: band.placement_node_index,+ band_index,+ content: LayerContent::Painted,+ may_hold_content: !reach.is_empty(),+ reach,}+}- impl TestList {- fn new() -> Self {- Self {- builder: DisplayListBuilder::new(),- }+impl LayerStack {+ /// One layer that replays the whole list, which is always correct.+ pub fn one_layer_replaying_whole_list(+ viewport_rect: IntRect,+ whole_list_span: ListSpan,+ why_list_is_one_layer: Option<WhyListIsOneLayer>,+ layering_obstacles: LayeringObstacles,+ ) -> Self {+ let spaces = vec![RasterSpace::of_viewport(viewport_rect)];+ let root_node = PlacementNode {+ identity: identity_of_node(&spaces, RasterSpaceIndex::VIEWPORT, &[]),+ raster_space_index: RasterSpaceIndex::VIEWPORT,+ composite_clips: Vec::new(),+ composited_effect: None,+ parent_index: None,+ reach_in_parent_node: Reach::Anywhere,+ };+ let layers = vec![StackLayer {+ identity: LayerIdentity::Painted {+ node: root_node.identity,+ band_ordinal_in_node: 0,+ above_barrier: None,+ },+ placement_node_index: PlacementNodeIndex(0),+ band_index: BandIndex(0),+ content: LayerContent::Painted,+ may_hold_content: true,+ reach: viewport_rect,+ }];+ Self {+ layers,+ bands: vec![PlacementNodeBand {+ placement_node_index: PlacementNodeIndex(0),+ band_ordinal_in_node: 0,+ parent_band_holding_this_band_as_barrier: None,+ record_spans: vec![whole_list_span],+ cuts: Vec::new(),+ layer_below_all_cuts: LayerIndex(0),+ }],+ nodes: vec![root_node],+ spaces,+ composited_effects: Vec::new(),+ base_layer: LayerIndex(0),+ why_list_is_one_layer,+ layering_obstacles,+ tiles_hold_content_moving_within_space_by_space_index: vec![true],+ swept_reach_in_parent_space_by_space_index: vec![None],+ innermost_composited_band_at_or_around_band: Vec::new(),}-- fn with<C: DisplayListCommand>(mut self, command: C, context: ContextRef) -> Self {- self.builder.append(&command, &[], context);- self+ .with_lookups()+ }++ // The lookups that the methods read, built from what the stack holds. Every index the stack holds must be in range.+ fn with_lookups(mut self) -> Self {+ self.innermost_composited_band_at_or_around_band =+ innermost_composited_band_at_or_around_each_band(&self.nodes, &self.bands);+ self+ }++ /// The stack of a plan of more than one layer, as the planner and the compositor both work it out. The layers come+ /// in the order of the walk of the bands: a band's layer below all cuts, then per cut the layers of its barrier,+ /// which are a canvas, video or nested context or those of the nested band, and the layer above the cut. The+ /// ordinal of a band in its node counts the bands of the node before it in the walk. The base layer is the first+ /// layer that can hold content where that is the layer below all cuts of a band of a node that covers the viewport,+ /// and the first layer otherwise.+ ///+ /// Every index the plan holds must be in range, each node must come after the node it is in, and the walk must+ /// enter each band of the plan once.+ fn of_layered_plan(+ plan: LayeredPlan,+ spaces: Vec<RasterSpace>,+ tree: &VisualContextTree,+ layering_obstacles: LayeringObstacles,+ ) -> Self {+ let mut nodes: Vec<PlacementNode> = Vec::with_capacity(plan.nodes.len());+ for node in plan.nodes {+ let identity = match (node.composited_effect, node.parent_index) {+ (Some(effect), Some(parent_index)) => {+ identity_of_composited_node(nodes[parent_index.0].identity, effect)+ }+ _ => identity_of_node(&spaces, node.raster_space_index, &node.composite_clips),+ };+ nodes.push(PlacementNode {+ identity,+ raster_space_index: node.raster_space_index,+ composite_clips: node.composite_clips,+ composited_effect: node.composited_effect,+ parent_index: node.parent_index,+ reach_in_parent_node: node.reach_in_parent_node,+ });}-- fn with_inline_clips<C: DisplayListCommand>(- mut self,- command: C,- context: ContextRef,- inline_clips: &[PendingInlineClip],- ) -> Self {- self.builder- .append_with_inline_clips(&command, &[], context, inline_clips);- self+ let mut bands: Vec<PlacementNodeBand> = Vec::with_capacity(plan.bands.len());+ let mut layers: Vec<StackLayer> = Vec::new();+ let mut next_band_ordinal_by_node_index = vec![0; nodes.len()];+ let mut bands_of_plan = plan.bands.into_iter();+ let mut walk: Vec<BandOfWalk> = Vec::new();+ let mut enters_next_band = true;+ loop {+ if enters_next_band && let Some(band) = bands_of_plan.next() {+ let band_index = BandIndex(bands.len());+ let band_ordinal_in_node = &mut next_band_ordinal_by_node_index[band.placement_node_index.0];+ bands.push(PlacementNodeBand {+ placement_node_index: band.placement_node_index,+ band_ordinal_in_node: *band_ordinal_in_node,+ parent_band_holding_this_band_as_barrier: walk.last().map(|walked| walked.band_index),+ record_spans: band.record_spans,+ cuts: Vec::with_capacity(band.cuts.len()),+ layer_below_all_cuts: LayerIndex(layers.len()),+ });+ *band_ordinal_in_node += 1;+ let layer = painted_layer_of_band(&nodes, &bands, band_index, None, band.reach_of_layer_below_all_cuts);+ layers.push(layer);+ walk.push(BandOfWalk {+ band_index,+ cuts_to_pass: band.cuts.into_iter(),+ reach_of_layer_above_nested_band: IntRect::default(),+ });+ }+ enters_next_band = false;+ let Some(walked) = walk.last_mut() else {+ break;+ };+ let band_index = walked.band_index;+ match walked.cuts_to_pass.next() {+ Some(CutOfPlan {+ barrier:+ BarrierOfPlan::Media {+ content,+ ordinal,+ record_span,+ reach,+ },+ reach_of_layer_above_cut,+ }) => {+ layers.push(StackLayer {+ identity: LayerIdentity::Media { content, ordinal },+ placement_node_index: bands[band_index.0].placement_node_index,+ band_index,+ content: LayerContent::Media { record_span },+ may_hold_content: true,+ reach,+ });+ let barrier = Some(BarrierIdentity::Media { content, ordinal });+ let layer = painted_layer_of_band(&nodes, &bands, band_index, barrier, reach_of_layer_above_cut);+ layers.push(layer);+ bands[band_index.0].cuts.push(BarrierCut {+ barrier_first_record_position: record_span.begin,+ cut_reach: Reach::Within(reach),+ layer_above_cut: LayerIndex(layers.len() - 1),+ });+ }+ Some(CutOfPlan {+ barrier: BarrierOfPlan::NestedBand,+ reach_of_layer_above_cut,+ }) => {+ walked.reach_of_layer_above_nested_band = reach_of_layer_above_cut;+ enters_next_band = true;+ }+ None => {+ walk.pop();+ let Some(walked_around) = walk.last() else {+ continue;+ };+ let nested_band = &bands[band_index.0];+ let nested_node = &nodes[nested_band.placement_node_index.0];+ // A plan opens a band for the stretch of records it starts with, so the cut of a nested band is+ // painted where its content begins.+ let where_content_of_nested_band_begins = [+ nested_band.record_spans.first().map(|span| span.begin),+ nested_band.cuts.first().map(|cut| cut.barrier_first_record_position),+ ]+ .into_iter()+ .flatten()+ .min()+ .unwrap_or_default();+ let cut = BarrierCut {+ barrier_first_record_position: where_content_of_nested_band_begins,+ cut_reach: nested_node.reach_in_parent_node,+ layer_above_cut: LayerIndex(layers.len()),+ };+ let barrier = Some(BarrierIdentity::NestedNodeBand {+ node: nested_node.identity,+ band_ordinal_in_node: nested_band.band_ordinal_in_node,+ });+ let (band_index, reach_of_layer_above_cut) =+ (walked_around.band_index, walked_around.reach_of_layer_above_nested_band);+ let layer = painted_layer_of_band(&nodes, &bands, band_index, barrier, reach_of_layer_above_cut);+ layers.push(layer);+ bands[band_index.0].cuts.push(cut);+ }+ }}-- fn plan(&self, tree: &VisualContextTree, scroll_offsets: &[FloatPoint]) -> Result<LayerPlan, UnlayeredReason> {- let (tape, runs) = (self.builder.bytes(), self.builder.command_runs());- let summary = summarize(tape, runs);- let effect_clips = EffectClipPlan::new(tree, runs).unwrap();- build_layer_plan(&LayerPlanInputs {- tape,- command_runs: runs,- summary: &summary,- effect_clips: &effect_clips,- tree,- scroll_offsets,- viewport_rect: VIEWPORT,+ let base_layer = layers+ .iter()+ .position(|layer| layer.may_hold_content)+ .filter(|&index| {+ matches!(+ layers[index].identity,+ LayerIdentity::Painted {+ above_barrier: None,+ ..+ }+ ) && node_covers_viewport(&nodes, &spaces, layers[index].placement_node_index)})+ .map_or(LayerIndex(0), LayerIndex);+ LayerStack {+ composited_effects: CompositedEffect::of_nodes(&nodes, tree),+ spaces,+ nodes,+ bands,+ layers,+ base_layer,+ why_list_is_one_layer: None,+ layering_obstacles,+ tiles_hold_content_moving_within_space_by_space_index: plan+ .tiles_hold_content_moving_within_space_by_space_index,+ swept_reach_in_parent_space_by_space_index: plan.swept_reach_in_parent_space_by_space_index,+ innermost_composited_band_at_or_around_band: Vec::new(),}+ .with_lookups()}- fn damage_with_layer_plans(- tree: &VisualContextTree,- (old_list, old_plan, old_scroll_offsets): (&TestList, &LayerPlan, &[FloatPoint]),- (new_list, new_plan, new_scroll_offsets): (&TestList, &LayerPlan, &[FloatPoint]),- ) -> DisplayListDamage {- let (old_tape, old_runs) = (old_list.builder.bytes(), old_list.builder.command_runs());- let (new_tape, new_runs) = (new_list.builder.bytes(), new_list.builder.command_runs());- let (old_summary, new_summary) = (summarize(old_tape, old_runs), summarize(new_tape, new_runs));- let old_chunks = TapeChunks::with_a_chunk_per_run(old_tape, old_runs);- let new_chunks = TapeChunks::with_a_chunk_per_run(new_tape, new_runs);- let old_effect_clips = EffectClipPlan::new(tree, old_runs).unwrap();- let new_effect_clips = EffectClipPlan::new(tree, new_runs).unwrap();- compute_display_list_damage(- DisplayListFrame {- command_bytes: old_tape,- command_runs: old_runs,- chunks: &old_chunks,- effect_clip_plan: &old_effect_clips,- summary: &old_summary,- visual_context_tree: tree,- scroll_offsets: old_scroll_offsets,- },- DisplayListFrame {- command_bytes: new_tape,- command_runs: new_runs,- chunks: &new_chunks,- effect_clip_plan: &new_effect_clips,- summary: &new_summary,- visual_context_tree: tree,- scroll_offsets: new_scroll_offsets,- },- VIEWPORT,- LiveContentChanges::default(),- Some(LayerPlans {- old: old_plan,- new: new_plan,- }),- )+ pub fn replays_whole_list(&self) -> bool {+ self.why_list_is_one_layer.is_some()}- fn kinds(plan: &LayerPlan) -> Vec<&'static str> {- plan.layers- .iter()- .map(|layer| match layer.kind {- LayerKind::Base => "base",- LayerKind::Painted => "painted",- LayerKind::Media { .. } => "media",- })- .collect()- }-- #[test]- fn content_over_a_canvas_goes_above_it_and_other_content_stays_in_the_base_layer() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let elsewhere = separate_clip(&mut tree, root);- let list = TestList::new()- .with(fill(IntRect::new(0, 0, 800, 600)), root)- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(150, 150, 20, 20)), root)- .with(fill(IntRect::new(500, 400, 20, 20)), elsewhere);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(kinds(&plan), ["base", "media", "painted"]);- assert_eq!(plan.layers[1].rect, IntRect::new(97, 97, 206, 106));- assert_eq!(plan.layers[2].rect, IntRect::new(147, 147, 26, 26));- let run_end = |run: usize| list.builder.command_runs()[run].offset + list.builder.command_runs()[run].size;- let canvas_span = plan.layers[1].record_spans[0];- assert_eq!(- plan.layers[0].record_spans,- [- RecordSpan {- begin_offset: 0,- end_offset: canvas_span.begin_offset,- },- RecordSpan {- begin_offset: run_end(2),- end_offset: run_end(3),- },- ]- );- assert_eq!(- plan.layers[2].record_spans,- [RecordSpan {- begin_offset: canvas_span.end_offset,- end_offset: run_end(2),- }]- );+ /// Whether every tile replays the whole list: a stack of one layer whose tree sorts planes by depth cannot tell+ /// which records show in a tile.+ pub fn one_layer_list_cannot_tell_which_records_show_in_tile(&self) -> bool {+ self.replays_whole_list() && self.layering_obstacles.sorts_planes_by_depth}- fn layers_of_records(list: &TestList, plan: &LayerPlan) -> Vec<usize> {- let mut layers = Vec::new();- for_each_command(list.builder.bytes(), |_, record_offset, _| {- layers.push(plan.layer_of_record(record_offset as u32));- });- layers+ /// Whether tiles of the space hold content that moves within it as nodes that move on their own, or that the+ /// compositor scrolls without the space following them, do, so that the tiles read where those nodes are. Those of+ /// a space that holds none read no value the compositor animates either.+ pub fn space_holds_content_that_moves_within_it(&self, raster_space_index: RasterSpaceIndex) -> bool {+ self.replays_whole_list()+ || self+ .tiles_hold_content_moving_within_space_by_space_index+ .get(raster_space_index.0)+ .copied()+ .unwrap_or(true)}- fn record_offsets(list: &TestList) -> Vec<u32> {- let mut offsets = Vec::new();- for_each_command(list.builder.bytes(), |_, record_offset, _| {- offsets.push(record_offset as u32);- });- offsets.push(list.builder.bytes().len() as u32);- offsets- }-- #[test]- fn records_in_the_run_after_a_canvas_are_placed_one_by_one() {- let tree = identity_tree();- let root = ContextRef::default();- let list = TestList::new()- .with(fill(IntRect::new(0, 0, 800, 600)), root)- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(150, 150, 20, 20)), root)- .with(fill(IntRect::new(500, 400, 20, 20)), root)- .with(fill(IntRect::new(160, 160, 20, 20)), root);- // The canvas is alone in its run.- assert_eq!(list.builder.command_runs().len(), 3);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(kinds(&plan), ["base", "media", "painted"]);- assert_eq!(layers_of_records(&list, &plan), [0, 1, 2, 0, 2]);- assert_eq!(plan.layers[2].rect, IntRect::new(147, 147, 36, 36));- let offsets = record_offsets(&list);- let span = |first_record: usize, record_after_last: usize| RecordSpan {- begin_offset: offsets[first_record],- end_offset: offsets[record_after_last],- };- assert_eq!(plan.layers[0].record_spans, [span(0, 1), span(3, 4)]);- assert_eq!(plan.layers[1].record_spans, [span(1, 2)]);- assert_eq!(plan.layers[2].record_spans, [span(2, 3), span(4, 5)]);+ // The layers of a band come in the order of its cuts, so its topmost layer is the one above its last cut.+ pub fn band_has_layer_at_or_above_base_layer(&self, band_index: BandIndex) -> bool {+ let band = &self.bands[band_index.0];+ let topmost_layer_of_band = band+ .cuts+ .last()+ .map_or(band.layer_below_all_cuts, |cut| cut.layer_above_cut);+ topmost_layer_of_band >= self.base_layer}- #[test]- fn records_in_a_run_that_touches_a_canvas_are_placed_one_by_one() {- let mut tree = identity_tree();- let root = ContextRef::default();- let boxes = separate_clip(&mut tree, root);- let list = TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(500, 400, 20, 20)), boxes)- .with(fill(IntRect::new(150, 150, 20, 20)), boxes)- .with(fill(IntRect::new(600, 400, 20, 20)), boxes);- assert_eq!(list.builder.command_runs().len(), 2);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(layers_of_records(&list, &plan), [1, 0, 2, 0]);+ pub fn space_of_layer(&self, layer_index: LayerIndex) -> RasterSpaceIndex {+ self.nodes[self.layers[layer_index.0].placement_node_index.0].raster_space_index}- #[test]- fn a_run_under_a_perspective_transform_is_placed_whole() {- let mut tree = identity_tree();- let mut perspective_matrix = FloatMatrix4x4::identity();- perspective_matrix.elements[3][0] = 0.0001;- let under_perspective = tree.append_spatial_under(- ContextRef::default(),- SpatialData::Transform(TransformData {- matrix: perspective_matrix,- origin: FloatPoint::default(),- sorting_context_root_index: None,- flattens_inherited_transform: false,- role: TransformDataRole::CssTransform,- synthetic_plane: false,- establishes_sorting_context: false,- bounds: FloatRect::default(),- }),+ // An offset past the coordinate limit shows nothing of the space, and is kept within the limit so that a rect of the+ // stack offset by it still fits in an `IntRect`.+ fn composite_offset_of_space(+ &self,+ raster_space_index: RasterSpaceIndex,+ scroll_offsets: &[FloatPoint],+ ) -> IntPoint {+ let (x, y) = space_and_ancestors_below_viewport(&self.spaces, raster_space_index).fold(+ (0i64, 0i64),+ |(x_so_far, y_so_far), space_or_ancestor_index| {+ let space_or_ancestor = &self.spaces[space_or_ancestor_index.0];+ let anchor_translation = space_or_ancestor.anchor_translation_on_whole_device_pixels(+ device_offset_for_index(scroll_offsets, space_or_ancestor.anchor),+ );+ (+ x_so_far + i64::from(anchor_translation.x),+ y_so_far + i64::from(anchor_translation.y),+ )+ },);- let list = TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), ContextRef::default())- .with(fill(IntRect::new(150, 150, 20, 20)), under_perspective)- .with(fill(IntRect::new(500, 400, 20, 20)), under_perspective);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(layers_of_records(&list, &plan), [1, 2, 2]);+ let limit = i64::from(COORDINATE_LIMIT_IN_DEVICE_PIXELS);+ IntPoint {+ x: x.clamp(-limit, limit) as i32,+ y: y.clamp(-limit, limit) as i32,+ }}- #[test]- fn compositor_metadata_stays_in_the_layer_of_the_record_before_it() {- let tree = identity_tree();- let root = ContextRef::default();- let metadata = CompositorBlockingWheelEventRegion {- rect: FloatRect::new(0.0, 0.0, 900.0, 900.0),- };- let list = TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(150, 150, 20, 20)), root)- .with(metadata, root)- .with(fill(IntRect::new(160, 160, 20, 20)), root);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(layers_of_records(&list, &plan), [1, 2, 2, 2]);- assert_eq!(plan.layers[2].record_spans.len(), 1);+ /// Per raster space, by its index, where the frame composites its rasters, or for a space whose anchor the+ /// compositor animates, those of the space it is in.+ pub fn composite_offsets(&self, scroll_offsets: &[FloatPoint]) -> Vec<IntPoint> {+ (0..self.spaces.len())+ .map(|space_index| self.composite_offset_of_space(RasterSpaceIndex(space_index), scroll_offsets))+ .collect()}- #[test]- fn a_canvas_under_a_group_effect_is_not_a_layer() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let group = tree.append_effect_node_under(root, effects(0.5, CompositingAndBlendingOperator::Normal));- let list = TestList::new().with(canvas(IntRect::new(100, 100, 200, 100)), group);- assert_eq!(- list.plan(&tree, &[]),- Err(UnlayeredReason::NoMediaCanBeLayer {- first_rejected_media: CANVAS,- rejection: MediaLayerRejection::InsideGroupEffect,+ /// Per raster space, by its index, how the frame composites its rasters: at `composite_offsets`, or for a space+ /// whose anchor the compositor animates, through the matrix `draw_matrix_in_frame` gives its anchor in the frame.+ pub fn spaces_to_frame(+ &self,+ composite_offsets: &[IntPoint],+ draw_matrix_in_frame: impl Fn(SpatialNodeIndex) -> FloatMatrix4x4,+ ) -> Vec<SpaceToFrame> {+ self.spaces+ .iter()+ .zip(composite_offsets)+ .map(|(space, &composite_offset)| match space.anchor_kind {+ RasterSpaceAnchorKind::AnimatedTransform { raster_scale } => {+ let anchor_to_frame = draw_matrix_in_frame(space.anchor);+ if !anchor_to_frame.is_2d_affine() {+ return SpaceToFrame::Offset(composite_offset);+ }+ let raster_to_anchor = 1.0 / raster_scale;+ SpaceToFrame::Transform(+ anchor_to_frame+ .extract_2d_affine()+ .scaled(raster_to_anchor, raster_to_anchor),+ )+ }+ _ => SpaceToFrame::Offset(composite_offset),})- );+ .collect()}- #[test]- fn a_nested_context_is_a_layer_that_the_window_server_does_not_show() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let elsewhere = separate_clip(&mut tree, root);- let list = TestList::new()- .with(fill(IntRect::new(0, 0, 800, 600)), root)- .with(nested_context(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(150, 150, 20, 20)), root)- .with(fill(IntRect::new(500, 400, 20, 20)), elsewhere);- let plan = list.plan(&tree, &[]).unwrap();- assert_eq!(kinds(&plan), ["base", "media", "painted"]);- assert_eq!(- plan.layers[1].kind,- LayerKind::Media {- content: NESTED_CONTEXT- }- );- assert_eq!(plan.layers[1].rect, IntRect::new(97, 97, 206, 106));- assert_eq!(plan.layers[1].window_server_placement, None);- assert_eq!(plan.layers[2].rect, IntRect::new(147, 147, 26, 26));+ /// The clip a layer's raster is composited within, in the viewport, or none for no clip.+ pub fn composite_clip_of_layer_in_viewport(+ &self,+ layer_index: LayerIndex,+ composite_offsets: &[IntPoint],+ ) -> Option<IntRect> {+ self.composite_clip_of_node_in_viewport(self.layers[layer_index.0].placement_node_index, composite_offsets)}- #[test]- fn a_canvas_keeps_its_layer_when_more_nested_contexts_than_layers_are_drawn_before_it() {- let tree = identity_tree();- let mut list = TestList::new();- for index in 0..=MAXIMUM_MEDIA_LAYER_COUNT {- let child_context_id = CompositorContextId(10 + index as u64);- let rect = IntRect::new(index as i32 * 60, 0, 50, 50);- list = list.with(nested_context_with_id(rect, child_context_id), ContextRef::default());- }- list = list.with(canvas(IntRect::new(0, 300, 200, 100)), ContextRef::default());- let plan = list.plan(&tree, &[]).unwrap();- let media_of_layers: Vec<LiveContent> = plan- .layers+ /// The clip the rasters of a node are composited within, in the viewport, or none for no clip.+ pub fn composite_clip_of_node_in_viewport(+ &self,+ node_index: PlacementNodeIndex,+ composite_offsets: &[IntPoint],+ ) -> Option<IntRect> {+ self.nodes[node_index.0]+ .composite_clips.iter()- .filter_map(|layer| match layer.kind {- LayerKind::Media { content } => Some(content),- _ => None,+ .fold(None, |intersection_so_far, clip| {+ let clip_rect_in_viewport = clip.rect.translated(+ composite_offsets[clip.raster_space_index.0].x,+ composite_offsets[clip.raster_space_index.0].y,+ );+ Some(+ intersection_so_far.map_or(clip_rect_in_viewport, |intersection_so_far: IntRect| {+ intersection_so_far.intersected(clip_rect_in_viewport)+ }),+ )})- .collect();- assert_eq!(media_of_layers.len(), MAXIMUM_MEDIA_LAYER_COUNT);- assert_eq!(media_of_layers.last(), Some(&CANVAS));}- #[test]- fn a_nested_context_under_a_group_effect_is_not_a_layer() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let group = tree.append_effect_node_under(root, effects(0.5, CompositingAndBlendingOperator::Normal));- let list = TestList::new().with(nested_context(IntRect::new(100, 100, 200, 100)), group);- assert_eq!(- list.plan(&tree, &[]),- Err(UnlayeredReason::NoMediaCanBeLayer {- first_rejected_media: NESTED_CONTEXT,- rejection: MediaLayerRejection::InsideGroupEffect,+ /// The rounded composite clips of a node, in the viewport, which the clip of `composite_clip_of_node_in_viewport`+ /// bounds.+ pub fn rounded_composite_clips_of_node_in_viewport(+ &self,+ node_index: PlacementNodeIndex,+ composite_offsets: &[IntPoint],+ ) -> Vec<(IntRect, CornerRadii)> {+ self.nodes[node_index.0]+ .composite_clips+ .iter()+ .filter(|clip| clip.is_rounded())+ .map(|clip| {+ let offset = composite_offsets[clip.raster_space_index.0];+ (clip.rect.translated(offset.x, offset.y), clip.corner_radii)})- );+ .collect()}- #[test]- fn a_canvas_between_the_runs_of_one_group_is_not_a_layer() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let group = tree.append_effect_node_under(root, effects(1.0, CompositingAndBlendingOperator::Normal));- let list = TestList::new()- .with(fill(IntRect::new(0, 0, 10, 10)), group)- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(20, 0, 10, 10)), group);- assert_eq!(- list.plan(&tree, &[]),- Err(UnlayeredReason::NoMediaCanBeLayer {- first_rejected_media: CANVAS,- rejection: MediaLayerRejection::BetweenRunsOfOneGroupEffect,- })- );+ /// Whether the layer is rastered in a space whose anchor the compositor animates, which the frame composites+ /// through the anchor's transform.+ fn layer_is_in_animated_space(&self, layer_index: LayerIndex) -> bool {+ matches!(+ self.spaces[self.space_of_layer(layer_index).0].anchor_kind,+ RasterSpaceAnchorKind::AnimatedTransform { .. }+ )}- #[test]- fn a_blend_mode_reading_the_root_group_leaves_the_list_unlayered() {- let mut tree = tree_with_root_isolation_effect();- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()- };- let multiply = tree.append_effect_node_under(root, effects(1.0, CompositingAndBlendingOperator::Multiply));- let list = TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(IntRect::new(500, 400, 20, 20)), multiply);- assert_eq!(list.plan(&tree, &[]), Err(UnlayeredReason::BlendModeReadsRootGroup));+ fn layer_is_composited_within_rounded_clips(&self, layer_index: LayerIndex) -> bool {+ self.nodes[self.layers[layer_index.0].placement_node_index.0]+ .composite_clips+ .iter()+ .any(CompositeClip::is_rounded)}- #[test]- fn a_list_without_canvases_videos_or_nested_contexts_is_not_layered() {- let tree = identity_tree();- let list = TestList::new().with(fill(IntRect::new(100, 100, 200, 100)), ContextRef::default());- assert_eq!(list.plan(&tree, &[]), Err(UnlayeredReason::NoMedia));+ /// The innermost band the layer is in whose node the compositor composites inside its effect, if any.+ fn innermost_composited_band_around_layer(&self, layer_index: LayerIndex) -> Option<BandIndex> {+ self.innermost_composited_band_at_or_around_band[self.layers[layer_index.0].band_index.0]}- fn list_with_scrolled_box(tree: &mut VisualContextTree) -> (TestList, SpatialNodeIndex) {- let scroll_node = tree.append_spatial(- SpatialData::Scroll(ScrollData {- state_slot: crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,- owner_paintable: NodeSlotId::INVALID,- }),- VISUAL_VIEWPORT_NODE_INDEX,- );- let scrolled = ContextRef {- spatial: scroll_node,- ..ContextRef::default()- };- let list = TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), ContextRef::default())- .with(fill(IntRect::new(500, 120, 20, 20)), scrolled);- (list, scroll_node)+ /// The next band out from `composited_band` whose node the compositor composites inside its effect, if any.+ fn composited_band_around(&self, composited_band: BandIndex) -> Option<BandIndex> {+ self.bands[composited_band.0]+ .parent_band_holding_this_band_as_barrier+ .and_then(|band_around| self.innermost_composited_band_at_or_around_band[band_around.0])}- #[test]- fn scrolling_content_over_a_canvas_moves_it_above_the_canvas() {- let mut tree = identity_tree();- let (list, scroll_node) = list_with_scrolled_box(&mut tree);- let mut scroll_offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];- let unscrolled = list.plan(&tree, &scroll_offsets).unwrap();- assert_eq!(kinds(&unscrolled), ["base", "media"]);- scroll_offsets[scroll_node.0 as usize] = FloatPoint { x: -300.0, y: 0.0 };- let scrolled = list.plan(&tree, &scroll_offsets).unwrap();- assert_eq!(kinds(&scrolled), ["base", "media", "painted"]);- assert!(!scrolled.has_same_layers_as(&unscrolled));+ pub fn layer_is_inside_composited_effects(&self, layer_index: LayerIndex) -> bool {+ self.innermost_composited_band_around_layer(layer_index).is_some()}- #[test]- fn content_scrolled_within_its_layer_damages_only_that_layer() {- let mut tree = identity_tree();- let (list, scroll_node) = list_with_scrolled_box(&mut tree);- let unscrolled_offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];- let mut scrolled_offsets = unscrolled_offsets.clone();- scrolled_offsets[scroll_node.0 as usize] = FloatPoint { x: 0.0, y: 50.0 };- let before = list.plan(&tree, &unscrolled_offsets).unwrap();- let after = list.plan(&tree, &scrolled_offsets).unwrap();- assert!(after.has_same_layers_as(&before));- let damage = damage_with_layer_plans(- &tree,- (&list, &before, &unscrolled_offsets),- (&list, &after, &scrolled_offsets),- );- assert_eq!(damage.layer_rects, [damage.rect, Some(IntRect::default())]);+ /// The bands the layer is in, innermost first, whose nodes the compositor composites inside their effects. A plan+ /// nests no more of them than `MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS`.+ pub fn composited_bands_around_layer_innermost_first(+ &self,+ layer_index: LayerIndex,+ ) -> impl Iterator<Item = BandIndex> + '_ {+ std::iter::successors(+ self.innermost_composited_band_around_layer(layer_index),+ |&band_index| self.composited_band_around(band_index),+ )}- struct ContextsAroundACanvas {- under_box: ContextRef,- canvas: ContextRef,- boxes_after_canvas: Vec<ContextRef>,+ /// Per layer, how far the filters of the effects the compositor composites around it read past each of its pixels,+ /// summed and cut to `LARGEST_SUMMED_READ_REACH_OF_COMPOSITED_FILTERS_IN_DEVICE_PIXELS`, where+ /// `read_reach_of_composited_node` tells it of one composited node and its effect.+ pub fn summed_read_reach_of_composited_filters_by_layer(+ &self,+ mut read_reach_of_composited_node: impl FnMut(PlacementNodeIndex, EffectNodeIndex) -> i32,+ ) -> Vec<i32> {+ if self.composited_effects.is_empty() {+ return vec![0; self.layers.len()];+ }+ let mut read_reach_by_composited_node_index: Vec<Option<i32>> = vec![None; self.nodes.len()];+ let mut summed_read_reach_by_band_index: Vec<i32> = Vec::with_capacity(self.bands.len());+ for band in &self.bands {+ let summed_around = band+ .parent_band_holding_this_band_as_barrier+ .and_then(|band_around| summed_read_reach_by_band_index.get(band_around.0).copied())+ .unwrap_or(0);+ let node_index = band.placement_node_index;+ let read_reach_of_node = self.nodes[node_index.0].composited_effect.map_or(0, |effect| {+ *read_reach_by_composited_node_index[node_index.0]+ .get_or_insert_with(|| read_reach_of_composited_node(node_index, effect))+ });+ summed_read_reach_by_band_index.push(+ summed_around+ .saturating_add(read_reach_of_node)+ .min(LARGEST_SUMMED_READ_REACH_OF_COMPOSITED_FILTERS_IN_DEVICE_PIXELS),+ );+ }+ self.layers+ .iter()+ .map(|layer| summed_read_reach_by_band_index[layer.band_index.0])+ .collect()}- // Each box gets a clip of its own, so that it is a run of its own.- fn contexts_around_a_canvas(tree: &mut VisualContextTree, box_count_after_canvas: usize) -> ContextsAroundACanvas {- let root = ContextRef {- effect: tree.root_isolation_effect.unwrap(),- ..ContextRef::default()+ // A layer of a space whose anchor the compositor animates is taken to be anywhere the animation can take it, so+ // that which media the window server shows stays put from one sample to the next.+ fn reach_of_layer_in_viewport(&self, layer_index: LayerIndex, composite_offsets: &[IntPoint]) -> IntRect {+ let node = &self.nodes[self.layers[layer_index.0].placement_node_index.0];+ let swept_reach_of_animated_space = self+ .swept_reach_in_parent_space_by_space_index+ .get(node.raster_space_index.0)+ .copied()+ .flatten();+ let reach_in_raster_space = match self.composited_bands_around_layer_innermost_first(layer_index).last() {+ _ if let Some(swept_reach) = swept_reach_of_animated_space => swept_reach,+ Some(outermost_composited_band) => {+ let outermost_composited_node =+ &self.nodes[self.bands[outermost_composited_band.0].placement_node_index.0];+ match outermost_composited_node.reach_in_parent_node {+ Reach::Nothing => return IntRect::default(),+ Reach::Within(draw_and_read_reach_of_outermost_composited_effect) => {+ draw_and_read_reach_of_outermost_composited_effect+ }+ Reach::Anywhere => return self.spaces[RasterSpaceIndex::VIEWPORT.0].extent,+ }+ }+ None => self.layers[layer_index.0].reach,};- ContextsAroundACanvas {- under_box: separate_clip(tree, root),- canvas: root,- boxes_after_canvas: (0..box_count_after_canvas).map(|_| separate_clip(tree, root)).collect(),+ let composite_offset = composite_offsets[node.raster_space_index.0];+ let reach_in_viewport = reach_in_raster_space.translated(composite_offset.x, composite_offset.y);+ match self.composite_clip_of_layer_in_viewport(layer_index, composite_offsets) {+ Some(clip) => reach_in_viewport.intersected(clip),+ None => reach_in_viewport,}}- fn list_around_a_canvas(- contexts: &ContextsAroundACanvas,- (under, under_color): (IntRect, Color),- boxes_after_canvas: &[IntRect],- ) -> TestList {- let mut list = TestList::new()- .with(- FillRect {- color: under_color,- ..fill(under)- },- contexts.under_box,- )- .with(canvas(IntRect::new(100, 100, 200, 100)), contexts.canvas);- for (rect, context) in boxes_after_canvas.iter().zip(&contexts.boxes_after_canvas) {- list = list.with(fill(*rect), *context);+ /// Which layers the window server shows above the frame, rather than the frame holding them, of those above the+ /// base layer that can hold content. The frame holds every layer up to the topmost one it must hold: one inside an+ /// effect the compositor composites, or a canvas, video or nested context the window server cannot show by itself,+ /// as `window_server_can_show` says. Below that, the window server still shows a canvas or video it can show where+ /// no layer above it that the frame holds can show over it. A painted layer is the window server's to show only to+ /// stay above a canvas or video that it shows, so the frame also holds the painted layers below the lowest of+ /// those, and every layer where the window server shows no canvas or video.+ pub fn layers_the_window_server_shows(+ &self,+ composite_offsets: &[IntPoint],+ window_server_can_show: impl Fn(LayerIndex) -> bool,+ ) -> Vec<bool> {+ let mut shown_by_window_server = vec![false; self.layers.len()];+ let is_media = |layer: LayerIndex| matches!(self.layers[layer.0].content, LayerContent::Media { .. });+ let has_media_above_base = (self.base_layer.0 + 1..self.layers.len()).any(|layer| is_media(LayerIndex(layer)));+ if self.replays_whole_list() || !has_media_above_base {+ return shown_by_window_server;}- list- }-- #[test]- fn content_that_changes_under_a_canvas_damages_only_the_base_layer() {- let mut tree = tree_with_root_isolation_effect();- let contexts = contexts_around_a_canvas(&mut tree, 2);- let list_with_under_color = |color| {- list_around_a_canvas(- &contexts,- (IntRect::new(50, 50, 400, 300), color),- &[IntRect::new(150, 150, 20, 20), IntRect::new(600, 500, 20, 20)],- )+ let layers_above_base_that_may_hold_content: Vec<LayerIndex> = (self.base_layer.0 + 1..self.layers.len())+ .map(LayerIndex)+ .filter(|&layer| self.layers[layer.0].may_hold_content)+ .collect();+ let frame_must_hold = |layer: LayerIndex| {+ self.layer_is_inside_composited_effects(layer)+ || self.layer_is_composited_within_rounded_clips(layer)+ || self.layer_is_in_animated_space(layer)+ || (is_media(layer) && !window_server_can_show(layer))};- let old_list = list_with_under_color(Color::from_rgb(255, 0, 0));- let new_list = list_with_under_color(Color::from_rgb(0, 0, 255));- let old_plan = old_list.plan(&tree, &[]).unwrap();- let new_plan = new_list.plan(&tree, &[]).unwrap();- assert_eq!(kinds(&new_plan), ["base", "media", "painted"]);- let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));- let under_rect = Some(IntRect::new(49, 49, 402, 302));- assert_eq!(damage.rect, under_rect);- assert_eq!(- damage.layer_rects,- [under_rect, Some(IntRect::default()), Some(IntRect::default())]- );+ let position_of_topmost_layer_frame_must_hold = layers_above_base_that_may_hold_content+ .iter()+ .rposition(|&layer| frame_must_hold(layer));+ let count_up_to_topmost_layer_frame_must_hold =+ position_of_topmost_layer_frame_must_hold.map_or(0, |position| position + 1);+ for &layer in &layers_above_base_that_may_hold_content[count_up_to_topmost_layer_frame_must_hold..] {+ shown_by_window_server[layer.0] = true;+ }+ let mut reach_in_viewport_of_held_layers_above = IntRect::default();+ for &layer in layers_above_base_that_may_hold_content[..count_up_to_topmost_layer_frame_must_hold]+ .iter()+ .rev()+ {+ let reach_in_viewport = self.reach_of_layer_in_viewport(layer, composite_offsets);+ if is_media(layer)+ && !frame_must_hold(layer)+ && reach_in_viewport_of_held_layers_above+ .intersected(reach_in_viewport)+ .is_empty()+ {+ shown_by_window_server[layer.0] = true;+ continue;+ }+ reach_in_viewport_of_held_layers_above = reach_in_viewport_of_held_layers_above.united(reach_in_viewport);+ }+ let lowest_media_the_window_server_shows = layers_above_base_that_may_hold_content+ .iter()+ .copied()+ .find(|&layer| is_media(layer) && shown_by_window_server[layer.0]);+ for &layer in &layers_above_base_that_may_hold_content {+ if lowest_media_the_window_server_shows.is_none_or(|lowest_media| layer < lowest_media) {+ shown_by_window_server[layer.0] = false;+ }+ }+ shown_by_window_server}- const SMALL_RED_BOX: (IntRect, Color) = (IntRect::new(0, 0, 10, 10), Color::from_rgb(255, 0, 0));-- #[test]- fn a_box_that_moves_off_a_canvas_damages_the_layer_it_leaves_and_the_one_it_enters() {- let mut tree = tree_with_root_isolation_effect();- let contexts = contexts_around_a_canvas(&mut tree, 2);- let list_with_second_box_at =- |second| list_around_a_canvas(&contexts, SMALL_RED_BOX, &[IntRect::new(150, 150, 20, 20), second]);- let old_list = list_with_second_box_at(IntRect::new(160, 160, 20, 20));- let new_list = list_with_second_box_at(IntRect::new(600, 500, 20, 20));- let old_plan = old_list.plan(&tree, &[]).unwrap();- let new_plan = new_list.plan(&tree, &[]).unwrap();- assert_eq!(kinds(&old_plan), ["base", "media", "painted"]);- assert!(new_plan.has_same_layers_as(&old_plan));- let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));- assert_eq!(- damage.layer_rects,- [- Some(IntRect::new(599, 499, 22, 22)),- Some(IntRect::default()),- Some(IntRect::new(159, 159, 22, 22)),- ]+ /// Works out where the window server can show the content of each canvas and video layer under `scroll_offsets`,+ /// and which layers it shows where it can show every canvas and video it has a placement for.+ pub fn window_server_presentation_of_media(+ &self,+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+ ) -> WindowServerPresentationOfMedia {+ let world_of_frame = std::cell::OnceCell::new();+ let placements = self.window_server_placements_of_media(+ list,+ tree,+ || {+ world_of_frame+ .get_or_init(|| WorldTransforms::new(tree, scroll_offsets, Some(FloatMatrix4x4::identity())))+ },+ viewport_rect,);+ let composite_offsets = self.composite_offsets(scroll_offsets);+ let shown_by_window_server_by_layer_index = self.layers_the_window_server_shows(&composite_offsets, |layer| {+ matches!(placements.of_layer(layer), Some(Ok(_)))+ });+ WindowServerPresentationOfMedia {+ placements,+ shown_by_window_server_by_layer_index,+ }}- // The first box grows over an unchanged box, which the layer above the canvas then takes in. With `last_box`, a- // box after the unchanged one changes too, so that the diff compares the unchanged box command by command.- fn assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(last_box: Option<(IntRect, IntRect)>) {- let mut tree = tree_with_root_isolation_effect();- let contexts = contexts_around_a_canvas(&mut tree, 3);- let unchanged_box = IntRect::new(400, 150, 20, 20);- let list_with = |first_box, last_box: Option<IntRect>| {- let mut boxes = vec![first_box, unchanged_box];- boxes.extend(last_box);- list_around_a_canvas(&contexts, SMALL_RED_BOX, &boxes)- };- let old_list = list_with(IntRect::new(150, 150, 20, 20), last_box.map(|(old, _)| old));- let new_list = list_with(IntRect::new(150, 150, 300, 20), last_box.map(|(_, new)| new));- let old_plan = old_list.plan(&tree, &[]).unwrap();- let new_plan = new_list.plan(&tree, &[]).unwrap();- let unchanged_box_record = new_list.builder.command_runs()[3].offset;- assert_eq!(old_plan.layer_of_record(unchanged_box_record), 0);- assert_eq!(new_plan.layer_of_record(unchanged_box_record), 2);- let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));- assert!(damage.layer_rects[0].unwrap().contains_rect(unchanged_box));- assert!(damage.layer_rects[2].unwrap().contains_rect(unchanged_box));- }-- #[test]- fn an_unchanged_box_that_a_growing_layer_takes_in_damages_the_layer_it_leaves() {- assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(None);- }-- #[test]- fn an_unchanged_box_between_changed_boxes_that_a_growing_layer_takes_in_damages_the_layer_it_leaves() {- assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(Some((- IntRect::new(600, 500, 20, 20),- IntRect::new(620, 500, 20, 20),- )));- }-- #[test]- fn an_unchanged_run_that_a_growing_layer_splits_differently_damages_the_layers_its_record_moves_between() {- let mut tree = identity_tree();- let root = ContextRef::default();- let growing_box = separate_clip(&mut tree, root);- let unchanged_box = IntRect::new(400, 150, 20, 20);- let list_with_growing_box = |growing_box_rect| {- TestList::new()- .with(canvas(IntRect::new(100, 100, 200, 100)), root)- .with(fill(growing_box_rect), growing_box)- .with(fill(unchanged_box), root)- .with(fill(IntRect::new(160, 160, 20, 20)), root)- };- let old_list = list_with_growing_box(IntRect::new(150, 150, 20, 20));- let new_list = list_with_growing_box(IntRect::new(150, 150, 300, 20));- let old_plan = old_list.plan(&tree, &[]).unwrap();- let new_plan = new_list.plan(&tree, &[]).unwrap();- assert_eq!(layers_of_records(&old_list, &old_plan), [1, 2, 0, 2]);- assert_eq!(layers_of_records(&new_list, &new_plan), [1, 2, 2, 2]);- assert!(new_plan.has_same_layers_as(&old_plan));- let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));- assert!(damage.layer_rects[0].unwrap().contains_rect(unchanged_box));- assert!(damage.layer_rects[2].unwrap().contains_rect(unchanged_box));- }-- fn placement_of_only_media_layer(plan: &LayerPlan) -> Result<WindowServerPlacement, WindowServerRejection> {- let media_layers: Vec<&Layer> = plan+ /// Works out where the window server could show each canvas and video of the stack under the frame's values, with+ /// the world transforms of the tree in the frame that `world_of_frame` gives, which it asks for only where the+ /// stack holds a canvas or video the window server may show.+ pub fn window_server_placements_of_media<'world>(+ &self,+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ world_of_frame: impl FnOnce() -> &'world WorldTransforms,+ viewport_rect: IntRect,+ ) -> WindowServerPlacementsOfMedia {+ let window_server_may_show_content =+ |content: &LiveContent| !matches!(content, LiveContent::CompositedContext(_));+ let has_media_the_window_server_may_show = self.layers.iter().any(|layer| {+ matches!(&layer.identity, LayerIdentity::Media { content, .. } if window_server_may_show_content(content))+ });+ if !has_media_the_window_server_may_show {+ return WindowServerPlacementsOfMedia::default();+ }+ let world_of_frame = world_of_frame();+ let placement_by_layer_index = self.layers.iter()- .filter(|layer| matches!(layer.kind, LayerKind::Media { .. }))+ .map(|layer| {+ let (LayerContent::Media { record_span }, LayerIdentity::Media { content, .. }) =+ (&layer.content, &layer.identity)+ else {+ return None;+ };+ if !window_server_may_show_content(content) {+ return None;+ }+ let media_record_position = record_span.begin;+ let chunk = list.chunk(media_record_position.chunk_index);+ let run_holding_media =+ &chunk.runs()[chunk.index_of_first_run_ending_after(media_record_position.offset)];+ let (header, payload) = list.record_at(media_record_position);+ Some(crate::display_list::window_server_placement::window_server_placement(+ tree,+ world_of_frame,+ viewport_rect,+ run_holding_media,+ &header,+ payload,+ ))+ }).collect();- assert_eq!(media_layers.len(), 1);- media_layers[0].window_server_placement.unwrap()- }-- fn rounded_rect_clip(rect: FloatRect, corner_radii: CornerRadii) -> ClipNodeData {- ClipNodeData::Rect(crate::visual_context::ClipData {- rect,- corner_radii,- mode: ClipMode::Intersect,- })- }-- fn transform(matrix: FloatMatrix4x4) -> SpatialData {- SpatialData::Transform(TransformData {- matrix,- origin: FloatPoint::default(),- sorting_context_root_index: None,- flattens_inherited_transform: false,- role: TransformDataRole::CssTransform,- synthetic_plane: false,- establishes_sorting_context: false,- bounds: FloatRect::default(),- })+ WindowServerPlacementsOfMedia {+ placement_by_layer_index,+ }}- #[test]- fn rect_clips_of_a_canvas_intersect_into_one_clip_for_the_window_server() {- let mut tree = identity_tree();- let clip = tree.append_clip(- ClipNodeData::rect_clip(FloatRect::new(50.0, 50.0, 200.0, 300.0)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let clipped = ContextRef {- clip,- ..ContextRef::default()+ fn name_of_space(&self, raster_space_index: RasterSpaceIndex, node_namer: &dyn VisualContextNodeNamer) -> String {+ let raster_space = &self.spaces[raster_space_index.0];+ let anchor_kind_name = match raster_space.anchor_kind {+ RasterSpaceAnchorKind::Viewport => return "viewport".into(),+ RasterSpaceAnchorKind::ViewportScroller => return "document".into(),+ RasterSpaceAnchorKind::Scroller => "scroller",+ RasterSpaceAnchorKind::StickyBox { .. } => "sticky",+ RasterSpaceAnchorKind::AnimatedTransform { .. } => "animated",};- let list = TestList::new().with_inline_clips(- canvas(IntRect::new(100, 100, 200, 100)),- clipped,- &[PendingInlineClip::intersecting_float_rect(FloatRect::new(- 0.0, 0.0, 220.0, 150.0,- ))],- );- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- assert_eq!(placement.content_rect, IntRect::new(100, 100, 200, 100));- assert!(placement.content_to_viewport.is_identity());- assert_eq!(placement.clip_rect, FloatRect::new(50.0, 50.0, 170.0, 100.0));- assert_eq!(placement.rounded_clip, None);- assert_eq!(placement.scaling_mode, ScalingMode::NearestNeighbor);- }-- #[test]- fn a_rounded_clip_whose_corners_miss_the_content_clips_it_as_a_rect() {- let mut tree = identity_tree();- let clip = tree.append_clip(- rounded_rect_clip(FloatRect::new(10.0, 10.0, 320.0, 240.0), CornerRadii::uniform(16)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- // The clip is in another space than the content, as a scroller's is, and the corners are above and below the- // letterboxed picture.- let scrolled = tree.append_spatial_under(- ContextRef {- clip,- ..ContextRef::default()- },- transform(FloatMatrix4x4::identity()),- );- let list = TestList::new().with(canvas(IntRect::new(10, 40, 320, 180)), scrolled);- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- assert_eq!(placement.clip_rect, FloatRect::new(10.0, 10.0, 320.0, 240.0));- assert_eq!(placement.rounded_clip, None);+ format!(+ "{anchor_kind_name}@{} in {}",+ node_namer.name_of_spatial_node(raster_space.anchor),+ self.name_of_space(raster_space.parent_index, node_namer)+ )}- #[test]- fn a_rounded_clip_that_cuts_the_content_keeps_its_radius_and_corners() {- let mut tree = identity_tree();- let mut corner_radii = CornerRadii::uniform(8);- corner_radii.bottom_left = Default::default();- let scaled = tree.append_spatial_under(ContextRef::default(), transform(scale_matrix(2.0, 2.0, 1.0)));- let list = TestList::new().with_inline_clips(- canvas(IntRect::new(10, 10, 100, 50)),- scaled,- &[PendingInlineClip::intersecting_rounded_rect(- FloatRect::new(10.0, 10.0, 100.0, 50.0),- corner_radii,- )],- );- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- assert_eq!(placement.clip_rect, FloatRect::new(20.0, 20.0, 200.0, 100.0));- let rounded_clip = placement.rounded_clip.unwrap();- assert_eq!(rounded_clip.rect, FloatRect::new(20.0, 20.0, 200.0, 100.0));- assert_eq!(rounded_clip.radius, 16.0);- assert_eq!(- rounded_clip.rounded_corners,- crate::display_list::window_server_placement::RoundedCorners {- top_left: true,- top_right: true,- bottom_right: true,- bottom_left: false,+ fn name_of_node(&self, node_index: PlacementNodeIndex, node_namer: &dyn VisualContextNodeNamer) -> String {+ let mut name = self.name_of_space(self.nodes[node_index.0].raster_space_index, node_namer);+ let mut node_on_way_out = Some(node_index);+ while let Some(index) = node_on_way_out {+ if let Some(effect) = self.nodes[index.0].composited_effect {+ name.push_str(&format!(" inside {}", node_namer.name_of_effect_node(effect)));}- );+ node_on_way_out = self.nodes[index.0].parent_index;+ }+ name+ }++ // The layer right below a layer above a cut is the layer of the cut's canvas, video or nested context, or the+ // topmost layer of the cut's nested band.+ fn name_of_barrier_below(&self, layer_index: LayerIndex, node_namer: &dyn VisualContextNodeNamer) -> String {+ let layer_below = &self.layers[layer_index.0 - 1];+ match layer_below.identity {+ LayerIdentity::Media { .. } => format!("L{}", layer_index.0 - 1),+ LayerIdentity::Painted { .. } => {+ let nested_band = &self.bands[layer_below.band_index.0];+ format!(+ "band {} of {}",+ nested_band.band_ordinal_in_node,+ self.name_of_node(nested_band.placement_node_index, node_namer)+ )+ }+ }}- #[test]- fn a_rotated_canvas_under_a_clip_of_an_unrotated_box_is_shown_by_the_window_server() {- let mut tree = identity_tree();- let clip = tree.append_clip(- ClipNodeData::rect_clip(FloatRect::new(0.0, 0.0, 400.0, 300.0)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- let rotated = tree.append_spatial_under(- ContextRef {- clip,- ..ContextRef::default()- },- transform(rotation_matrix([0.0, 0.0, 1.0], std::f32::consts::FRAC_PI_2)),- );- let list = TestList::new().with(canvas(IntRect::new(100, -300, 200, 100)), rotated);- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- let [a, b, c, d, _, _] = placement.content_to_viewport.values;- assert!(a.abs() < 1e-6 && (b - 1.0).abs() < 1e-6 && (c + 1.0).abs() < 1e-6 && d.abs() < 1e-6);- assert_eq!(placement.clip_rect, FloatRect::new(0.0, 0.0, 400.0, 300.0));+ /// What the dump calls a layer: its index, what it holds, the space it is rastered in and the effects the+ /// compositor composites it inside, and what it sits above.+ pub fn name_of_layer(&self, layer_index: LayerIndex, node_namer: &dyn VisualContextNodeNamer) -> String {+ if self.why_list_is_one_layer.is_some() {+ return "[L0] single layer replaying the whole list".into();+ }+ let index = layer_index.0;+ let layer = &self.layers[index];+ let node_name = self.name_of_node(layer.placement_node_index, node_namer);+ match (&layer.identity, &layer.content) {+ (+ LayerIdentity::Painted {+ band_ordinal_in_node,+ above_barrier,+ ..+ },+ _,+ ) => {+ let kind = if layer_index == self.base_layer {+ "base"+ } else {+ "painted"+ };+ let mut name = format!("[L{index}] {kind} space={node_name}");+ if *band_ordinal_in_node != 0 {+ name.push_str(&format!(" band={band_ordinal_in_node}"));+ }+ if above_barrier.is_some() {+ name.push_str(&format!(+ " above {}",+ self.name_of_barrier_below(layer_index, node_namer)+ ));+ }+ name+ }+ (LayerIdentity::Media { content, ordinal }, _) => {+ let reach = layer.reach;+ format!(+ "[L{index}] {} #{ordinal} space={node_name} region=[{},{} {}x{}]",+ media_name(*content),+ reach.x,+ reach.y,+ reach.width,+ reach.height+ )+ }+ }}+}- #[test]- fn a_clip_in_the_rotated_space_of_a_video_that_leaves_it_whole_needs_no_layer() {- let mut tree = identity_tree();- let rotated =- tree.append_spatial_under(ContextRef::default(), transform(rotation_matrix([0.0, 0.0, 1.0], 0.3)));- let list = TestList::new().with_inline_clips(- canvas(IntRect::new(100, 100, 200, 100)),- rotated,- &[PendingInlineClip::intersecting_rounded_rect(- FloatRect::new(100.0, 80.0, 200.0, 140.0),- CornerRadii::uniform(10),- )],- );- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- assert_eq!(placement.clip_rect, VIEWPORT.to_float());- assert_eq!(placement.rounded_clip, None);- }+/// What of a tree and its list keeps the tiles of its layers from replaying only the records that reach them, or keeps+/// the list from being layered, at some sample of the animations of the tree.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct LayeringObstacles {+ pub sorts_planes_by_depth: bool,+ pub mask_declared_under_effects_its_mask_is_not_under: bool,+}- #[test]- fn a_clip_around_a_canvas_that_its_inline_transform_moves_out_of_stays() {- let tree = identity_tree();- let mut builder = DisplayListBuilder::new();- builder.append_with_inline_state(- &canvas(IntRect::new(0, 0, 100, 100)),- &[],- ContextRef::default(),- &[PendingInlineClip::intersecting_float_rect(FloatRect::new(- 0.0, 0.0, 100.0, 100.0,- ))],- Some(AffineTransform::identity().translated(20.0, 0.0)),- );- let list = TestList { builder };- let placement = placement_of_only_media_layer(&list.plan(&tree, &[]).unwrap()).unwrap();- assert_eq!(placement.clip_rect, FloatRect::new(0.0, 0.0, 100.0, 100.0));- assert_eq!(placement.content_to_viewport.values, [1.0, 0.0, 0.0, 1.0, 20.0, 0.0]);+impl LayeringObstacles {+ pub fn of(list: &DisplayListStorage, tree: &VisualContextTree) -> Self {+ Self::of_with_nesting_of_live_effects(list, tree, &NestingOfLiveEffects::of(tree))}- #[test]- fn media_layers_that_the_window_server_cannot_clip_are_replayed() {- let rejection_for = |tree: &VisualContextTree, context: ContextRef, inline_clips: &[PendingInlineClip]| {- let list =- TestList::new().with_inline_clips(canvas(IntRect::new(100, 100, 200, 100)), context, inline_clips);- placement_of_only_media_layer(&list.plan(tree, &[]).unwrap()).unwrap_err()- };- let tree = identity_tree();- let root = ContextRef::default();- let content = FloatRect::new(100.0, 100.0, 200.0, 100.0);-- let mut triangle = libgfx_rust::path::Path::new();- triangle.move_to(FloatPoint { x: 100.0, y: 100.0 });- triangle.line_to(FloatPoint { x: 300.0, y: 100.0 });- triangle.line_to(FloatPoint { x: 100.0, y: 200.0 });- triangle.close();- assert_eq!(- rejection_for(- &tree,- root,- &[PendingInlineClip::intersecting_path(- &triangle,- libgfx_rust::WindingRule::Nonzero- )]- ),- WindowServerRejection::ClippedByPath- );- assert_eq!(- rejection_for(- &tree,- root,- &[PendingInlineClip::subtracting_rect(FloatRect::new(- 150.0, 120.0, 20.0, 20.0- ))]+ pub(crate) fn of_with_nesting_of_live_effects(+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+ ) -> Self {+ Self {+ sorts_planes_by_depth: tree.may_sort_planes_by_depth(),+ mask_declared_under_effects_its_mask_is_not_under: !mask_declarations_are_on_effect_chains_of_their_masks(+ list,+ nesting_of_live_effects,),- WindowServerRejection::ClippedByExcludingClip- );+ }+ }- let mut differing_radii = CornerRadii::uniform(8);- differing_radii.top_left = libgfx_rust::CornerRadius {- horizontal_radius: 12,- vertical_radius: 12,- };- assert_eq!(- rejection_for(- &tree,- root,- &[PendingInlineClip::intersecting_rounded_rect(content, differing_radii)]- ),- WindowServerRejection::RoundedCornersOfDifferingRadii- );- let mut elliptical_radii = CornerRadii::uniform(8);- elliptical_radii.bottom_right.vertical_radius = 4;- assert_eq!(- rejection_for(- &tree,- root,- &[PendingInlineClip::intersecting_rounded_rect(content, elliptical_radii)]- ),- WindowServerRejection::RoundedCornersOfDifferingRadii- );- assert_eq!(- rejection_for(- &tree,- root,- &[- PendingInlineClip::intersecting_rounded_rect(content, CornerRadii::uniform(8)),- PendingInlineClip::intersecting_rounded_rect(- FloatRect::new(90.0, 90.0, 220.0, 120.0),- CornerRadii::uniform(30)- ),- ]- ),- WindowServerRejection::MoreThanOneRoundedClip- );+ /// Whether every tile replays every record of its band, as which records can show in a tile cannot be told.+ pub fn every_tile_replays_every_record(&self) -> bool {+ self.mask_declared_under_effects_its_mask_is_not_under+ }+}- let mut tree_with_rotated_clip = identity_tree();- let rotated =- tree_with_rotated_clip.append_spatial_under(root, transform(rotation_matrix([0.0, 0.0, 1.0], 0.3)));- let clip = tree_with_rotated_clip.append_clip(- ClipNodeData::rect_clip(FloatRect::new(0.0, 0.0, 150.0, 300.0)),- ClipNodeIndex::NONE,- rotated.spatial,- );- assert_eq!(- rejection_for(&tree_with_rotated_clip, ContextRef { clip, ..rotated }, &[]),- WindowServerRejection::ClippedInRotatedOrSkewedSpace- );+// A tile replays the declaration of a mask's content along with what the mask holds, and so opens the effects the+// declaration is under there, which draw nothing only when they are the mask's own or those around it. A list from+// another process can name a mask that the tree does not hold as a live node. No effect is inside such a mask.+fn mask_declarations_are_on_effect_chains_of_their_masks(+ list: &DisplayListStorage,+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+) -> bool {+ list.summary().mask_declarations.iter().all(|declaration| {+ let mask_effect = declaration.mask_effect;+ let declaration_effect = list.run(declaration.record.run_index as usize).context.effect;+ declaration_effect.is_none()+ || nesting_of_live_effects.is_or_is_inside(declaration_effect, mask_effect)+ || nesting_of_live_effects.is_or_is_inside(mask_effect, declaration_effect)+ })+}- let mut tree_with_rounded_clip_node = identity_tree();- let rounded = tree_with_rounded_clip_node.append_clip(- rounded_rect_clip(content, CornerRadii::uniform(10)),- ClipNodeIndex::NONE,- VISUAL_VIEWPORT_NODE_INDEX,- );- assert_eq!(- rejection_for(- &tree_with_rounded_clip_node,- ContextRef { clip: rounded, ..root },- &[PendingInlineClip::intersecting_rounded_rect(- content,- CornerRadii::uniform(10)- )]- ),- WindowServerRejection::MoreThanOneRoundedClip- );- }+fn anchors_of_layer_plans(tree: &VisualContextTree) -> Vec<SpatialNodeIndex> {+ raster_space_anchors(tree, &spatial_nodes_that_move_on_their_own(tree))}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rsnew file mode 100644index 00000000000..fc358153af0--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs@@ -0,0 +1,3548 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Plans the layers of a display list. WebContent's Paint thread plans them and sends the plan to the compositor. The+//! compositor takes a plan as it is, once the plan passes the checks of its wire form, and never plans.+//!+//! A band of a nested node ends where content outside it that can show where the band can is painted, so the layers+//! stacked in paint order of their barriers paint every pixel in the order the list does, as long as nothing within a+//! layer reads what is below the layer. So a backdrop filter that finds all it reads in its own layer, where it is+//! painted, reads it there, and one that does not gets a node of its own, whose layers the compositor composites inside+//! the filter's effect as a replay of the list composites the effect, over what is composited below them. So does an+//! effect whose opacity or filter the compositor animates, so that its samples change how its layers are composited and+//! not their tiles.++use super::wire::plan_holds_more_than_compositor_decodes;+use super::{+ BandOfPlan, BarrierCut, BarrierOfPlan, CutOfPlan, LayerIndex, LayerStack, LayeredPlan, LayeringObstacles,+ MAXIMUM_MEDIA_LAYER_COUNT, MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS, NodeOfPlan, PlacementNodeIndex,+ WhyCompositorCannotCompositeEffect, WhyListIsOneLayer, media_name,+};+use crate::display_list::animated_transform_spaces::{effect_reads_below_it, spatial_nodes_under_transform_animations};+use crate::display_list::commands::{DisplayListCommandType, EffectNodeIndex, SpatialNodeIndex};+use crate::display_list::effect_geometry::{+ FiltersOfEffects, KeyframeFiltersOfEffects, backdrop_filter_read_reach, filter_may_spread_at_some_sample,+ filter_read_reach_in_device_pixels,+};+use crate::display_list::placement::{+ CompositeClip, FiltersAndClipsOfList, RasterSpace, RasterSpaceAnchorKind, RasterSpaceGeometry, RasterSpaceIndex,+ RunGroupIndex, RunGroups, enclosing_int_rect_within_extent_limit, is_finite_rect,+};+use crate::display_list::reach::Reach;+use crate::display_list::storage::{DisplayListStorage, ListPosition, ListSpan, RunIndexInList};+use crate::display_list::summary::{IndexedRecord, LiveContent};+use crate::display_list::tiles::{CellRange, reaches_too_many_cells_to_follow_one_by_one, tile_coords_touching};+use crate::visual_context::queries::{BackdropReader, NestingOfLiveEffects, backdrop_reader_by_reading_effect_index};+use crate::visual_context::{EffectNodeData, VisualContextTree};+use libgfx_rust::{FloatPoint, FloatRect, IntRect};+use std::hash::Hash;+use std::sync::Arc;++mod lines_of_plan;+mod placement_tables;+mod raster_spaces_for_placing;++use placement_tables::{PlacementTables, RunsReachingOutsideTheirContext, lowest_common_ancestor_space};+use raster_spaces_for_placing::{+ RasterSpaceAnchorsOfTree, RasterSpaceGeometryForPlacing, RasterSpacesForPlacing, rect_swept_over_translations,+ spaces_with_geometries,+};++/// How many effects whose opacity or filter the compositor animates get layers of their own, first in paint order.+pub const MAXIMUM_ANIMATED_NODES_WITH_LAYERS: usize = 32;++/// A node whose values the compositor animates: a spatial node it transforms, or an effect node whose opacity or+/// filter it changes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AnimatedNode {+ Transform(SpatialNodeIndex),+ Effect(EffectNodeIndex),+}++/// Why what the compositor animates stays in the tiles of the layers around it, which it keys anew as it changes,+/// rather than getting layers of its own.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WhyAnimationHasNoLayer {+ InsideAnEffectTheCompositorCannotComposite(WhyCompositorCannotCompositeEffect),+ ItsFilterSpreadsWhatItFilters,+ ItHoldsAnEffectThatReadsWhatIsBelowIt,+ ItHoldsRecordsThatBlendWithWhatIsBelowThem,+ SortedByDepthInA3DSortingContext,+ NothingBoundsWhereItMoves,+ ItCanShowOverAnEarlierCanvasOrVideo,+ MoreAnimationsThanLayersFor,+}++impl std::fmt::Display for WhyAnimationHasNoLayer {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ WhyAnimationHasNoLayer::InsideAnEffectTheCompositorCannotComposite(why) => {+ return write!(formatter, "inside a {why}");+ }+ WhyAnimationHasNoLayer::ItsFilterSpreadsWhatItFilters => "its filter spreads what it filters",+ WhyAnimationHasNoLayer::ItHoldsAnEffectThatReadsWhatIsBelowIt => {+ "it holds an effect that reads what is below it"+ }+ WhyAnimationHasNoLayer::ItHoldsRecordsThatBlendWithWhatIsBelowThem => {+ "it holds records that blend with what is below them"+ }+ WhyAnimationHasNoLayer::SortedByDepthInA3DSortingContext => "sorted by depth in a 3D sorting context",+ WhyAnimationHasNoLayer::NothingBoundsWhereItMoves => "nothing bounds where it moves",+ WhyAnimationHasNoLayer::ItCanShowOverAnEarlierCanvasOrVideo => {+ "it can show over an earlier canvas or video"+ }+ WhyAnimationHasNoLayer::MoreAnimationsThanLayersFor => "past the most animations that get layers",+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WhyMediaHasNoLayer {+ DrawnInsideAnotherCommand,+ UnderTransformThatIsNot2DAffine,+ DrawsNothingVisible,+ MoreMediaThanLayersFor,+ SortedByDepthInA3DSortingContext,+ InsideAnEffectTheCompositorCannotComposite(WhyCompositorCannotCompositeEffect),+}++impl std::fmt::Display for WhyMediaHasNoLayer {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ WhyMediaHasNoLayer::DrawnInsideAnotherCommand => "drawn inside another command",+ WhyMediaHasNoLayer::UnderTransformThatIsNot2DAffine => "under a transform that is not 2D affine",+ WhyMediaHasNoLayer::DrawsNothingVisible => "draws nothing visible",+ WhyMediaHasNoLayer::MoreMediaThanLayersFor => "past the most media that get layers",+ WhyMediaHasNoLayer::SortedByDepthInA3DSortingContext => "sorted by depth in a 3D sorting context",+ WhyMediaHasNoLayer::InsideAnEffectTheCompositorCannotComposite(why) => {+ return write!(formatter, "inside a {why}");+ }+ })+ }+}++/// Why the compositor composites the layers of an effect's content inside the effect, as a replay of the list+/// composites the effect, rather than tiles holding the effect.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WhyEffectIsComposited {+ ItReadsWhatItsOwnLayerDoesNotHold,+ ItsBackdropFilterReadsPastTheEdgeOfTheFrame,+ ItHoldsAnEffectTheCompositorComposites,+ ItHoldsMedia(LiveContent),+ TheCompositorAnimatesIt,+ ItAppliesOverATransformTheCompositorAnimates,+}++impl std::fmt::Display for WhyEffectIsComposited {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ WhyEffectIsComposited::ItReadsWhatItsOwnLayerDoesNotHold => "it reads what its own layer does not hold",+ WhyEffectIsComposited::ItsBackdropFilterReadsPastTheEdgeOfTheFrame => {+ "its backdrop filter reads past the edge of the frame"+ }+ WhyEffectIsComposited::ItHoldsAnEffectTheCompositorComposites => {+ "it holds an effect the compositor composites"+ }+ WhyEffectIsComposited::ItHoldsMedia(content) => {+ return write!(formatter, "it holds a {} with a layer of its own", media_name(*content));+ }+ WhyEffectIsComposited::TheCompositorAnimatesIt => "the compositor animates it",+ WhyEffectIsComposited::ItAppliesOverATransformTheCompositorAnimates => {+ "it applies over a transform the compositor animates"+ }+ })+ }+}++/// A plan of the layers of a list: the stack the compositor composites frames from, and where the parts of the list+/// are placed among the spaces of the stack, which only the dump and the tests read.+#[derive(Clone, Debug, PartialEq)]+pub struct PlannedLayers {+ pub stack: LayerStack,+ pub placement: ListPlacement,+}++/// What a plan of the layers of a list reads, all of which WebContent publishes.+pub struct LayerStackInputs<'a> {+ pub list: &'a DisplayListStorage,+ /// The tree as WebContent published it, without the samples of the compositor's animations and without a visual+ /// viewport transform of the compositor's.+ pub tree: &'a VisualContextTree,+ /// The scroll offsets WebContent published with the tree. A plan reads only those that+ /// `RasterSpaceAnchorsOfTree::leaves_out_scroll_offset_of_node` does not name.+ pub scroll_offsets: &'a [FloatPoint],+ /// The viewport in device pixels.+ pub viewport_rect: IntRect,+}++// An animation of the opacity or filter of the root isolation effect makes it more than a plain group at some sample.+fn root_isolation_effect_is_plain_group(tree: &VisualContextTree) -> bool {+ let Some(root) = tree.root_isolation_effect else {+ return true;+ };+ match &tree.effect_nodes[root.0 as usize].data {+ EffectNodeData::Effects(effects) => {+ effects.opacity == 1.0+ && effects.blend_mode == libgfx_rust::CompositingAndBlendingOperator::Normal+ && effects.filter.is_none()+ && effects.backdrop_filter.is_none()+ && !tree.effect_opacity_or_filter_is_animated(root)+ }+ _ => false,+ }+}++/// Why a list cannot be layered at all.+fn why_list_cannot_be_layered(+ inputs: &LayerStackInputs<'_>,+ layering_obstacles: &LayeringObstacles,+) -> Option<WhyListIsOneLayer> {+ if inputs.viewport_rect.is_empty() {+ return Some(WhyListIsOneLayer::EmptyViewport);+ }+ if inputs.list.run_count() == 0 {+ return Some(WhyListIsOneLayer::EmptyDisplayList);+ }+ if !root_isolation_effect_is_plain_group(inputs.tree) {+ return Some(WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup);+ }+ if layering_obstacles.mask_declared_under_effects_its_mask_is_not_under {+ return Some(WhyListIsOneLayer::MaskDeclaredUnderEffectsItsMaskIsNotUnder);+ }+ None+}++/// A group of runs, which is placed whole, with where it is placed.+#[derive(Clone, Debug, PartialEq)]+pub struct PlacedRunGroup {+ pub raster_space_index: RasterSpaceIndex,+ /// At most one per space, ordered by space.+ pub composite_clips: Vec<CompositeClip>,+ /// Where it can show in the space's raster coordinates, under the values the frame shows, except that content+ /// that moves on its own is taken to be anywhere its fixed clips let it show.+ pub reach: IntRect,+ pub moves_within_space: bool,+ /// Whether the group paints within the root group, rather than below it as the canvas background is.+ pub paints_within_root_group: bool,+ /// In the space's raster coordinates.+ pub reach_read_by_records_blending_with_root_group: Reach<IntRect>,+}++/// The index of a placed effect in `ListPlacement::placed_effects`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct PlacedEffectIndex(pub usize);++/// The index of a content in `ListPlacement::placed_media`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct PlacedMediaIndex(pub usize);++/// A stretch of records of one run group that is placed as one: the records of the run group's runs that are inside+/// the same effects the compositor can composite, or the runs of a content that is a layer of its own, which hold it+/// alone and may span run groups.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlacedRecordStretch {+ pub record_span: ListSpan,+ /// The run group of its first run.+ pub run_group_index: RunGroupIndex,+ /// Where the records can show, in the raster coordinates of the run group's space: where the innermost placed+ /// effect around them can draw, if there is one.+ pub reach: IntRect,+ pub placed_media_index: Option<PlacedMediaIndex>,+ /// The innermost effect the compositor can composite the stretch's records inside.+ pub placed_effect_index: Option<PlacedEffectIndex>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+struct RecordStretchIndex(usize);++/// An effect whose content the compositor composites inside it, or may where the content does not find all it reads+/// in the layer it goes into, with where it is placed.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlacedEffect {+ pub effect: EffectNodeIndex,+ /// The placed effect around it, inside which the compositor composites it.+ pub placed_effect_around_index: Option<PlacedEffectIndex>,+ /// Where compositing the effect can draw, in the raster coordinates of the run group's space: wherever the runs+ /// under it in the run group of its first run can show, and if it moves within its space, wherever it can show.+ pub reach: IntRect,+ /// What it reads of what is composited below it there.+ pub backdrop_read_reach: Reach<IntRect>,+ /// None for an effect placed only as it reads the content of the root group, which the bands it can read are only+ /// known of as the stack is cut into them.+ pub why_composited_regardless_of_layer_content: Option<WhyEffectIsComposited>,+}++/// A canvas, video or nested context that is a layer of its own, alone in its run.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlacedMedia {+ pub content: LiveContent,+ /// How many drawings of the same content are painted before it.+ pub ordinal: u32,+ pub record_span: ListSpan,+ pub run_index: RunIndexInList,+ /// Where it can show, in the raster coordinates of the space of its run's group.+ pub reach: IntRect,+}++/// Where each part of a list is placed at the spaces a tree offers, under the values a frame shows. What it decides+/// holds for every sample of the animations of the tree.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct ListPlacement {+ pub run_groups: Vec<PlacedRunGroup>,+ pub record_stretches: Vec<PlacedRecordStretch>,+ /// In paint order.+ pub placed_media: Vec<PlacedMedia>,+ pub media_without_layers: Vec<(LiveContent, WhyMediaHasNoLayer)>,+ pub animations_without_layers: Vec<(AnimatedNode, WhyAnimationHasNoLayer)>,+ /// In paint order, each after the one around it.+ pub placed_effects: Vec<PlacedEffect>,+ /// The nodes that read the backdrop of a backdrop filter or a blend mode, in paint order.+ pub backdrop_readers_in_paint_order: Vec<EffectNodeIndex>,+ pub why_compositor_cannot_composite_by_effect_index: Vec<Option<WhyCompositorCannotCompositeEffect>>,+}++fn one_composite_clip_per_space_sorted_by_space(clips: &[CompositeClip]) -> Vec<CompositeClip> {+ let mut clip_per_space: Vec<CompositeClip> = Vec::with_capacity(clips.len());+ for clip in clips {+ match clip_per_space+ .iter_mut()+ .find(|clip_of_same_space| clip_of_same_space.raster_space_index == clip.raster_space_index)+ {+ Some(clip_of_same_space) => clip_of_same_space.rect = clip_of_same_space.rect.intersected(clip.rect),+ None => clip_per_space.push(*clip),+ }+ }+ clip_per_space.sort_by_key(|clip| clip.raster_space_index);+ clip_per_space+}++// Marks in each of `marks_by_effect_index` every effect node that holds a node marked there, in one walk of the tree.+fn mark_effects_around_marked_effects<const MARK_KIND_COUNT: usize>(+ tree: &VisualContextTree,+ marks_by_effect_index: &mut [Vec<bool>; MARK_KIND_COUNT],+) {+ let mut live_effects_parents_first = Vec::with_capacity(tree.effect_nodes.len());+ tree.visit_effect_nodes_parents_first(|index| live_effects_parents_first.push(index));+ for &index in live_effects_parents_first.iter().rev() {+ let parent = tree.effect_nodes[index].parent;+ if parent.is_none() {+ continue;+ }+ for marked_by_effect_index in marks_by_effect_index.iter_mut() {+ if marked_by_effect_index[index] {+ marked_by_effect_index[parent.0 as usize] = true;+ }+ }+ }+}++// Marks the effect of each run that `marks_run` marks.+fn effects_of_marked_runs(+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ marks_run: impl Fn(usize) -> bool,+) -> Vec<bool> {+ let mut marked_by_effect_index = vec![false; tree.effect_nodes.len()];+ for (run_index, run) in list.runs().enumerate() {+ if !run.context.effect.is_none() && marks_run(run_index) {+ marked_by_effect_index[run.context.effect.0 as usize] = true;+ }+ }+ marked_by_effect_index+}++// Per effect node, whether it is or holds the effect of a run sorted by depth, of a record that blends with what is+// below it, or an effect that reads what is below it.+struct WhatEffectsHold {+ run_sorted_by_depth_by_effect_index: Vec<bool>,+ records_blending_with_what_is_below_them_by_effect_index: Vec<bool>,+ effect_reading_what_is_below_it_by_effect_index: Vec<bool>,+}++// Why each effect is composited whatever its layers hold, and the effects that are, in the order they became so.+struct WhyEffectsAreCompositedRegardlessOfLayerContent {+ why_by_effect_index: Vec<Option<WhyEffectIsComposited>>,+ composited_effects: Vec<EffectNodeIndex>,+}++impl WhyEffectsAreCompositedRegardlessOfLayerContent {+ fn set(&mut self, effect: EffectNodeIndex, why: WhyEffectIsComposited) {+ let why_composited = &mut self.why_by_effect_index[effect.0 as usize];+ if why_composited.is_none() {+ self.composited_effects.push(effect);+ }+ *why_composited = Some(why);+ }++ fn set_unless_composited(&mut self, effect: EffectNodeIndex, why: WhyEffectIsComposited) {+ if self.why_by_effect_index[effect.0 as usize].is_none() {+ self.set(effect, why);+ }+ }++ fn mark_effects_around_as_composited(+ &mut self,+ tree: &VisualContextTree,+ mut effect_around: EffectNodeIndex,+ why: WhyEffectIsComposited,+ ) {+ while !effect_around.is_none() && tree.root_isolation_effect != Some(effect_around) {+ if tree.effect_pushes_layer_at_replay(effect_around) {+ self.set_unless_composited(effect_around, why);+ }+ effect_around = tree.effect_nodes[effect_around.0 as usize].parent;+ }+ }+}++/// Whether a backdrop filter reads nothing past each pixel, or only through blurs that mirror at the edge of what they+/// read, so that what it reads past the edge of the frame does not show.+fn backdrop_filter_reads_nothing_past_mirrored_edge(filter: &[u8]) -> bool {+ let probe = FloatRect::new(0.0, 0.0, 1.0, 1.0);+ let reads_past_each_pixel = crate::filter_bytes::changed_output_bounds(filter, probe) != Some(probe);+ !reads_past_each_pixel || libgfx_rust::filter::Filter::serialized_has_mirroring_blur(filter)+}++/// Where each part of the list is placed among `spaces`, given the geometry of each of them, with what the stack holds+/// per space of them: `LayerStack::swept_reach_in_parent_space_by_space_index` and+/// `LayerStack::tiles_hold_content_moving_within_space_by_space_index`.+fn place_list(+ inputs: &LayerStackInputs<'_>,+ spaces: RasterSpacesForPlacing,+ geometries: &[RasterSpaceGeometryForPlacing],+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+) -> (ListPlacement, Vec<Option<IntRect>>, Vec<bool>) {+ let tree = inputs.tree;+ // Placing decides for the filter that the tree holds and for each filter that an animation can give the effect.+ let filters_at_some_sample = FiltersOfEffects::of(tree, None, true);+ let filters_and_clips = FiltersAndClipsOfList {+ tree,+ filters: &filters_at_some_sample,+ effect_clips: inputs.list.effect_clip_plan(tree),+ };+ let placing = ListBeingPlaced::new(inputs, spaces, geometries, nesting_of_live_effects, filters_and_clips);+ let (runs, mut animations_without_layers) = placing.place_run_groups();+ let (placed_media, media_without_layers) = placing.place_media(&runs);+ let mut why_composited_regardless_of_layer_content =+ placing.effects_composited_regardless_of_layer_content(&runs, &placed_media, &mut animations_without_layers);+ let (backdrop_read_reach_by_effect_index, backdrop_readers_in_paint_order, reads_root_group_by_effect_index) =+ placing.note_backdrop_readers(&runs, &placed_media, &mut why_composited_regardless_of_layer_content);+ let (placed_effects, innermost_placed_effect_at_or_around_by_effect_index) = placing.place_effects(+ &runs,+ &why_composited_regardless_of_layer_content,+ &backdrop_read_reach_by_effect_index,+ &reads_root_group_by_effect_index,+ );+ let (record_stretches, tiles_hold_content_moving_within_space_by_space_index) = placing.place_record_stretches(+ &runs,+ &placed_media,+ &placed_effects,+ &innermost_placed_effect_at_or_around_by_effect_index,+ );+ let placement = ListPlacement {+ run_groups: runs.groups,+ record_stretches,+ placed_media,+ media_without_layers,+ animations_without_layers,+ placed_effects,+ backdrop_readers_in_paint_order,+ why_compositor_cannot_composite_by_effect_index: placing.why_compositor_cannot_composite_by_effect_index,+ };+ (+ placement,+ runs.swept_reach_in_parent_space_by_space_index,+ tiles_hold_content_moving_within_space_by_space_index,+ )+}++fn is_animated_space(space: &RasterSpace) -> bool {+ matches!(space.anchor_kind, RasterSpaceAnchorKind::AnimatedTransform { .. })+}++// What placing a list reads: its inputs, and what is worked out of them alone before anything is placed.+struct ListBeingPlaced<'a> {+ tree: &'a VisualContextTree,+ list: &'a DisplayListStorage,+ run_groups: Arc<RunGroups>,+ tables: PlacementTables,+ geometries: &'a [RasterSpaceGeometryForPlacing],+ nesting_of_live_effects: &'a NestingOfLiveEffects<'a>,+ filters_and_clips: FiltersAndClipsOfList<'a>,+ some_space_is_animated: bool,+ why_compositor_cannot_composite_by_effect_index: Vec<Option<WhyCompositorCannotCompositeEffect>>,+ why_compositor_cannot_composite_effect_or_effect_around_by_effect_index:+ std::cell::OnceCell<Vec<Option<WhyCompositorCannotCompositeEffect>>>,+ backdrop_reader_by_effect_index: Vec<Option<BackdropReader>>,+ first_run_index_by_effect_index: Vec<usize>,+ effects_in_paint_order_with_outer_before_inner: Vec<EffectNodeIndex>,+}++// What placing the run groups of a list works out, which the phases after it read.+struct RunGroupsPlaced {+ groups: Vec<PlacedRunGroup>,+ reach_of_run_by_run_index: Vec<IntRect>,+ run_moves_within_space_by_run_index: Vec<bool>,+ swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>>,+ reach_by_effect_index_once_worked_out: std::cell::OnceCell<Vec<IntRect>>,+}++impl<'a> ListBeingPlaced<'a> {+ fn new(+ inputs: &LayerStackInputs<'a>,+ spaces: RasterSpacesForPlacing,+ geometries: &'a [RasterSpaceGeometryForPlacing],+ nesting_of_live_effects: &'a NestingOfLiveEffects<'a>,+ filters_and_clips: FiltersAndClipsOfList<'a>,+ ) -> Self {+ let (tree, list) = (inputs.tree, inputs.list);+ let mut tables = PlacementTables::new(tree, spaces, geometries);+ let some_space_is_animated = tables.spaces().iter().any(is_animated_space);+ if some_space_is_animated {+ tables.note_animated_spaces_holding_every_run_of_effects(tree, list);+ }+ let keyframe_filters = KeyframeFiltersOfEffects::of(tree);+ // A space whose anchor the compositor animates rasters at a scale of its own, so how far a filter reads in the+ // pixels of tiles is told by the deepest space of the filter. Where a transform the compositor animates within+ // that space scales the filter, it is not known.+ let why_compositor_cannot_composite_by_effect_index: Vec<Option<WhyCompositorCannotCompositeEffect>> = tree+ .effect_nodes+ .iter()+ .enumerate()+ .map(|(index, effect_node)| {+ let effect = EffectNodeIndex(index as u32);+ if keyframe_filters.filter_may_move_what_it_filters(tree, effect) {+ return Some(WhyCompositorCannotCompositeEffect::FilterMovesWhatItFilters);+ }+ if !filter_may_spread_at_some_sample(tree, effect) {+ return None;+ }+ let deepest_space = tables.deepest_space_of(effect_node.spatial);+ let read_reach_in_device_pixels = (!tables+ .animation_samples_move_spatial_within_space(effect_node.spatial, deepest_space))+ .then(|| {+ keyframe_filters.filter_read_reach_in_device_pixels(+ tree,+ effect,+ &geometries[deepest_space.0]+ .raster+ .world+ .draw_matrix(effect_node.spatial),+ )+ })+ .flatten();+ read_reach_in_device_pixels+ .is_none()+ .then_some(WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed)+ })+ .collect();+ let mut first_run_index_by_effect_index = vec![usize::MAX; tree.effect_nodes.len()];+ let mut effects_in_paint_order_with_outer_before_inner = Vec::new();+ for run_index in 0..list.run_count() {+ let mut effect = list.run(run_index).context.effect;+ let mut newly_reached_effects_inner_to_outer = Vec::new();+ while !effect.is_none() && first_run_index_by_effect_index[effect.0 as usize] == usize::MAX {+ first_run_index_by_effect_index[effect.0 as usize] = run_index;+ newly_reached_effects_inner_to_outer.push(effect);+ effect = tree.effect_nodes[effect.0 as usize].parent;+ }+ effects_in_paint_order_with_outer_before_inner+ .extend(newly_reached_effects_inner_to_outer.into_iter().rev());+ }+ Self {+ tree,+ list,+ run_groups: list.run_groups(tree),+ tables,+ geometries,+ nesting_of_live_effects,+ filters_and_clips,+ some_space_is_animated,+ why_compositor_cannot_composite_by_effect_index,+ why_compositor_cannot_composite_effect_or_effect_around_by_effect_index: std::cell::OnceCell::new(),+ backdrop_reader_by_effect_index: backdrop_reader_by_reading_effect_index(tree),+ first_run_index_by_effect_index,+ effects_in_paint_order_with_outer_before_inner,+ }+ }++ // The walk up from an effect stops at the root isolation effect, which holds no reason.+ fn why_compositor_cannot_composite_effect_or_effects_around(+ &self,+ effect: EffectNodeIndex,+ ) -> Option<WhyCompositorCannotCompositeEffect> {+ let tree = self.tree;+ self.why_compositor_cannot_composite_effect_or_effect_around_by_effect_index+ .get_or_init(|| {+ let mut why_by_effect_index: Vec<Option<WhyCompositorCannotCompositeEffect>> =+ vec![None; tree.effect_nodes.len()];+ tree.visit_effect_nodes_parents_first(|index| {+ if tree.root_isolation_effect == Some(EffectNodeIndex(index as u32)) {+ return;+ }+ let parent = tree.effect_nodes[index].parent;+ why_by_effect_index[index] = self.why_compositor_cannot_composite_by_effect_index[index]+ .or_else(|| why_by_effect_index.get(parent.0 as usize).copied().flatten());+ });+ why_by_effect_index+ })+ .get(effect.0 as usize)+ .copied()+ .flatten()+ }++ fn run_group_of_effect(&self, effect: EffectNodeIndex) -> RunGroupIndex {+ self.run_groups+ .group_of_run(self.first_run_index_by_effect_index[effect.0 as usize])+ }++ fn space_of_run(&self, runs: &RunGroupsPlaced, run_index: usize) -> RasterSpaceIndex {+ runs.groups[self.run_groups.group_of_run(run_index).0].raster_space_index+ }++ fn reach_of_effect(&self, runs: &RunGroupsPlaced, effect: EffectNodeIndex) -> IntRect {+ let (tree, list) = (self.tree, self.list);+ runs.reach_by_effect_index_once_worked_out.get_or_init(|| {+ let mut reach_by_effect_index = vec![IntRect::default(); tree.effect_nodes.len()];+ for (run_index, &reach_of_run) in runs.reach_of_run_by_run_index.iter().enumerate() {+ let mut effect = list.run(run_index).context.effect;+ while !effect.is_none() {+ if self.run_group_of_effect(effect) == self.run_groups.group_of_run(run_index) {+ let reach_of_effect = &mut reach_by_effect_index[effect.0 as usize];+ *reach_of_effect = reach_of_effect.united(reach_of_run);+ }+ effect = tree.effect_nodes[effect.0 as usize].parent;+ }+ }+ reach_by_effect_index+ })[effect.0 as usize]+ }++ fn place_run_groups(&self) -> (RunGroupsPlaced, Vec<(AnimatedNode, WhyAnimationHasNoLayer)>) {+ let (tree, list, tables, run_groups) = (self.tree, self.list, &self.tables, &*self.run_groups);+ let spaces = tables.spaces();+ let runs_reaching_outside = RunsReachingOutsideTheirContext::new(list);+ let mut run_blends_with_root_group_by_run_index = vec![false; list.run_count()];+ for record in &list.summary().destination_blending_records {+ let effect = list.run(record.run_index as usize).context.effect;+ if tree.content_under_effect_composites_into_root_group(effect) {+ run_blends_with_root_group_by_run_index[record.run_index as usize] = true;+ }+ }+ let mut reach_of_run_by_run_index = vec![IntRect::default(); list.run_count()];+ let mut run_moves_within_space_by_run_index = vec![false; list.run_count()];++ let mut runs_of_animated_space_by_space_index: Vec<Vec<usize>> = vec![Vec::new(); spaces.len()];+ if self.some_space_is_animated {+ for run_index in 0..list.run_count() {+ let space = tables.deepest_space_of(list.run(run_index).context.spatial);+ if is_animated_space(&spaces[space.0]) {+ runs_of_animated_space_by_space_index[space.0].push(run_index);+ }+ }+ }+ let mut animated_space_is_decided = vec![false; spaces.len()];+ let mut swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>> = vec![None; spaces.len()];+ let mut animations_without_layers: Vec<(AnimatedNode, WhyAnimationHasNoLayer)> = Vec::new();++ let mut placed_run_groups: Vec<PlacedRunGroup> =+ Vec::with_capacity(run_groups.first_and_last_run_of_groups().len());+ for &(first_run_index, last_run_index) in run_groups.first_and_last_run_of_groups() {+ if self.some_space_is_animated {+ for run_index in first_run_index as usize..=last_run_index as usize {+ let space = tables.deepest_space_of(list.run(run_index).context.spatial);+ if !is_animated_space(&spaces[space.0]) || animated_space_is_decided[space.0] {+ continue;+ }+ animated_space_is_decided[space.0] = true;+ let canvases_and_videos_placed_before = list+ .summary()+ .live_content_records+ .iter()+ .filter(|media| matches!(media.content, LiveContent::Canvas(_) | LiveContent::VideoFrame(_)))+ .filter_map(|media| {+ let media_run_index = media.record.run_index as usize;+ let placed_group = placed_run_groups.get(run_groups.group_of_run(media_run_index).0)?;+ Some((+ placed_group.raster_space_index,+ reach_of_run_by_run_index[media_run_index],+ ))+ });+ match self.swept_reach_of_animated_space_in_parent_space(+ space,+ &runs_of_animated_space_by_space_index[space.0],+ canvases_and_videos_placed_before,+ ) {+ Ok(swept_reach) => swept_reach_in_parent_space_by_space_index[space.0] = Some(swept_reach),+ Err(why_no_layer) => {+ tables.refuse_animated_space(space);+ animations_without_layers+ .push((AnimatedNode::Transform(spaces[space.0].anchor), why_no_layer));+ }+ }+ }+ }+ placed_run_groups.push({+ let run_indices = first_run_index as usize..=last_run_index as usize;+ let mut raster_space_index = run_indices+ .clone()+ .map(|run_index| {+ runs_reaching_outside.deepest_space_of_run(tree, tables, run_index, list.run(run_index))+ })+ .reduce(|first, second| lowest_common_ancestor_space(spaces, first, second))+ .unwrap_or(RasterSpaceIndex::VIEWPORT);+ let composite_clips = loop {+ let mut clips_of_runs = run_indices.clone().map(|run_index| {+ runs_reaching_outside.composite_clips_of_run_in(+ tree,+ tables,+ run_index,+ list.run(run_index),+ raster_space_index,+ )+ });+ let first_clips = clips_of_runs.next().flatten();+ if let Some(first_clips) = first_clips+ && clips_of_runs.all(|clips| clips.as_deref() == Some(&*first_clips))+ {+ break one_composite_clip_per_space_sorted_by_space(&first_clips);+ }+ if raster_space_index == RasterSpaceIndex::VIEWPORT {+ break Vec::new();+ }+ raster_space_index = spaces[raster_space_index.0].parent_index;+ };+ let geometry = &self.geometries[raster_space_index.0];+ let mut moves_within_space = false;+ for run_index in run_indices.clone() {+ let run_moves_within_space =+ tables.context_moves_within_space(tree, list.run(run_index).context, raster_space_index)+ || runs_reaching_outside.inline_clips_of_run_move_within_space(+ tree,+ tables,+ run_index,+ raster_space_index,+ );+ run_moves_within_space_by_run_index[run_index] = run_moves_within_space;+ moves_within_space |= run_moves_within_space;+ }+ let mut reach_of_run_group = IntRect::default();+ let mut reach_read_by_records_blending_with_root_group = Reach::Nothing;+ for run_index in run_indices {+ let run = list.run(run_index);+ let ink_bounds_unless_moving_within_space =+ (!moves_within_space).then(|| run.ink_bounds.to_float());+ let reach_of_run = geometry.part_of_extent_reached_by(geometry.reach_of_content(+ &self.filters_and_clips,+ ink_bounds_unless_moving_within_space,+ run.context,+ ));+ reach_of_run_by_run_index[run_index] = reach_of_run;+ reach_of_run_group = reach_of_run_group.united(reach_of_run);+ if run_blends_with_root_group_by_run_index[run_index] {+ let blend_reads_below_where_it_draws = Reach::Within(reach_of_run);+ reach_read_by_records_blending_with_root_group =+ reach_read_by_records_blending_with_root_group.united(blend_reads_below_where_it_draws);+ }+ }+ let paints_within_root_group = match tree.root_isolation_effect {+ None => true,+ Some(root_isolation_effect) => (first_run_index..=last_run_index).any(|run_index| {+ self.nesting_of_live_effects+ .is_or_is_inside(list.run(run_index as usize).context.effect, root_isolation_effect)+ }),+ };+ PlacedRunGroup {+ raster_space_index,+ composite_clips,+ reach: reach_of_run_group,+ moves_within_space,+ paints_within_root_group,+ reach_read_by_records_blending_with_root_group,+ }+ });+ }+ let runs = RunGroupsPlaced {+ groups: placed_run_groups,+ reach_of_run_by_run_index,+ run_moves_within_space_by_run_index,+ swept_reach_in_parent_space_by_space_index,+ reach_by_effect_index_once_worked_out: std::cell::OnceCell::new(),+ };+ (runs, animations_without_layers)+ }++ /// Where content of `space`, whose anchor the compositor animates, can show in the raster coordinates of the space+ /// it is in wherever the animation takes it, or why the space holds none of it: content that a frame cannot+ /// composite through the anchor's transform, or whose reach nothing bounds, which would cut every tile around it,+ /// or that can show over a canvas or video painted before it, which would take those from the window server for the+ /// whole animation.+ fn swept_reach_of_animated_space_in_parent_space(+ &self,+ space: RasterSpaceIndex,+ run_indices_of_space: &[usize],+ canvases_and_videos_placed_before: impl Iterator<Item = (RasterSpaceIndex, IntRect)>,+ ) -> Result<IntRect, WhyAnimationHasNoLayer> {+ let (tree, list, tables, geometries) = (self.tree, self.list, &self.tables, self.geometries);+ let filters_and_clips = &self.filters_and_clips;+ let raster_space = tables.spaces()[space.0];+ let RasterSpaceAnchorKind::AnimatedTransform { raster_scale } = raster_space.anchor_kind else {+ unreachable!("only spaces whose anchor the compositor animates are swept");+ };+ if list+ .summary()+ .destination_blending_records+ .iter()+ .any(|record| run_indices_of_space.binary_search(&(record.run_index as usize)).is_ok())+ {+ return Err(WhyAnimationHasNoLayer::ItHoldsRecordsThatBlendWithWhatIsBelowThem);+ }+ for &run_index in run_indices_of_space {+ let mut effect = list.run(run_index).context.effect;+ while !effect.is_none() {+ let effect_node = &tree.effect_nodes[effect.0 as usize];+ let composited_around_space = tables.animated_space_holding_every_run_of_effect(effect) == Some(space)+ && !tables.moves_with(effect_node.spatial, space);+ if composited_around_space {+ if effect_reads_below_it(tree, effect) {+ return Err(WhyAnimationHasNoLayer::ItHoldsAnEffectThatReadsWhatIsBelowIt);+ }+ if let Some(why) = self.why_compositor_cannot_composite_by_effect_index[effect.0 as usize] {+ return Err(WhyAnimationHasNoLayer::InsideAnEffectTheCompositorCannotComposite(why));+ }+ }+ effect = effect_node.parent;+ }+ }++ let geometry = &geometries[space.0];+ // Content that moves within the space, as a sample of an animation inside it moves it or spreads it, reaches+ // wherever its clips fixed in the space let it.+ let content_reach_in_space = run_indices_of_space.iter().fold(Reach::Nothing, |reach, &run_index| {+ let run = list.run(run_index);+ if run.ink_bounds.is_empty() {+ return reach;+ }+ let drawn_within =+ (!tables.context_moves_within_space(tree, run.context, space)).then(|| run.ink_bounds.to_float());+ reach.united(geometry.reach_of_content(filters_and_clips, drawn_within, run.context))+ });+ let content_rect_in_anchor_space = match content_reach_in_space {+ Reach::Nothing => return Ok(IntRect::default()),+ Reach::Anywhere => return Err(WhyAnimationHasNoLayer::NothingBoundsWhereItMoves),+ Reach::Within(rect) => libgfx_rust::FloatRect::new(+ rect.x as f32 / raster_scale,+ rect.y as f32 / raster_scale,+ rect.width as f32 / raster_scale,+ rect.height as f32 / raster_scale,+ ),+ };++ let parent_space = raster_space.parent_index;+ let parent_geometry = &geometries[parent_space.0];+ let parent_of_anchor = tree.spatial_nodes[raster_space.anchor.0 as usize].parent;+ let reach_within_clips_fixed_in_parent_space =+ run_indices_of_space.iter().fold(Reach::Nothing, |reach, &run_index| {+ reach.united(parent_geometry.reach_of_content(filters_and_clips, None, list.run(run_index).context))+ });+ let swept_bounds_in_parent_space = (!tables.spatial_moves_within_space(parent_of_anchor, parent_space))+ .then(|| {+ crate::display_list::animated_transform_spaces::swept_bounds_in_parent(+ tree,+ raster_space.anchor,+ content_rect_in_anchor_space,+ )+ })+ .flatten()+ .map(|bounds| parent_geometry.raster.world.map_rect_to_root(parent_of_anchor, bounds))+ .filter(|bounds| is_finite_rect(*bounds));+ let swept_reach = match swept_bounds_in_parent_space {+ Some(bounds) => {+ let margin = crate::display_list::placement::ANTIALIASING_MARGIN_IN_DEVICE_PIXELS;+ let swept_rect =+ enclosing_int_rect_within_extent_limit(bounds).inflated_edges(margin, margin, margin, margin);+ reach_within_clips_fixed_in_parent_space.limited_to(swept_rect)+ }+ None => reach_within_clips_fixed_in_parent_space,+ };+ if swept_reach == Reach::Anywhere {+ return Err(WhyAnimationHasNoLayer::NothingBoundsWhereItMoves);+ }+ let swept_reach = parent_geometry.part_of_extent_reached_by(swept_reach);++ for (space_of_media, reach_of_media) in canvases_and_videos_placed_before {+ if space_of_media != parent_space || !reach_of_media.intersected(swept_reach).is_empty() {+ return Err(WhyAnimationHasNoLayer::ItCanShowOverAnEarlierCanvasOrVideo);+ }+ }+ Ok(swept_reach)+ }++ fn place_media(&self, runs: &RunGroupsPlaced) -> (Vec<PlacedMedia>, Vec<(LiveContent, WhyMediaHasNoLayer)>) {+ let (tree, list, run_groups) = (self.tree, self.list, &*self.run_groups);+ let mut placed_media: Vec<PlacedMedia> = Vec::new();+ let mut media_without_layers = Vec::new();+ let spatial_node_is_under_transform_animation_leaving_plane =+ spatial_nodes_under_transform_animations(tree, |node| tree.transform_animation_of_node_leaves_plane(node));+ for live_content_record in &list.summary().live_content_records {+ let content = live_content_record.content;+ if matches!(content, LiveContent::ImageFrame(_)) {+ continue;+ }+ let record: IndexedRecord = live_content_record.record;+ let (run_index, record_position) = (record.run_index, record.position);+ let why_no_layer = if run_groups.run_is_sorted_by_depth(run_index as usize) {+ Some(WhyMediaHasNoLayer::SortedByDepthInA3DSortingContext)+ } else {+ self.why_media_has_no_layer(+ &self.geometries[self.space_of_run(runs, run_index as usize).0].raster,+ run_index,+ record_position,+ runs.reach_of_run_by_run_index[run_index as usize],+ spatial_node_is_under_transform_animation_leaving_plane+ .get(list.run(run_index as usize).context.spatial.0 as usize)+ .copied()+ .unwrap_or(false),+ )+ };+ match why_no_layer {+ None => {+ let record_span = list.span_of_run(run_index as usize);+ debug_assert_eq!(+ record_position, record_span.begin,+ "a canvas, video or nested context is alone in its run"+ );+ placed_media.push(PlacedMedia {+ content,+ ordinal: 0,+ record_span,+ run_index: RunIndexInList(run_index),+ reach: runs.reach_of_run_by_run_index[run_index as usize],+ });+ }+ Some(why_no_layer) => media_without_layers.push((content, why_no_layer)),+ }+ }+ if placed_media.len() > MAXIMUM_MEDIA_LAYER_COUNT {+ let nested_contexts_after_canvases_and_videos =+ |media: &PlacedMedia| matches!(media.content, LiveContent::CompositedContext(_));+ placed_media.sort_by_key(nested_contexts_after_canvases_and_videos);+ for media_past_limit in placed_media.drain(MAXIMUM_MEDIA_LAYER_COUNT..) {+ media_without_layers.push((media_past_limit.content, WhyMediaHasNoLayer::MoreMediaThanLayersFor));+ }+ placed_media.sort_by_key(|media| media.record_span.begin);+ }+ for index in 0..placed_media.len() {+ placed_media[index].ordinal = placed_media[..index]+ .iter()+ .filter(|earlier| earlier.content == placed_media[index].content)+ .count() as u32;+ }+ (placed_media, media_without_layers)+ }++ // Under a transform animation that leaves the plane, a sample can draw the media through a matrix that is not 2D+ // affine, whatever the tree holds.+ fn why_media_has_no_layer(+ &self,+ geometry: &RasterSpaceGeometry,+ run_index: u32,+ media_record_position: ListPosition,+ reach_of_run_holding_only_media: IntRect,+ is_under_transform_animation_leaving_plane: bool,+ ) -> Option<WhyMediaHasNoLayer> {+ let (header, _) = self.list.record_at(media_record_position);+ if !matches!(+ header.command_type,+ DisplayListCommandType::DrawCanvas+ | DisplayListCommandType::DrawVideoFrame+ | DisplayListCommandType::DrawCompositedContext+ ) {+ return Some(WhyMediaHasNoLayer::DrawnInsideAnotherCommand);+ }+ let run = self.list.run(run_index as usize);+ if is_under_transform_animation_leaving_plane || !geometry.world.draw_matrix(run.context.spatial).is_2d_affine()+ {+ return Some(WhyMediaHasNoLayer::UnderTransformThatIsNot2DAffine);+ }+ if let Some(why) = self.why_compositor_cannot_composite_effect_or_effects_around(run.context.effect) {+ return Some(WhyMediaHasNoLayer::InsideAnEffectTheCompositorCannotComposite(why));+ }+ if reach_of_run_holding_only_media.is_empty() {+ return Some(WhyMediaHasNoLayer::DrawsNothingVisible);+ }+ None+ }++ fn effects_composited_regardless_of_layer_content(+ &self,+ runs: &RunGroupsPlaced,+ placed_media: &[PlacedMedia],+ animations_without_layers: &mut Vec<(AnimatedNode, WhyAnimationHasNoLayer)>,+ ) -> WhyEffectsAreCompositedRegardlessOfLayerContent {+ let (tree, list) = (self.tree, self.list);+ let spaces = self.tables.spaces();+ let mut why_composited_regardless_of_layer_content = WhyEffectsAreCompositedRegardlessOfLayerContent {+ why_by_effect_index: vec![None; tree.effect_nodes.len()],+ composited_effects: Vec::new(),+ };+ for media in placed_media {+ why_composited_regardless_of_layer_content.mark_effects_around_as_composited(+ tree,+ list.run(media.run_index.0 as usize).context.effect,+ WhyEffectIsComposited::ItHoldsMedia(media.content),+ );+ }++ let effect_reads_what_is_below_it = |effect: EffectNodeIndex| {+ self.backdrop_reader_by_effect_index[effect.0 as usize].is_some() || effect_reads_below_it(tree, effect)+ };+ let canvas_or_video_painted_before_can_show_under =+ |first_run_index: usize, raster_space_index: RasterSpaceIndex, reach: IntRect| {+ placed_media.iter().any(|media| {+ matches!(media.content, LiveContent::Canvas(_) | LiveContent::VideoFrame(_))+ && (media.run_index.0 as usize) < first_run_index+ && (self.space_of_run(runs, media.run_index.0 as usize) != raster_space_index+ || !media.reach.intersected(reach).is_empty())+ })+ };+ let mut animated_nodes_with_layers_count = 0;++ let space_holds_placed_content_by_space_index = std::cell::OnceCell::new();+ let space_holds_placed_content = |space: RasterSpaceIndex| {+ space_holds_placed_content_by_space_index.get_or_init(|| {+ let mut holds_by_space_index = vec![false; spaces.len()];+ for run_group in &runs.groups {+ holds_by_space_index[run_group.raster_space_index.0] = true;+ }+ holds_by_space_index+ })[space.0]+ };+ if self.some_space_is_animated {+ for (index, effect_node) in tree.effect_nodes.iter().enumerate() {+ let effect = EffectNodeIndex(index as u32);+ let Some(space) = self.tables.animated_space_holding_every_run_of_effect(effect) else {+ continue;+ };+ let applies_over_animated_transform = runs.swept_reach_in_parent_space_by_space_index[space.0]+ .is_some()+ && !self.tables.moves_with(effect_node.spatial, space)+ && space_holds_placed_content(space);+ if !applies_over_animated_transform || !tree.effect_pushes_layer_at_replay(effect) {+ continue;+ }+ why_composited_regardless_of_layer_content.set_unless_composited(+ effect,+ WhyEffectIsComposited::ItAppliesOverATransformTheCompositorAnimates,+ );+ why_composited_regardless_of_layer_content.mark_effects_around_as_composited(+ tree,+ effect_node.parent,+ WhyEffectIsComposited::ItHoldsAnEffectTheCompositorComposites,+ );+ }+ }++ let what_effects_hold_once_worked_out = std::cell::OnceCell::new();+ let what_effects_hold = || {+ what_effects_hold_once_worked_out.get_or_init(|| {+ let mut runs_holding_records_blending_with_what_is_below_them = vec![false; list.run_count()];+ for record in &list.summary().destination_blending_records {+ runs_holding_records_blending_with_what_is_below_them[record.run_index as usize] = true;+ }+ let mut effect_reads_what_is_below_it_by_effect_index = vec![false; tree.effect_nodes.len()];+ for &effect in &self.effects_in_paint_order_with_outer_before_inner {+ effect_reads_what_is_below_it_by_effect_index[effect.0 as usize] =+ effect_reads_what_is_below_it(effect);+ }+ let mut marks = [+ effects_of_marked_runs(list, tree, |run_index| {+ self.run_groups.run_is_sorted_by_depth(run_index)+ }),+ effects_of_marked_runs(list, tree, |run_index| {+ runs_holding_records_blending_with_what_is_below_them[run_index]+ }),+ effect_reads_what_is_below_it_by_effect_index,+ ];+ mark_effects_around_marked_effects(tree, &mut marks);+ let [+ run_sorted_by_depth_by_effect_index,+ records_blending_with_what_is_below_them_by_effect_index,+ effect_reading_what_is_below_it_by_effect_index,+ ] = marks;+ WhatEffectsHold {+ run_sorted_by_depth_by_effect_index,+ records_blending_with_what_is_below_them_by_effect_index,+ effect_reading_what_is_below_it_by_effect_index,+ }+ })+ };+ for &effect in &self.effects_in_paint_order_with_outer_before_inner {+ if !tree.effect_opacity_or_filter_is_animated(effect) {+ continue;+ }+ let filter_is_animated = tree.effect_filter_is_animated(effect);+ let first_run_index = self.first_run_index_by_effect_index[effect.0 as usize];+ if tree.root_isolation_effect == Some(effect)+ || !matches!(tree.effect_nodes[effect.0 as usize].data, EffectNodeData::Effects(_))+ {+ continue;+ }+ let why_no_layer = (|| {+ if filter_is_animated && filter_may_spread_at_some_sample(tree, effect) {+ return Some(WhyAnimationHasNoLayer::ItsFilterSpreadsWhatItFilters);+ }+ if let Some(why) = self.why_compositor_cannot_composite_effect_or_effects_around(effect) {+ return Some(WhyAnimationHasNoLayer::InsideAnEffectTheCompositorCannotComposite(why));+ }+ let what_effects_hold = what_effects_hold();+ if what_effects_hold.run_sorted_by_depth_by_effect_index[effect.0 as usize] {+ return Some(WhyAnimationHasNoLayer::SortedByDepthInA3DSortingContext);+ }+ if what_effects_hold.records_blending_with_what_is_below_them_by_effect_index[effect.0 as usize] {+ return Some(WhyAnimationHasNoLayer::ItHoldsRecordsThatBlendWithWhatIsBelowThem);+ }+ if what_effects_hold.effect_reading_what_is_below_it_by_effect_index[effect.0 as usize] {+ return Some(WhyAnimationHasNoLayer::ItHoldsAnEffectThatReadsWhatIsBelowIt);+ }+ if canvas_or_video_painted_before_can_show_under(+ first_run_index,+ self.space_of_run(runs, first_run_index),+ self.reach_of_effect(runs, effect),+ ) {+ return Some(WhyAnimationHasNoLayer::ItCanShowOverAnEarlierCanvasOrVideo);+ }+ if animated_nodes_with_layers_count == MAXIMUM_ANIMATED_NODES_WITH_LAYERS {+ return Some(WhyAnimationHasNoLayer::MoreAnimationsThanLayersFor);+ }+ None+ })();+ if let Some(why_no_layer) = why_no_layer {+ animations_without_layers.push((AnimatedNode::Effect(effect), why_no_layer));+ continue;+ }+ animated_nodes_with_layers_count += 1;+ why_composited_regardless_of_layer_content+ .set_unless_composited(effect, WhyEffectIsComposited::TheCompositorAnimatesIt);+ why_composited_regardless_of_layer_content.mark_effects_around_as_composited(+ tree,+ tree.effect_nodes[effect.0 as usize].parent,+ WhyEffectIsComposited::ItHoldsAnEffectTheCompositorComposites,+ );+ }+ why_composited_regardless_of_layer_content+ }++ // What each backdrop reader reads, in paint order, and whether it reads the root group. An effect that reads what+ // its own layer does not hold is composited.+ fn note_backdrop_readers(+ &self,+ runs: &RunGroupsPlaced,+ placed_media: &[PlacedMedia],+ why_composited_regardless_of_layer_content: &mut WhyEffectsAreCompositedRegardlessOfLayerContent,+ ) -> (Vec<Reach<IntRect>>, Vec<EffectNodeIndex>, Vec<bool>) {+ let (tree, list) = (self.tree, self.list);+ let mut backdrop_read_reach_by_effect_index = vec![Reach::Nothing; tree.effect_nodes.len()];+ let mut backdrop_readers_in_paint_order = Vec::new();+ // Empty until an effect reads the root group.+ let mut reads_root_group_by_effect_index: Vec<bool> = Vec::new();+ for &effect in &self.effects_in_paint_order_with_outer_before_inner {+ let Some(backdrop_reader) = self.backdrop_reader_by_effect_index[effect.0 as usize] else {+ continue;+ };+ let run_group = &runs.groups[self.run_group_of_effect(effect).0];+ let geometry = &self.geometries[run_group.raster_space_index.0];+ let reach_of_reading_effect = self.reach_of_effect(runs, effect);+ let (backdrop_read_reach, reads_nothing_past_mirrored_edge) =+ match backdrop_reader.effect_with_backdrop_filter {+ Some(effect_with_backdrop_filter) => {+ let effect_node = &tree.effect_nodes[effect_with_backdrop_filter.0 as usize];+ let EffectNodeData::Effects(effects) = &effect_node.data else {+ unreachable!("a backdrop filter belongs to an effects node");+ };+ let backdrop_filter = effects+ .backdrop_filter+ .as_ref()+ .expect("a reader with a backdrop filter has one");+ // Where a transform the compositor animates moves or scales the backdrop filter within the+ // space, a sample can read anywhere.+ let backdrop_read_reach = if self.tables.animation_samples_move_spatial_within_space(+ effect_node.spatial,+ run_group.raster_space_index,+ ) {+ Reach::Anywhere+ } else if run_group.moves_within_space {+ filter_read_reach_in_device_pixels(+ &backdrop_filter.filter,+ &geometry.raster.world.draw_matrix(effect_node.spatial),+ )+ .map_or(Reach::Anywhere, |read_reach_in_device_pixels| {+ Reach::Within(run_group.reach.inflated_edges(+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ read_reach_in_device_pixels,+ ))+ })+ } else {+ backdrop_filter_read_reach(tree, &geometry.raster, effect_with_backdrop_filter)+ };+ (+ backdrop_read_reach,+ backdrop_filter_reads_nothing_past_mirrored_edge(&backdrop_filter.filter),+ )+ }+ None => (Reach::Within(reach_of_reading_effect), true),+ };+ backdrop_read_reach_by_effect_index[effect.0 as usize] = backdrop_read_reach;+ let reading_effect_node = &tree.effect_nodes[effect.0 as usize];+ let backdrop_root = if reading_effect_node.parent.is_none() {+ None+ } else {+ tree.nearest_layer_at_or_above(reading_effect_node.parent)+ .filter(|root| tree.root_isolation_effect != Some(*root))+ };+ let why_composited = if !reads_nothing_past_mirrored_edge {+ Some(WhyEffectIsComposited::ItsBackdropFilterReadsPastTheEdgeOfTheFrame)+ } else if let Some(backdrop_root) = backdrop_root {+ let backdrop_read_tiles = match backdrop_read_reach {+ Reach::Within(rect) => Reach::Within(CellRange::touched_by(rect).rect()),+ backdrop_read_reach => backdrop_read_reach,+ };+ let read_tiles_cut_by_earlier_composited_effect = why_composited_regardless_of_layer_content+ .composited_effects+ .iter()+ .any(|&other_effect| {+ other_effect != effect+ && self.first_run_index_by_effect_index[other_effect.0 as usize]+ < self.first_run_index_by_effect_index[effect.0 as usize]+ && self+ .nesting_of_live_effects+ .is_strictly_inside(other_effect, backdrop_root)+ && !self.nesting_of_live_effects.is_strictly_inside(effect, other_effect)+ && backdrop_read_tiles.meets(Reach::Within(+ self.reach_of_effect(runs, other_effect).united(+ match backdrop_read_reach_by_effect_index[other_effect.0 as usize] {+ Reach::Within(rect) => rect,+ _ => IntRect::default(),+ },+ ),+ ))+ });+ let read_tiles_cut_by_earlier_media = placed_media.iter().any(|media| {+ let effect_of_media = list.run(media.run_index.0 as usize).context.effect;+ (media.run_index.0 as usize) < self.first_run_index_by_effect_index[effect.0 as usize]+ && self+ .nesting_of_live_effects+ .is_or_is_inside(effect_of_media, backdrop_root)+ && backdrop_read_tiles.meets(Reach::Within(media.reach))+ });+ (read_tiles_cut_by_earlier_composited_effect || read_tiles_cut_by_earlier_media)+ .then_some(WhyEffectIsComposited::ItReadsWhatItsOwnLayerDoesNotHold)+ } else {+ None+ };+ backdrop_readers_in_paint_order.push(effect);+ if backdrop_root.is_none() {+ reads_root_group_by_effect_index.resize(tree.effect_nodes.len(), false);+ reads_root_group_by_effect_index[effect.0 as usize] = true;+ }+ let Some(why_composited) = why_composited else {+ continue;+ };+ why_composited_regardless_of_layer_content.set(effect, why_composited);+ why_composited_regardless_of_layer_content.mark_effects_around_as_composited(+ tree,+ reading_effect_node.parent,+ WhyEffectIsComposited::ItHoldsAnEffectTheCompositorComposites,+ );+ }+ (+ backdrop_read_reach_by_effect_index,+ backdrop_readers_in_paint_order,+ reads_root_group_by_effect_index,+ )+ }++ fn place_effects(+ &self,+ runs: &RunGroupsPlaced,+ why_composited_regardless_of_layer_content: &WhyEffectsAreCompositedRegardlessOfLayerContent,+ backdrop_read_reach_by_effect_index: &[Reach<IntRect>],+ reads_root_group_by_effect_index: &[bool],+ ) -> (Vec<PlacedEffect>, Vec<Option<PlacedEffectIndex>>) {+ let tree = self.tree;+ // Effects come after the effects around them, so the innermost placed effect at or around each is known by+ // then.+ let mut innermost_placed_effect_at_or_around_by_effect_index: Vec<Option<PlacedEffectIndex>> =+ vec![None; tree.effect_nodes.len()];+ let mut placed_effects: Vec<PlacedEffect> = Vec::new();+ for &effect in &self.effects_in_paint_order_with_outer_before_inner {+ let parent = tree.effect_nodes[effect.0 as usize].parent;+ let innermost_placed_effect_around = innermost_placed_effect_at_or_around_by_effect_index+ .get(parent.0 as usize)+ .copied()+ .flatten();+ innermost_placed_effect_at_or_around_by_effect_index[effect.0 as usize] = innermost_placed_effect_around;+ let why_composited_regardless_of_layer_content =+ why_composited_regardless_of_layer_content.why_by_effect_index[effect.0 as usize];+ let reads_root_group = reads_root_group_by_effect_index+ .get(effect.0 as usize)+ .copied()+ .unwrap_or(false);+ if why_composited_regardless_of_layer_content.is_none() && !reads_root_group {+ continue;+ }+ innermost_placed_effect_at_or_around_by_effect_index[effect.0 as usize] =+ Some(PlacedEffectIndex(placed_effects.len()));+ placed_effects.push(PlacedEffect {+ effect,+ placed_effect_around_index: innermost_placed_effect_around,+ reach: self.reach_of_effect(runs, effect),+ backdrop_read_reach: backdrop_read_reach_by_effect_index[effect.0 as usize],+ why_composited_regardless_of_layer_content,+ });+ }+ (placed_effects, innermost_placed_effect_at_or_around_by_effect_index)+ }++ fn place_record_stretches(+ &self,+ runs: &RunGroupsPlaced,+ placed_media: &[PlacedMedia],+ placed_effects: &[PlacedEffect],+ innermost_placed_effect_at_or_around_by_effect_index: &[Option<PlacedEffectIndex>],+ ) -> (Vec<PlacedRecordStretch>, Vec<bool>) {+ let list = self.list;+ let innermost_placed_effect_of_run = |run_index: usize| {+ innermost_placed_effect_at_or_around_by_effect_index+ .get(list.run(run_index).context.effect.0 as usize)+ .copied()+ .flatten()+ };++ let mut record_stretches: Vec<PlacedRecordStretch> = Vec::with_capacity(runs.groups.len());+ let mut remaining_placed_media = placed_media.iter().enumerate().peekable();+ let mut tiles_hold_content_moving_within_space_by_space_index = vec![false; self.tables.spaces().len()];+ for run_index in 0..list.run_count() {+ let run_group_index = self.run_groups.group_of_run(run_index);+ let innermost_placed_effect = innermost_placed_effect_of_run(run_index);+ if let Some((placed_media_index, media)) =+ remaining_placed_media.next_if(|(_, media)| media.run_index.0 as usize == run_index)+ {+ record_stretches.push(PlacedRecordStretch {+ record_span: media.record_span,+ run_group_index,+ reach: media.reach,+ placed_media_index: Some(PlacedMediaIndex(placed_media_index)),+ placed_effect_index: innermost_placed_effect,+ });+ continue;+ }+ if runs.run_moves_within_space_by_run_index[run_index] {+ tiles_hold_content_moving_within_space_by_space_index[self.space_of_run(runs, run_index).0] = true;+ }+ let run_span = list.span_of_run(run_index);+ let run_draws_nothing = list.run(run_index).ink_bounds.is_empty();+ let reach_of_run_in_stretch = match innermost_placed_effect {+ _ if run_draws_nothing => IntRect::default(),+ Some(placed_effect_index) => placed_effects[placed_effect_index.0].reach,+ None => runs.reach_of_run_by_run_index[run_index],+ };+ match record_stretches.last_mut() {+ Some(last)+ if last.run_group_index == run_group_index+ && last.placed_effect_index == innermost_placed_effect+ && last.placed_media_index.is_none() =>+ {+ last.record_span.end = run_span.end;+ last.reach = last.reach.united(reach_of_run_in_stretch);+ }+ _ => record_stretches.push(PlacedRecordStretch {+ record_span: run_span,+ run_group_index,+ reach: reach_of_run_in_stretch,+ placed_media_index: None,+ placed_effect_index: innermost_placed_effect,+ }),+ }+ }+ (record_stretches, tiles_hold_content_moving_within_space_by_space_index)+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+struct BandBeingBuiltIndex(usize);++struct BandBeingBuilt {+ placement_node_index: PlacementNodeIndex,+ barriers: Vec<BarrierBeingBuilt>,+ own_record_stretch_indices: Vec<RecordStretchIndex>,+ first_record_stretch_index: RecordStretchIndex,+ root_group_reach_so_far: Reach<IntRect>,+}++#[derive(Clone, Copy)]+enum BarrierBeingBuilt {+ Media {+ record_stretch_index: RecordStretchIndex,+ },+ NestedNodeBand {+ band_being_built_index: BandBeingBuiltIndex,+ },+}++// Calls `for_layer_and_part_of_reach` with each layer that records of a band at `record_position` go into, and the part+// of `reach` they go into it in: per tile, the layer above the last of `cuts` painted before them that cuts the tile, or+// where they reach too many tiles to follow one by one, each layer above a cut painted before them, and the layer below+// all cuts unless one of those cuts every tile, in all of `reach`.+fn for_each_layer_records_go_into(+ cuts: &[BarrierCut],+ layer_below_all_cuts: LayerIndex,+ record_position: ListPosition,+ reach: IntRect,+ mut for_layer_and_part_of_reach: impl FnMut(LayerIndex, IntRect),+) {+ let count_of_cuts_painted_before = cuts+ .iter()+ .take_while(|cut| cut.barrier_first_record_position <= record_position)+ .count();+ let cuts_painted_before = &cuts[..count_of_cuts_painted_before];+ if cuts_painted_before.is_empty() || reaches_too_many_cells_to_follow_one_by_one(reach) {+ let cells_reached = CellRange::touched_by(reach);+ let a_cut_painted_before_cuts_every_cell_reached = cuts_painted_before.iter().any(|cut| match cut.cut_reach {+ Reach::Anywhere => true,+ Reach::Within(cut_rect) => CellRange::touched_by(cut_rect).holds_every_cell_of(cells_reached),+ Reach::Nothing => false,+ });+ if !a_cut_painted_before_cuts_every_cell_reached {+ for_layer_and_part_of_reach(layer_below_all_cuts, reach);+ }+ for cut in cuts_painted_before {+ for_layer_and_part_of_reach(cut.layer_above_cut, reach);+ }+ return;+ }+ for coord in tile_coords_touching(reach) {+ let cell = coord.cell_rect();+ let layer_in_cell = cuts_painted_before+ .iter()+ .rev()+ .find(|cut| cut.cuts_cell(cell))+ .map_or(layer_below_all_cuts, |cut| cut.layer_above_cut);+ for_layer_and_part_of_reach(layer_in_cell, reach.intersected(cell));+ }+}++struct StackBeingBuilt<'a> {+ placement: &'a ListPlacement,+ spaces: &'a [RasterSpace],+ nodes: Vec<NodeOfPlan>,+ node_of_run_group: Vec<PlacementNodeIndex>,+ children_of_node: Vec<Vec<PlacementNodeIndex>>,+ bands_being_built: Vec<BandBeingBuilt>,+ /// Per placed effect, once decided, the node the compositor composites it in, if it composites it.+ composited_node_once_decided_by_placed_effect: Vec<Option<Option<PlacementNodeIndex>>>,+ composited_effects_around_node_by_node_index: Vec<usize>,+}++impl StackBeingBuilt<'_> {+ fn add_node(&mut self, node: NodeOfPlan) -> PlacementNodeIndex {+ let parent_index = node.parent_index;+ let composited_effects_around_parent = parent_index.map_or(0, |parent_index| {+ self.composited_effects_around_node_by_node_index[parent_index.0]+ });+ self.composited_effects_around_node_by_node_index+ .push(composited_effects_around_parent + usize::from(node.composited_effect.is_some()));+ self.nodes.push(node);+ self.children_of_node.push(Vec::new());+ let node_index = PlacementNodeIndex(self.nodes.len() - 1);+ if let Some(parent_index) = parent_index {+ self.children_of_node[parent_index.0].push(node_index);+ }+ node_index+ }++ fn find_or_add_node(+ &mut self,+ raster_space_index: RasterSpaceIndex,+ composite_clips: &[CompositeClip],+ ) -> PlacementNodeIndex {+ if let Some(existing_node_index) = self.nodes.iter().position(|node| {+ node.raster_space_index == raster_space_index+ && node.composite_clips == composite_clips+ && node.composited_effect.is_none()+ }) {+ return PlacementNodeIndex(existing_node_index);+ }+ let spaces = self.spaces;+ let (parent_index, reach_in_parent_node) = if raster_space_index == RasterSpaceIndex::VIEWPORT {+ (None, Reach::Anywhere)+ } else {+ let parent_space = spaces[raster_space_index.0].parent_index;+ let reach_in_parent_node = composite_clips+ .iter()+ .find(|clip| clip.raster_space_index == parent_space)+ .map_or(Reach::Anywhere, |clip| Reach::Within(clip.rect));+ let composite_clips_of_parent_node: Vec<CompositeClip> = composite_clips+ .iter()+ .filter(|clip| clip.raster_space_index != parent_space)+ .copied()+ .collect();+ (+ Some(self.find_or_add_node(parent_space, &composite_clips_of_parent_node)),+ reach_in_parent_node,+ )+ };+ self.add_node(NodeOfPlan {+ raster_space_index,+ composite_clips: composite_clips.to_vec(),+ composited_effect: None,+ parent_index,+ reach_in_parent_node,+ })+ }++ fn add_composited_node_inside(+ &mut self,+ parent_index: PlacementNodeIndex,+ effect: EffectNodeIndex,+ reach_in_parent_node: Reach<IntRect>,+ ) -> PlacementNodeIndex {+ let parent_node = &self.nodes[parent_index.0];+ let composited_node = NodeOfPlan {+ raster_space_index: parent_node.raster_space_index,+ composite_clips: parent_node.composite_clips.clone(),+ composited_effect: Some(effect),+ parent_index: Some(parent_index),+ reach_in_parent_node,+ };+ self.add_node(composited_node)+ }++ fn placed_effects_around_stretch_outermost_first(&self, stretch: &PlacedRecordStretch) -> Vec<PlacedEffectIndex> {+ let mut placed_effects_around_stretch: Vec<PlacedEffectIndex> =+ std::iter::successors(stretch.placed_effect_index, |&placed_effect_index| {+ self.placement.placed_effects[placed_effect_index.0].placed_effect_around_index+ })+ .collect();+ placed_effects_around_stretch.reverse();+ placed_effects_around_stretch+ }++ fn reach_of_stretch_with_what_effects_around_it_read(&self, stretch: &PlacedRecordStretch) -> Reach<IntRect> {+ self.placed_effects_around_stretch_outermost_first(stretch)+ .into_iter()+ .fold(Reach::Within(stretch.reach), |reach, placed_effect_index| {+ reach.united(self.placement.placed_effects[placed_effect_index.0].backdrop_read_reach)+ })+ }++ fn draw_and_read_reach_of_placed_effect(&self, placed_effect_index: PlacedEffectIndex) -> Reach<IntRect> {+ let placed_effect = &self.placement.placed_effects[placed_effect_index.0];+ Reach::Within(placed_effect.reach).united(placed_effect.backdrop_read_reach)+ }++ // A node of a space whose anchor the compositor animates reaches only where its content can show wherever the+ // animation takes it, and a node of a sticky box only where its content, with the nodes of the spaces in it, can+ // show wherever the box is held. Nodes come after the nodes they are in, so a walk from the last node sees the final+ // reach of each node before the node it is in.+ fn limit_reach_of_moving_space_nodes_to_content_swept_over_how_they_move(+ &mut self,+ swept_reach_in_parent_space_by_space_index: &[Option<IntRect>],+ ) {+ let (placement, spaces) = (self.placement, self.spaces);+ let mut content_reach_by_node_index = vec![Reach::Nothing; self.nodes.len()];+ for stretch in &placement.record_stretches {+ let node_index = self.node_of_run_group[stretch.run_group_index.0];+ content_reach_by_node_index[node_index.0] = content_reach_by_node_index[node_index.0]+ .united(self.reach_of_stretch_with_what_effects_around_it_read(stretch));+ }+ for node_index in (0..self.nodes.len()).rev() {+ let node = &mut self.nodes[node_index];+ if node.composited_effect.is_some() {+ continue;+ }+ if let Some(Some(swept_reach)) = swept_reach_in_parent_space_by_space_index.get(node.raster_space_index.0) {+ node.reach_in_parent_node = node.reach_in_parent_node.limited_to(*swept_reach);+ }+ let raster_space = &spaces[node.raster_space_index.0];+ if matches!(raster_space.anchor_kind, RasterSpaceAnchorKind::StickyBox { .. })+ && let Reach::Within(content_reach) = content_reach_by_node_index[node_index]+ {+ let content_reach_swept_over_offset_range = rect_swept_over_translations(+ content_reach,+ raster_space.lowest_anchor_translation,+ raster_space.highest_anchor_translation,+ );+ node.reach_in_parent_node = node+ .reach_in_parent_node+ .limited_to(content_reach_swept_over_offset_range);+ }+ if let Some(parent_index) = node.parent_index {+ let reach_in_parent_node = node.reach_in_parent_node;+ content_reach_by_node_index[parent_index.0] =+ content_reach_by_node_index[parent_index.0].united(reach_in_parent_node);+ }+ }+ }++ fn path_from_root_to(&self, mut node_index: PlacementNodeIndex) -> Vec<PlacementNodeIndex> {+ let mut path = vec![node_index];+ while let Some(parent_index) = self.nodes[node_index.0].parent_index {+ path.push(parent_index);+ node_index = parent_index;+ }+ path.reverse();+ path+ }++ fn open_band(+ &mut self,+ placement_node_index: PlacementNodeIndex,+ first_record_stretch_index: RecordStretchIndex,+ ) -> BandBeingBuiltIndex {+ self.bands_being_built.push(BandBeingBuilt {+ placement_node_index,+ barriers: Vec::new(),+ own_record_stretch_indices: Vec::new(),+ first_record_stretch_index,+ root_group_reach_so_far: Reach::Nothing,+ });+ BandBeingBuiltIndex(self.bands_being_built.len() - 1)+ }++ fn reach_can_meet_tiles(+ &self,+ node_of_reach: PlacementNodeIndex,+ reach_in_node: Reach<IntRect>,+ path_from_root_to_node_of_tiles: &[PlacementNodeIndex],+ tiles_in_node: IntRect,+ ) -> bool {+ if reach_in_node == Reach::Nothing {+ return false;+ }+ let path_from_root_to_node_of_reach = self.path_from_root_to(node_of_reach);+ let length_of_shared_path = path_from_root_to_node_of_reach+ .iter()+ .zip(path_from_root_to_node_of_tiles)+ .take_while(|(first, second)| first == second)+ .count();+ let reach_in_lowest_shared_node = match path_from_root_to_node_of_reach.get(length_of_shared_path) {+ Some(&child_of_lowest_shared_node) => self.nodes[child_of_lowest_shared_node.0].reach_in_parent_node,+ None => reach_in_node,+ };+ let tiles_in_lowest_shared_node = match path_from_root_to_node_of_tiles.get(length_of_shared_path) {+ Some(&child_of_lowest_shared_node) => self.nodes[child_of_lowest_shared_node.0].reach_in_parent_node,+ None => Reach::Within(tiles_in_node),+ };+ reach_in_lowest_shared_node.meets(tiles_in_lowest_shared_node)+ }++ fn reader_painted_next_finds_all_it_reads_in_own_layer(+ &self,+ reader_node: PlacementNodeIndex,+ open_band_of_reader_node: Option<BandBeingBuiltIndex>,+ read_tiles: IntRect,+ ) -> bool {+ let path_from_root_to_reader_node = self.path_from_root_to(reader_node);+ let another_band_shows_root_group_in_read_tiles =+ self.bands_being_built.iter().enumerate().any(|(index, band)| {+ Some(BandBeingBuiltIndex(index)) != open_band_of_reader_node+ && self.reach_can_meet_tiles(+ band.placement_node_index,+ band.root_group_reach_so_far,+ &path_from_root_to_reader_node,+ read_tiles,+ )+ });+ if another_band_shows_root_group_in_read_tiles {+ return false;+ }+ let Some(open_band_of_reader_node) = open_band_of_reader_node else {+ return true;+ };+ self.bands_being_built[open_band_of_reader_node.0]+ .barriers+ .iter()+ .all(|barrier| {+ let reach_of_barrier = match *barrier {+ BarrierBeingBuilt::Media { record_stretch_index } => {+ Reach::Within(self.placement.record_stretches[record_stretch_index.0].reach)+ }+ BarrierBeingBuilt::NestedNodeBand { band_being_built_index } => {+ let nested_node_index = self.bands_being_built[band_being_built_index.0].placement_node_index;+ self.nodes[nested_node_index.0].reach_in_parent_node+ }+ };+ !reach_of_barrier.touches(read_tiles)+ })+ }++ fn close_bands_of_node_and_nodes_inside(+ &self,+ node_index: PlacementNodeIndex,+ open_band_by_node_index: &mut [Option<BandBeingBuiltIndex>],+ ) {+ let mut nodes_to_close = vec![node_index];+ while let Some(node_index) = nodes_to_close.pop() {+ open_band_by_node_index[node_index.0] = None;+ nodes_to_close.extend_from_slice(&self.children_of_node[node_index.0]);+ }+ }++ fn placed_effect_is_composited(+ &self,+ placed_effect: &PlacedEffect,+ node_of_first_stretch_painted_next: PlacementNodeIndex,+ open_band_of_node: Option<BandBeingBuiltIndex>,+ ) -> bool {+ if placed_effect.why_composited_regardless_of_layer_content.is_some() {+ return true;+ }+ let finds_all_it_reads_in_own_layer = match placed_effect.backdrop_read_reach {+ Reach::Nothing => true,+ Reach::Within(backdrop_read_rect) => self.reader_painted_next_finds_all_it_reads_in_own_layer(+ node_of_first_stretch_painted_next,+ open_band_of_node,+ CellRange::touched_by(backdrop_read_rect).rect(),+ ),+ Reach::Anywhere => false,+ };+ !finds_all_it_reads_in_own_layer+ }++ fn node_of_stretch(+ &mut self,+ stretch: &PlacedRecordStretch,+ open_band_by_node_index: &mut Vec<Option<BandBeingBuiltIndex>>,+ ) -> Result<PlacementNodeIndex, WhyListIsOneLayer> {+ let mut node_index = self.node_of_run_group[stretch.run_group_index.0];+ for placed_effect_index in self.placed_effects_around_stretch_outermost_first(stretch) {+ let composited_node_index = match self.composited_node_once_decided_by_placed_effect[placed_effect_index.0]+ {+ Some(composited_node_index) => composited_node_index,+ None => {+ let placed_effect = self.placement.placed_effects[placed_effect_index.0];+ let composited_node_index = if self.placed_effect_is_composited(+ &placed_effect,+ node_index,+ open_band_by_node_index[node_index.0],+ ) {+ if self.composited_effects_around_node_by_node_index[node_index.0]+ >= MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS+ {+ return Err(WhyListIsOneLayer::CompositedEffectsNestTooDeep);+ }+ // Media and animations get no layer inside an effect the compositor cannot composite, but an+ // effect that reads what is below its layer can still make one composited.+ if let Some(why) = self.placement.why_compositor_cannot_composite_by_effect_index+ [placed_effect.effect.0 as usize]+ {+ return Err(WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(why));+ }+ let draw_and_read_reach = self.draw_and_read_reach_of_placed_effect(placed_effect_index);+ let composited_node_index =+ self.add_composited_node_inside(node_index, placed_effect.effect, draw_and_read_reach);+ open_band_by_node_index.push(None);+ Some(composited_node_index)+ } else {+ None+ };+ self.composited_node_once_decided_by_placed_effect[placed_effect_index.0] =+ Some(composited_node_index);+ composited_node_index+ }+ };+ let Some(composited_node_index) = composited_node_index else {+ break;+ };+ node_index = composited_node_index;+ }+ Ok(node_index)+ }++ fn cut_into_bands(&mut self) -> Result<(), WhyListIsOneLayer> {+ let placement = self.placement;+ let root_node_index = PlacementNodeIndex(0);+ let mut open_band_by_node_index: Vec<Option<BandBeingBuiltIndex>> = vec![None; self.nodes.len()];+ open_band_by_node_index[root_node_index.0] = Some(self.open_band(root_node_index, RecordStretchIndex(0)));+ let mut composited_nodes_whose_bands_may_be_open: Vec<PlacementNodeIndex> = Vec::new();+ let mut node_is_on_path_of_stretch: Vec<bool> = Vec::new();+ for (index, stretch) in placement.record_stretches.iter().enumerate() {+ let stretch_index = RecordStretchIndex(index);+ if stretch.reach.is_empty() {+ continue;+ }+ let node_of_stretch = self.node_of_stretch(stretch, &mut open_band_by_node_index)?;+ let reach_read_by_blending_records =+ placement.run_groups[stretch.run_group_index.0].reach_read_by_records_blending_with_root_group;+ if reach_read_by_blending_records != Reach::Nothing {+ let blending_records_find_all_they_read_in_own_layer = match reach_read_by_blending_records {+ Reach::Within(read_rect) => {+ let tiles_blending_records_draw_or_read =+ CellRange::touched_by(stretch.reach.united(read_rect)).rect();+ self.reader_painted_next_finds_all_it_reads_in_own_layer(+ node_of_stretch,+ open_band_by_node_index[node_of_stretch.0],+ tiles_blending_records_draw_or_read,+ )+ }+ _ => false,+ };+ if !blending_records_find_all_they_read_in_own_layer {+ return Err(WhyListIsOneLayer::RecordsBlendWithWhatOtherLayersHoldBelowThem);+ }+ }+ let path_from_root_to_node_of_stretch = self.path_from_root_to(node_of_stretch);+ // A replay of the list composites an effect anew wherever content outside it is painted, so the bands of+ // its node end there.+ composited_nodes_whose_bands_may_be_open.retain(|node| open_band_by_node_index[node.0].is_some());+ if !composited_nodes_whose_bands_may_be_open.is_empty() {+ node_is_on_path_of_stretch.resize(self.nodes.len(), false);+ for node_on_path in &path_from_root_to_node_of_stretch {+ node_is_on_path_of_stretch[node_on_path.0] = true;+ }+ for &composited_node_index in &composited_nodes_whose_bands_may_be_open {+ if open_band_by_node_index[composited_node_index.0].is_some()+ && !node_is_on_path_of_stretch[composited_node_index.0]+ {+ self.close_bands_of_node_and_nodes_inside(composited_node_index, &mut open_band_by_node_index);+ }+ }+ for node_on_path in &path_from_root_to_node_of_stretch {+ node_is_on_path_of_stretch[node_on_path.0] = false;+ }+ }+ for depth in 0..path_from_root_to_node_of_stretch.len() {+ let node_on_path = path_from_root_to_node_of_stretch[depth];+ let open_band_of_node_on_path =+ open_band_by_node_index[node_on_path.0].expect("the bands along the path of a stretch are open");+ let next_node_on_path = path_from_root_to_node_of_stretch.get(depth + 1).copied();+ let reach_of_stretch_in_node_on_path = match next_node_on_path {+ Some(next_node) => self.nodes[next_node.0].reach_in_parent_node,+ None => Reach::Within(stretch.reach),+ };+ for &other_child in &self.children_of_node[node_on_path.0] {+ if Some(other_child) == next_node_on_path || open_band_by_node_index[other_child.0].is_none() {+ continue;+ }+ if reach_of_stretch_in_node_on_path.meets(self.nodes[other_child.0].reach_in_parent_node) {+ self.close_bands_of_node_and_nodes_inside(other_child, &mut open_band_by_node_index);+ }+ }+ match next_node_on_path {+ Some(next_node) if open_band_by_node_index[next_node.0].is_none() => {+ let new_band_of_next_node = self.open_band(next_node, stretch_index);+ open_band_by_node_index[next_node.0] = Some(new_band_of_next_node);+ if self.nodes[next_node.0].composited_effect.is_some() {+ composited_nodes_whose_bands_may_be_open.push(next_node);+ }+ self.bands_being_built[open_band_of_node_on_path.0].barriers.push(+ BarrierBeingBuilt::NestedNodeBand {+ band_being_built_index: new_band_of_next_node,+ },+ );+ }+ Some(_) => {}+ None if stretch.placed_media_index.is_some() => {+ self.bands_being_built[open_band_of_node_on_path.0]+ .barriers+ .push(BarrierBeingBuilt::Media {+ record_stretch_index: stretch_index,+ });+ }+ None => self.bands_being_built[open_band_of_node_on_path.0]+ .own_record_stretch_indices+ .push(stretch_index),+ }+ }+ if placement.run_groups[stretch.run_group_index.0].paints_within_root_group {+ let open_band_of_stretch = open_band_by_node_index[node_of_stretch.0]+ .expect("the band of a stretch is open once it is placed");+ let band_of_stretch = &mut self.bands_being_built[open_band_of_stretch.0];+ band_of_stretch.root_group_reach_so_far = band_of_stretch+ .root_group_reach_so_far+ .united(Reach::Within(stretch.reach));+ }+ }+ Ok(())+ }++ // Puts the band into `bands`, and after it the bands nested in it, in the order of a walk that enters a nested band+ // at its barrier.+ fn emit_band(&mut self, band_being_built_index: BandBeingBuiltIndex, bands: &mut Vec<BandOfPlan>) {+ let placement = self.placement;+ let band_being_built = &mut self.bands_being_built[band_being_built_index.0];+ let placement_node_index = band_being_built.placement_node_index;+ let own_record_stretch_indices = std::mem::take(&mut band_being_built.own_record_stretch_indices);+ let barriers = std::mem::take(&mut band_being_built.barriers);+ let band_position = bands.len();+ bands.push(BandOfPlan {+ placement_node_index,+ record_spans: Vec::new(),+ reach_of_layer_below_all_cuts: IntRect::default(),+ cuts: Vec::new(),+ });+ // Here a layer index counts the band's painted layers: the one below all cuts, then the one above each cut.+ let mut cuts = Vec::with_capacity(barriers.len());+ let mut barriers_of_plan = Vec::with_capacity(barriers.len());+ for barrier in barriers {+ let (barrier_of_plan, barrier_first_record_position, cut_reach) = match barrier {+ BarrierBeingBuilt::Media { record_stretch_index } => {+ let media_stretch = &placement.record_stretches[record_stretch_index.0];+ let media = &placement.placed_media[media_stretch+ .placed_media_index+ .expect("a media barrier is a media stretch")+ .0];+ let barrier_of_plan = BarrierOfPlan::Media {+ content: media.content,+ ordinal: media.ordinal,+ record_span: media_stretch.record_span,+ reach: media_stretch.reach,+ };+ (+ barrier_of_plan,+ media_stretch.record_span.begin,+ Reach::Within(media_stretch.reach),+ )+ }+ BarrierBeingBuilt::NestedNodeBand {+ band_being_built_index: nested_band_being_built_index,+ } => {+ let nested_band = &self.bands_being_built[nested_band_being_built_index.0];+ let first_record_position_of_nested_band = placement.record_stretches+ [nested_band.first_record_stretch_index.0]+ .record_span+ .begin;+ let cut_reach = self.nodes[nested_band.placement_node_index.0].reach_in_parent_node;+ self.emit_band(nested_band_being_built_index, bands);+ (+ BarrierOfPlan::NestedBand,+ first_record_position_of_nested_band,+ cut_reach,+ )+ }+ };+ cuts.push(BarrierCut {+ barrier_first_record_position,+ cut_reach,+ layer_above_cut: LayerIndex(cuts.len() + 1),+ });+ barriers_of_plan.push(barrier_of_plan);+ }++ // A record draws nothing past the reach of its stretch, so the layers it is replayed into anywhere else stay+ // empty.+ let mut reach_of_painted_layers = vec![IntRect::default(); cuts.len() + 1];+ let mut record_spans: Vec<ListSpan> = Vec::with_capacity(own_record_stretch_indices.len());+ for &stretch_index in &own_record_stretch_indices {+ let stretch = &placement.record_stretches[stretch_index.0];+ let stretch_span = stretch.record_span;+ for_each_layer_records_go_into(+ &cuts,+ LayerIndex(0),+ stretch_span.begin,+ stretch.reach,+ |layer, part_of_reach| {+ reach_of_painted_layers[layer.0] = reach_of_painted_layers[layer.0].united(part_of_reach);+ },+ );+ match record_spans.last_mut() {+ Some(last) if last.end == stretch_span.begin => last.end = stretch_span.end,+ _ => record_spans.push(stretch_span),+ }+ }+ let band = &mut bands[band_position];+ band.record_spans = record_spans;+ band.reach_of_layer_below_all_cuts = reach_of_painted_layers[0];+ band.cuts = barriers_of_plan+ .into_iter()+ .zip(&reach_of_painted_layers[1..])+ .map(|(barrier, &reach_of_layer_above_cut)| CutOfPlan {+ barrier,+ reach_of_layer_above_cut,+ })+ .collect();+ }+}++// The plan of the stack, or the first reason found while the stack is cut into bands why the list goes as one layer+// after all.+fn assemble_plan(+ inputs: &LayerStackInputs<'_>,+ placement: &ListPlacement,+ swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>>,+ tiles_hold_content_moving_within_space_by_space_index: Vec<bool>,+ spaces: &[RasterSpace],+ layering_obstacles: &LayeringObstacles,+) -> Result<LayeredPlan, WhyListIsOneLayer> {+ let mut stack_being_built = StackBeingBuilt {+ placement,+ spaces,+ nodes: Vec::new(),+ node_of_run_group: Vec::new(),+ children_of_node: Vec::new(),+ bands_being_built: Vec::new(),+ composited_node_once_decided_by_placed_effect: vec![None; placement.placed_effects.len()],+ composited_effects_around_node_by_node_index: Vec::new(),+ };+ stack_being_built.find_or_add_node(RasterSpaceIndex::VIEWPORT, &[]);+ stack_being_built.node_of_run_group = placement+ .run_groups+ .iter()+ .map(|run_group| stack_being_built.find_or_add_node(run_group.raster_space_index, &run_group.composite_clips))+ .collect();+ stack_being_built.limit_reach_of_moving_space_nodes_to_content_swept_over_how_they_move(+ &swept_reach_in_parent_space_by_space_index,+ );+ stack_being_built.cut_into_bands()?;+ if layering_obstacles.sorts_planes_by_depth+ && contexts_sorting_planes_by_depth_hold_effects_that_read_or_are_composited(+ inputs,+ placement,+ &stack_being_built.nodes,+ )+ {+ return Err(WhyListIsOneLayer::SortingContext3D);+ }+ let mut bands = Vec::with_capacity(stack_being_built.bands_being_built.len());+ stack_being_built.emit_band(BandBeingBuiltIndex(0), &mut bands);++ let plan = LayeredPlan {+ nodes: stack_being_built.nodes,+ bands,+ tiles_hold_content_moving_within_space_by_space_index,+ swept_reach_in_parent_space_by_space_index,+ };+ if plan_holds_more_than_compositor_decodes(&plan) {+ return Err(WhyListIsOneLayer::PlanHoldsMoreThanCompositorDecodes);+ }+ Ok(plan)+}++// A 3D sorting context that sorts its planes by depth is placed whole into the tiles of one band, which replay it+// whole, as sorting its planes reads all of them. That holds only where nothing inside it reads what is below it or is+// composited apart from it.+fn contexts_sorting_planes_by_depth_hold_effects_that_read_or_are_composited(+ inputs: &LayerStackInputs<'_>,+ placement: &ListPlacement,+ nodes: &[NodeOfPlan],+) -> bool {+ let tree = inputs.tree;+ let run_groups = inputs.list.run_groups(tree);+ let mut marks = [effects_of_marked_runs(inputs.list, tree, |run_index| {+ run_groups.run_is_sorted_by_depth(run_index)+ })];+ mark_effects_around_marked_effects(tree, &mut marks);+ let [effect_holds_run_sorted_by_depth_by_effect_index] = marks;+ placement+ .backdrop_readers_in_paint_order+ .iter()+ .copied()+ .chain(nodes.iter().filter_map(|node| node.composited_effect))+ .any(|effect| effect_holds_run_sorted_by_depth_by_effect_index[effect.0 as usize])+}++/// Works out the layers of a list from where `place_list` placed its parts among `spaces`, whose extents are not filled+/// in.+///+/// A plan of more nodes, bands, cuts or spans than the compositor decodes, or of composited effects nested deeper than+/// `MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS`, gives the list one layer. Within those limits no layer that an effect the+/// compositor composites or a canvas, video or nested context needs is given up, as that would draw the list wrong,+/// and a layer holds tiles only where its content reaches, which the pool of tiles gives back.+///+/// A plan of more layers that fails the checks the compositor runs on a plan it receives is a bug of the planner. A+/// build with debug assertions panics on it, and other builds give the list one layer.+fn build_layer_stack(+ inputs: &LayerStackInputs<'_>,+ placement: ListPlacement,+ swept_reach_in_parent_space_by_space_index: Vec<Option<IntRect>>,+ tiles_hold_content_moving_within_space_by_space_index: Vec<bool>,+ spaces: Vec<RasterSpace>,+ layering_obstacles: LayeringObstacles,+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+) -> PlannedLayers {+ let stack_of_plan = assemble_plan(+ inputs,+ &placement,+ swept_reach_in_parent_space_by_space_index,+ tiles_hold_content_moving_within_space_by_space_index,+ &spaces,+ &layering_obstacles,+ )+ .and_then(|plan| {+ LayerStack::of_plan_passing_checks(+ plan,+ spaces,+ inputs.list,+ inputs.tree,+ inputs.viewport_rect,+ layering_obstacles,+ nesting_of_live_effects,+ )+ .map_err(|why_plan_fails_checks| {+ debug_assert!(+ false,+ "the compositor refuses a plan of layers the planner made: {why_plan_fails_checks}"+ );+ eprintln!(+ "WebContent: Sending one layer, as the compositor refuses the plan of layers: {why_plan_fails_checks}"+ );+ WhyListIsOneLayer::PlanFailsChecksOfCompositor+ })+ });+ match stack_of_plan {+ Ok(stack) => PlannedLayers { stack, placement },+ Err(why_list_is_one_layer) => one_layer(inputs, why_list_is_one_layer, layering_obstacles, placement),+ }+}++fn one_layer(+ inputs: &LayerStackInputs<'_>,+ why_list_is_one_layer: WhyListIsOneLayer,+ layering_obstacles: LayeringObstacles,+ placement: ListPlacement,+) -> PlannedLayers {+ PlannedLayers {+ stack: LayerStack::one_layer_replaying_whole_list(+ inputs.viewport_rect,+ inputs.list.whole_span(),+ Some(why_list_is_one_layer),+ layering_obstacles,+ ),+ placement,+ }+}++// The scroll offsets a plan reads of `scroll_offsets`: zero for each node that `leaves_out_scroll_offset_of_node` names.+fn scroll_offsets_layer_plans_read(+ scroll_offsets: &[FloatPoint],+ leaves_out_scroll_offset_of_node: &[bool],+) -> Vec<FloatPoint> {+ scroll_offsets+ .iter()+ .enumerate()+ .map(|(node_index, &scroll_offset)| {+ if leaves_out_scroll_offset_of_node+ .get(node_index)+ .copied()+ .unwrap_or(false)+ {+ FloatPoint::default()+ } else {+ scroll_offset+ }+ })+ .collect()+}++/// Plans the layers of a list, and gives the stack with where it placed the parts of the list. The plan holds for every+/// sample of the compositor's animations and wherever the compositor scrolls the nodes it scrolls. Where the window+/// server can show the media of the stack is left to be worked out for each frame.+pub fn plan_layer_stack(inputs: &LayerStackInputs<'_>) -> PlannedLayers {+ let anchors_of_tree = RasterSpaceAnchorsOfTree::of(inputs.tree);+ let scroll_offsets_read =+ scroll_offsets_layer_plans_read(inputs.scroll_offsets, &anchors_of_tree.leaves_out_scroll_offset_of_node);+ plan_layer_stack_at_anchors(+ &LayerStackInputs {+ scroll_offsets: &scroll_offsets_read,+ ..*inputs+ },+ &anchors_of_tree,+ )+}++// `anchors_of_tree` are those of `inputs.tree`, and `inputs.scroll_offsets` hold zero for each node whose offset+// `RasterSpaceAnchorsOfTree::leaves_out_scroll_offset_of_node` names.+fn plan_layer_stack_at_anchors(+ inputs: &LayerStackInputs<'_>,+ anchors_of_tree: &RasterSpaceAnchorsOfTree,+) -> PlannedLayers {+ let nesting_of_live_effects = NestingOfLiveEffects::of(inputs.tree);+ let layering_obstacles =+ LayeringObstacles::of_with_nesting_of_live_effects(inputs.list, inputs.tree, &nesting_of_live_effects);+ if let Some(why) = why_list_cannot_be_layered(inputs, &layering_obstacles) {+ return one_layer(inputs, why, layering_obstacles, ListPlacement::default());+ }+ let (spaces, geometries) = spaces_with_geometries(+ inputs.tree,+ anchors_of_tree,+ inputs.scroll_offsets,+ inputs.viewport_rect,+ );+ let spaces_of_stack = spaces.spaces().to_vec();+ let (placement, swept_reach_in_parent_space_by_space_index, tiles_hold_content_moving_within_space_by_space_index) =+ place_list(inputs, spaces, &geometries, &nesting_of_live_effects);+ build_layer_stack(+ inputs,+ placement,+ swept_reach_in_parent_space_by_space_index,+ tiles_hold_content_moving_within_space_by_space_index,+ spaces_of_stack,+ layering_obstacles,+ &nesting_of_live_effects,+ )+}++/// What a plan of the layers of a list is made from, all of which WebContent publishes: the list, the tree, the viewport+/// rect, and of the scroll offsets, those the plan reads. A plan made from inputs holds for others that plan alike.+pub struct InputsOfLayerPlan {+ list: Arc<DisplayListStorage>,+ tree: Arc<VisualContextTree>,+ viewport_rect: IntRect,+ anchors_of_tree: Arc<RasterSpaceAnchorsOfTree>,+ scroll_offsets_plan_reads: Vec<FloatPoint>,+}++impl InputsOfLayerPlan {+ pub fn new(+ list: Arc<DisplayListStorage>,+ tree: Arc<VisualContextTree>,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+ ) -> Self {+ Self::new_after(None, list, tree, scroll_offsets, viewport_rect)+ }++ /// As `new`, but where `earlier` inputs were made for the same tree, what plans work out of the tree alone comes+ /// from them.+ pub fn new_after(+ earlier: Option<&Self>,+ list: Arc<DisplayListStorage>,+ tree: Arc<VisualContextTree>,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+ ) -> Self {+ let anchors_of_tree = match earlier {+ Some(earlier) if Arc::ptr_eq(&earlier.tree, &tree) => earlier.anchors_of_tree.clone(),+ _ => Arc::new(RasterSpaceAnchorsOfTree::of(&tree)),+ };+ Self {+ scroll_offsets_plan_reads: scroll_offsets_layer_plans_read(+ scroll_offsets,+ &anchors_of_tree.leaves_out_scroll_offset_of_node,+ ),+ list,+ tree,+ viewport_rect,+ anchors_of_tree,+ }+ }++ /// The inputs of the same list and tree under other scroll offsets and another viewport rect.+ pub fn with_scroll_offsets_and_viewport_rect(&self, scroll_offsets: &[FloatPoint], viewport_rect: IntRect) -> Self {+ Self::new_after(+ Some(self),+ self.list.clone(),+ self.tree.clone(),+ scroll_offsets,+ viewport_rect,+ )+ }++ pub fn viewport_rect(&self) -> IntRect {+ self.viewport_rect+ }++ /// Whether a plan made from these inputs is the plan of `other`: the lists hold the same chunks in the same order,+ /// the trees have the same content, the viewport rects are the same, and the plan reads the same scroll offsets.+ pub fn plan_alike_as(&self, other: &Self) -> bool {+ // A list of scroll offsets leaves out the zero offsets of the nodes past its end.+ let offset_at =+ |offsets: &[FloatPoint], node_index: usize| offsets.get(node_index).copied().unwrap_or_default();+ let node_count = self+ .scroll_offsets_plan_reads+ .len()+ .max(other.scroll_offsets_plan_reads.len());+ self.viewport_rect == other.viewport_rect+ && (0..node_count).all(|node_index| {+ offset_at(&self.scroll_offsets_plan_reads, node_index)+ == offset_at(&other.scroll_offsets_plan_reads, node_index)+ })+ && (Arc::ptr_eq(&self.list, &other.list) || self.list.holds_same_chunks_in_same_order_as(&other.list))+ && (Arc::ptr_eq(&self.tree, &other.tree) || self.tree.has_same_content_as(&other.tree))+ }++ /// Plans the layers of the list under these inputs.+ pub fn plan(&self) -> PlannedLayers {+ plan_layer_stack_at_anchors(+ &LayerStackInputs {+ list: &self.list,+ tree: &self.tree,+ scroll_offsets: &self.scroll_offsets_plan_reads,+ viewport_rect: self.viewport_rect,+ },+ &self.anchors_of_tree,+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::commands::{CanvasId, ContextRef};+ use crate::display_list::layers::{+ CutsOfCell, LayerIdentity, NodeNamesFromIndices, WindowServerPresentationOfMedia, media_name,+ };+ use crate::display_list::test_fixtures::{+ GREEN, ListOfOneChunk, VIEWPORT, animation_of, canvas, effects, fill, frosted_glass, opacity_animation_of,+ scroll_node, scroll_record, spinning, transform, transform_animation_of, tree_with_document_scroll,+ tree_with_root_isolation_effect,+ };+ use crate::display_list::tiles::TILE_SIZE_IN_DEVICE_PIXELS;+ use crate::node_slot_id::NodeSlotId;+ use crate::visual_context::{+ CompositorScrollNodeRecord, CompositorScrollTable, EffectsData, SpatialData, TransformData, TransformDataRole,+ };+ use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatMatrix4x4, FloatRect};++ fn kinds_of_layers_from_base_up_that_may_hold_content(stack: &LayerStack) -> Vec<String> {+ stack+ .layers+ .iter()+ .enumerate()+ .filter(|(index, layer)| {+ *index == stack.base_layer.0 || (*index > stack.base_layer.0 && layer.may_hold_content)+ })+ .map(|(index, layer)| {+ let space = stack.name_of_space(+ stack.nodes[layer.placement_node_index.0].raster_space_index,+ &NodeNamesFromIndices,+ );+ match layer.identity {+ LayerIdentity::Painted {+ band_ordinal_in_node: band,+ above_barrier,+ ..+ } => {+ let kind = if index == stack.base_layer.0 { "base" } else { "painted" };+ let above = above_barrier.map_or(String::new(), |_| {+ format!(+ " above {}",+ stack.name_of_barrier_below(LayerIndex(index), &NodeNamesFromIndices)+ )+ });+ format!("{kind} {space} band {band}{above}")+ }+ LayerIdentity::Media { content, ordinal } => format!("{} #{ordinal} {space}", media_name(content)),+ }+ })+ .collect()+ }++ #[test]+ fn samples_of_a_transform_animation_leave_the_placement_alike() {+ let (mut tree, _, document) = tree_with_document_scroll();+ let moving = transformed_context(&mut tree, document, FloatRect::new(0.0, 0.0, 50.0, 50.0));+ tree.set_visual_animations(vec![transform_animation_of(+ moving.spatial,+ crate::host::FfiVisualAnimationTransformOperationKind::TranslateX,+ 0.0,+ 400.0,+ )]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(canvas(IntRect::new(500, 300, 200, 100), 1), document)+ .with(fill(IntRect::new(100, 300, 50, 50), GREEN), moving);+ let at_start = list.planned(&tree.with_visual_animation_samples(0), &[]);+ let halfway = list.planned(&tree.with_visual_animation_samples(500_000_000), &[]);+ assert_eq!(at_start.placement, halfway.placement);+ assert_eq!(+ at_start.stack.swept_reach_in_parent_space_by_space_index,+ halfway.stack.swept_reach_in_parent_space_by_space_index+ );+ assert_eq!(+ at_start.stack.tiles_hold_content_moving_within_space_by_space_index,+ halfway.stack.tiles_hold_content_moving_within_space_by_space_index+ );+ // Wherever the animation takes the box, it can go over the canvas, so it sits above it.+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&halfway.stack),+ [+ "base document band 0",+ "canvas #0 document",+ "painted document band 0 above L2"+ ]+ );+ }++ #[test]+ fn a_fixed_header_painted_after_a_scrolling_document_leaves_the_base_layer_in_the_document() {+ let (tree, viewport, document) = tree_with_document_scroll();+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(0, 0, 800, 50), GREEN), viewport);+ let planned = list.planned(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&planned.stack),+ [+ "base document band 0",+ "painted viewport band 0 above band 0 of document"+ ]+ );+ let storage = DisplayListStorage::of_builder(&list.builder);+ assert_eq!(planned.layers_of_record(storage.span_of_run(1).begin).len(), 1);+ }++ #[test]+ fn content_reaching_too_many_cells_to_follow_marks_no_layer_below_a_cut_that_covers_it() {+ let (mut tree, _, document) = tree_with_document_scroll();+ let taller_than_the_cells_followed_one_by_one = IntRect::new(0, 0, 800, 4100 * TILE_SIZE_IN_DEVICE_PIXELS);+ let mut scroll_table = tree.compositor_scroll_table().clone();+ let mut document_scrolling_past_the_cells_followed_one_by_one = scroll_table.nodes.to_vec();+ document_scrolling_past_the_cells_followed_one_by_one[0]+ .max_scroll_offset+ .y = taller_than_the_cells_followed_one_by_one.height as f32;+ scroll_table.nodes = document_scrolling_past_the_cells_followed_one_by_one.into();+ assert!(tree.set_compositor_scroll_table(scroll_table));+ let sliding_panel = transformed_context(+ &mut tree,+ document,+ taller_than_the_cells_followed_one_by_one.to_float(),+ );+ tree.set_visual_animations(vec![sliding(sliding_panel.spatial)]);+ let list = ListOfOneChunk::default()+ .with(fill(taller_than_the_cells_followed_one_by_one, GREEN), sliding_panel)+ .with(fill(taller_than_the_cells_followed_one_by_one, GREEN), document);+ let planned = list.planned(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&planned.stack),+ [+ "base viewport band 0",+ "painted animated@s2 in document band 0",+ "painted document band 0 above band 0 of animated@s2 in document"+ ]+ );+ }++ fn sliding(node: SpatialNodeIndex) -> crate::visual_animation::VisualAnimation {+ transform_animation_of(+ node,+ crate::host::FfiVisualAnimationTransformOperationKind::TranslateX,+ 0.0,+ 300.0,+ )+ }++ fn transformed_context(tree: &mut VisualContextTree, parent: ContextRef, bounds: FloatRect) -> ContextRef {+ let spatial = tree.append_spatial(SpatialData::Transform(transform(bounds)), parent.spatial);+ ContextRef { spatial, ..parent }+ }++ fn clipped_context(+ tree: &mut VisualContextTree,+ parent: ContextRef,+ rect: IntRect,+ corner_radii: libgfx_rust::CornerRadii,+ ) -> ContextRef {+ let clip = tree.append_clip(+ crate::visual_context::ClipNodeData::Rect(crate::visual_context::ClipData {+ rect: rect.to_float(),+ corner_radii,+ mode: crate::display_list::commands::ClipMode::Intersect,+ }),+ parent.clip,+ parent.spatial,+ );+ ContextRef { clip, ..parent }+ }++ // LibWeb appends an element's effects node at the spatial node of its parent, above the element's transform.+ fn element_with_own_effect(+ tree: &mut VisualContextTree,+ transformed: ContextRef,+ parent: ContextRef,+ opacity: f32,+ ) -> ContextRef {+ let effect = tree.append_effect(+ effects(opacity, CompositingAndBlendingOperator::Normal),+ parent.effect,+ parent.spatial,+ parent.clip,+ );+ ContextRef { effect, ..transformed }+ }++ fn space_names(stack: &LayerStack) -> Vec<String> {+ (0..stack.spaces.len())+ .map(|index| stack.name_of_space(RasterSpaceIndex(index), &NodeNamesFromIndices))+ .collect()+ }++ #[test]+ fn a_spinner_is_rastered_in_its_own_space_and_reaches_the_circle_it_turns_in() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner)+ .with(fill(IntRect::new(0, 100, 100, 100), GREEN), viewport)+ .stack(&tree, &[]);+ assert_eq!(space_names(&stack), ["viewport", "animated@s1 in viewport"]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&stack),+ [+ "base viewport band 0",+ "painted animated@s1 in viewport band 0",+ "painted viewport band 0 above band 0 of animated@s1 in viewport"+ ]+ );+ assert_eq!(+ stack.swept_reach_in_parent_space_by_space_index[1],+ Some(IntRect::new(34, 34, 72, 72))+ );+ }++ #[test]+ fn a_spinner_under_a_scale_far_below_the_smallest_raster_scale_is_rastered_at_the_smallest() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let shrunk = transformed_context(&mut tree, viewport, FloatRect::new(0.0, 0.0, 100.0, 100.0));+ let SpatialData::Transform(shrinking) = &mut tree.spatial_nodes[shrunk.spatial.0 as usize].data else {+ unreachable!()+ };+ shrinking.matrix = libgfx_rust::scale_matrix(0.001, 0.001, 1.0);+ let spinner = transformed_context(&mut tree, shrunk, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner)+ .stack(&tree, &[]);+ let raster_scales: Vec<f32> = stack+ .spaces+ .iter()+ .filter_map(|space| match space.anchor_kind {+ RasterSpaceAnchorKind::AnimatedTransform { raster_scale } => Some(raster_scale),+ _ => None,+ })+ .collect();+ assert_eq!(raster_scales, [1.0 / 64.0]);+ }++ #[test]+ fn samples_of_a_spinner_leave_its_space_and_raster_geometry_alike() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner);+ let geometry_of_spinner_space_at = |time_ns: i64| {+ let sample = tree.with_visual_animation_samples(time_ns);+ let (_, geometries) =+ spaces_with_geometries(&sample, &RasterSpaceAnchorsOfTree::of(&sample), &[], VIEWPORT);+ geometries[1].raster.world.draw_matrix(spinner.spatial)+ };+ assert_eq!(+ geometry_of_spinner_space_at(0),+ geometry_of_spinner_space_at(250_000_000)+ );+ let at_start = list.planned(&tree.with_visual_animation_samples(0), &[]);+ let a_quarter_in = list.planned(&tree.with_visual_animation_samples(250_000_000), &[]);+ assert_eq!(at_start, a_quarter_in);+ }++ #[test]+ fn an_unclipped_slide_reaches_where_its_keyframes_take_it() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let slider = transformed_context(&mut tree, viewport, FloatRect::new(0.0, 0.0, 50.0, 50.0));+ tree.set_visual_animations(vec![sliding(slider.spatial)]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 50, 50), GREEN), slider)+ .with(fill(IntRect::new(0, 50, 100, 100), GREEN), viewport)+ .stack(&tree, &[]);+ assert_eq!(space_names(&stack), ["viewport", "animated@s1 in viewport"]);+ assert_eq!(+ stack.swept_reach_in_parent_space_by_space_index[1],+ Some(IntRect::new(0, 0, 356, 56))+ );+ }++ #[test]+ fn a_slide_within_a_rounded_clip_is_composited_within_it() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let track = clipped_context(+ &mut tree,+ viewport,+ IntRect::new(0, 0, 200, 50),+ libgfx_rust::CornerRadii::uniform(10),+ );+ let slider = transformed_context(&mut tree, track, FloatRect::new(0.0, 0.0, 50.0, 50.0));+ tree.set_visual_animations(vec![sliding(slider.spatial)]);+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 200, 50), GREEN), track)+ .with(fill(IntRect::new(0, 0, 50, 50), GREEN), slider)+ .planned(&tree, &[]);+ let lines: Vec<String> = planned+ .layer_lines(+ &WindowServerPresentationOfMedia::default(),+ &NodeNamesFromIndices,+ |_| None,+ )+ .into_iter()+ .map(|(_, line)| line)+ .collect();+ assert_eq!(+ lines,+ [+ "[L0] base space=viewport",+ "[L1] painted space=animated@s1 in viewport composited within [0,0 200x50] radii=(10,10,10,10) of viewport"+ ]+ );+ }++ #[test]+ fn a_skew_or_an_overshooting_slide_stays_in_the_tiles_around_it() {+ use crate::host::FfiVisualAnimationTransformOperationKind as Kind;+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let skewed = transformed_context(&mut tree, viewport, FloatRect::new(0.0, 0.0, 50.0, 50.0));+ let overshooting = transformed_context(&mut tree, viewport, FloatRect::new(0.0, 100.0, 50.0, 50.0));+ let mut overshooting_slide = sliding(overshooting.spatial);+ overshooting_slide.keyframes[0].easing = crate::easing::Easing::CubicBezier {+ x1: 0.3,+ y1: 1.6,+ x2: 0.6,+ y2: 1.0,+ };+ tree.set_visual_animations(vec![+ transform_animation_of(skewed.spatial, Kind::SkewX, 0.0, 0.3),+ overshooting_slide,+ ]);+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 50, 50), GREEN), skewed)+ .with(fill(IntRect::new(0, 100, 50, 50), GREEN), overshooting)+ .planned(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&planned.stack),+ ["base viewport band 0"]+ );+ assert_eq!(+ planned.placement.animations_without_layers,+ [+ (+ AnimatedNode::Transform(skewed.spatial),+ WhyAnimationHasNoLayer::NothingBoundsWhereItMoves+ ),+ (+ AnimatedNode::Transform(overshooting.spatial),+ WhyAnimationHasNoLayer::NothingBoundsWhereItMoves+ )+ ]+ );+ }++ #[test]+ fn a_spinner_with_its_own_opacity_is_composited_inside_it() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ let translucent_spinner = element_with_own_effect(&mut tree, spinner, viewport, 0.5);+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), translucent_spinner)+ .planned(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&planned.stack),+ ["base viewport band 0", "painted animated@s1 in viewport band 0"]+ );+ assert_eq!(+ whys_of_composited_effects(&planned),+ [(+ translucent_spinner.effect,+ WhyEffectIsComposited::ItAppliesOverATransformTheCompositorAnimates+ )]+ );+ }++ #[test]+ fn an_element_that_fades_and_spins_is_composited_through_both() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ let fading_spinner = element_with_own_effect(&mut tree, spinner, viewport, 1.0);+ tree.set_visual_animations(vec![+ spinning(spinner.spatial),+ opacity_animation_of(fading_spinner.effect, 0.2, 1.0),+ ]);+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), fading_spinner)+ .planned(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&planned.stack),+ ["base viewport band 0", "painted animated@s1 in viewport band 0"]+ );+ assert_eq!(+ whys_of_composited_effects(&planned),+ // The fading effect pushes a layer at every sample, so it applies over the spinner at every sample.+ [(+ fading_spinner.effect,+ WhyEffectIsComposited::ItAppliesOverATransformTheCompositorAnimates+ )]+ );+ }++ #[test]+ fn a_spinner_in_a_translucent_group_with_siblings_is_placed_with_the_group() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let group = tree.append_effect_node_under(viewport, effects(0.5, CompositingAndBlendingOperator::Normal));+ let spinner = transformed_context(&mut tree, group, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), group)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner)+ .stack(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&stack),+ ["base viewport band 0"]+ );+ }++ #[test]+ fn a_spinner_over_an_earlier_canvas_stays_in_the_tiles_around_it() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let planned = ListOfOneChunk::default()+ .with(canvas(IntRect::new(0, 0, 200, 120), 1), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner)+ .planned(&tree, &[]);+ assert_eq!(+ planned.placement.animations_without_layers,+ [(+ AnimatedNode::Transform(spinner.spatial),+ WhyAnimationHasNoLayer::ItCanShowOverAnEarlierCanvasOrVideo+ )]+ );+ }++ #[test]+ fn a_spinner_holding_a_canvas_gives_the_canvas_a_layer_in_its_space() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner = transformed_context(&mut tree, viewport, FloatRect::new(50.0, 50.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(canvas(IntRect::new(50, 50, 40, 40), 1), spinner)+ .stack(&tree, &[]);+ assert_eq!(+ kinds_of_layers_from_base_up_that_may_hold_content(&stack),+ ["base viewport band 0", "canvas #0 animated@s1 in viewport"]+ );+ }++ #[test]+ fn a_fade_over_an_earlier_canvas_stays_in_the_tiles_around_it() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let controls = tree.append_effect_node_under(viewport, effects(1.0, CompositingAndBlendingOperator::Normal));+ tree.set_visual_animations(vec![opacity_animation_of(controls.effect, 0.2, 1.0)]);+ let planned = ListOfOneChunk::default()+ .with(canvas(IntRect::new(0, 0, 200, 120), 1), viewport)+ .with(fill(IntRect::new(0, 80, 200, 40), GREEN), controls)+ .planned(&tree, &[]);+ assert!(planned.stack.composited_effects.is_empty());+ assert_eq!(+ planned.placement.animations_without_layers,+ [(+ AnimatedNode::Effect(controls.effect),+ WhyAnimationHasNoLayer::ItCanShowOverAnEarlierCanvasOrVideo+ )]+ );+ }++ // Before the animation starts, at its first keyframe, between its keyframes, at its last keyframe and after its+ // end, for an animation that `played_once_after_a_delay` gives.+ const SAMPLE_TIMES_NS: [i64; 6] = [0, 200_000_000, 450_000_000, 700_000_000, 1_200_000_000, 2_000_000_000];++ fn played_once_after_a_delay(+ animation: crate::visual_animation::VisualAnimation,+ ) -> crate::visual_animation::VisualAnimation {+ crate::visual_animation::VisualAnimation {+ timing: crate::animation_timing::AnimationEffectTiming {+ start_delay: crate::animation_timing::TimeValue::milliseconds(200.0),+ iteration_count: 1.0,+ ..animation.timing+ },+ ..animation+ }+ }++ fn layers_planned_alike_for_every_sample(list: &ListOfOneChunk, tree: &VisualContextTree) -> PlannedLayers {+ let planned = list.planned(tree, &[]);+ for time_ns in SAMPLE_TIMES_NS {+ assert!(+ list.planned(&tree.with_visual_animation_samples(time_ns), &[]) == planned,+ "the plan of the sample at {time_ns} ns differs from the plan of the tree"+ );+ }+ planned+ }++ fn filter_function(+ kind: crate::filter_bytes::FfiFilterFunctionKind,+ amount: f32,+ ) -> crate::filter_bytes::FfiFilterFunction {+ crate::filter_bytes::FfiFilterFunction {+ kind,+ amount,+ offset_x: 0.0,+ offset_y: 0.0,+ color: Color::TRANSPARENT,+ color_operation: libgfx_rust::ColorFilterType::Grayscale,+ }+ }++ fn grayscale(amount: f32) -> crate::filter_bytes::FfiFilterFunction {+ filter_function(crate::filter_bytes::FfiFilterFunctionKind::Color, amount)+ }++ fn blur(radius: f32) -> crate::filter_bytes::FfiFilterFunction {+ filter_function(crate::filter_bytes::FfiFilterFunctionKind::Blur, radius)+ }++ fn filter_bytes_of(functions: &[crate::filter_bytes::FfiFilterFunction]) -> Option<std::sync::Arc<Vec<u8>>> {+ crate::filter_bytes::filter_functions_graph(functions.iter().copied().map(libgfx_rust::filter::Filter::from))+ .map(|graph| std::sync::Arc::new(graph.serialize()))+ }++ fn filter_animation_of(+ effect: EffectNodeIndex,+ from: Vec<crate::filter_bytes::FfiFilterFunction>,+ to: Vec<crate::filter_bytes::FfiFilterFunction>,+ ) -> crate::visual_animation::VisualAnimation {+ let keyframe = |offset: f64, functions| crate::visual_animation::VisualAnimationKeyframe {+ offset,+ easing: crate::easing::Easing::default(),+ value: crate::visual_animation::VisualAnimationValue::Filter(functions),+ };+ animation_of(+ crate::host::FfiVisualAnimationTargetKind::Filter,+ effect.0,+ vec![keyframe(0.0, from), keyframe(1.0, to)],+ )+ }++ fn element_with_filter(+ tree: &mut VisualContextTree,+ parent: ContextRef,+ filter: Option<std::sync::Arc<Vec<u8>>>,+ ) -> ContextRef {+ tree.append_effect_node_under(+ parent,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter,+ backdrop_filter: None,+ }),+ )+ }++ #[derive(Clone, Copy, Debug)]+ enum Animated {+ OpacityFromOne,+ ColorFilter,+ BlurFilter,+ BlurFilterFromNone,+ Translation,+ Rotation,+ Scale,+ RotationOutOfPlane,+ }++ #[derive(Clone, Copy, Debug)]+ enum UnderAnimatedNode {+ Fill,+ Canvas,+ BackdropFilter,+ }++ const ELEMENT: IntRect = IntRect::new(50, 50, 40, 40);++ // An element whose own value equals that of the first keyframe of its animation, between two fills of the page.+ fn page_with_animated_element(+ animated: Animated,+ under_animated_node: UnderAnimatedNode,+ ) -> (VisualContextTree, ListOfOneChunk, ContextRef) {+ use crate::host::FfiVisualAnimationTransformOperationKind as Kind;+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let (element, animation) = match animated {+ Animated::OpacityFromOne => {+ let element =+ tree.append_effect_node_under(viewport, effects(1.0, CompositingAndBlendingOperator::Normal));+ (element, opacity_animation_of(element.effect, 1.0, 0.0))+ }+ Animated::ColorFilter => {+ let element = element_with_filter(&mut tree, viewport, filter_bytes_of(&[grayscale(0.0)]));+ let animation = filter_animation_of(element.effect, vec![grayscale(0.0)], vec![grayscale(1.0)]);+ (element, animation)+ }+ Animated::BlurFilter => {+ let element = element_with_filter(&mut tree, viewport, filter_bytes_of(&[blur(0.0)]));+ let animation = filter_animation_of(element.effect, vec![blur(0.0)], vec![blur(4.0)]);+ (element, animation)+ }+ Animated::BlurFilterFromNone => {+ let element = element_with_filter(&mut tree, viewport, None);+ let animation = filter_animation_of(element.effect, Vec::new(), vec![blur(4.0)]);+ (element, animation)+ }+ Animated::Translation | Animated::Rotation | Animated::Scale | Animated::RotationOutOfPlane => {+ let element = transformed_context(&mut tree, viewport, ELEMENT.to_float());+ let (kind, from, to) = match animated {+ Animated::Translation => (Kind::TranslateX, 0.0, 100.0),+ Animated::Rotation => (Kind::Rotate, 0.0, 360.0),+ Animated::Scale => (Kind::Scale, 1.0, 2.0),+ _ => (Kind::RotateX, 0.0, 180.0),+ };+ (element, transform_animation_of(element.spatial, kind, from, to))+ }+ };+ tree.set_visual_animations(vec![played_once_after_a_delay(animation)]);+ let list = ListOfOneChunk::default().with(fill(IntRect::new(0, 0, 200, 200), GREEN), viewport);+ let list = match under_animated_node {+ UnderAnimatedNode::Fill => list.with(fill(ELEMENT, GREEN), element),+ UnderAnimatedNode::Canvas => list.with(canvas(ELEMENT, 1), element),+ UnderAnimatedNode::BackdropFilter => {+ let glass = frosted_glass(&mut tree, element, ELEMENT);+ list.with(fill(ELEMENT, GREEN), glass)+ }+ };+ let list = list.with(fill(IntRect::new(0, 150, 200, 50), GREEN), viewport);+ (tree, list, element)+ }++ #[test]+ fn every_sample_of_an_animation_starting_at_the_value_of_the_tree_is_planned_as_the_tree_is() {+ for animated in [+ Animated::OpacityFromOne,+ Animated::ColorFilter,+ Animated::BlurFilter,+ Animated::BlurFilterFromNone,+ Animated::Translation,+ Animated::Rotation,+ Animated::Scale,+ Animated::RotationOutOfPlane,+ ] {+ for under_animated_node in [+ UnderAnimatedNode::Fill,+ UnderAnimatedNode::Canvas,+ UnderAnimatedNode::BackdropFilter,+ ] {+ let (tree, list, _) = page_with_animated_element(animated, under_animated_node);+ let stack = layers_planned_alike_for_every_sample(&list, &tree).stack;+ assert!(+ stack.why_list_is_one_layer.is_none(),+ "{animated:?} over {under_animated_node:?} is one layer: {:?}",+ stack.why_list_is_one_layer+ );+ }+ }+ }++ fn whys_of_composited_effects(planned: &PlannedLayers) -> Vec<(EffectNodeIndex, WhyEffectIsComposited)> {+ planned+ .composited_effects_with_why_and_backdrop_read_reach()+ .map(|(composited, why, _)| (composited.effect, why))+ .collect()+ }++ #[test]+ fn an_opacity_animation_starting_opaque_is_composited_at_every_sample() {+ let (tree, list, element) = page_with_animated_element(Animated::OpacityFromOne, UnderAnimatedNode::Fill);+ assert!(+ tree.with_visual_animation_samples(0)+ .effect_pushes_layer_at_replay(element.effect)+ );+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(+ whys_of_composited_effects(&planned),+ [(element.effect, WhyEffectIsComposited::TheCompositorAnimatesIt)]+ );+ }++ #[test]+ fn a_backdrop_filter_in_an_element_whose_opacity_is_animated_reads_the_layer_of_the_element() {+ let (tree, list, _) = page_with_animated_element(Animated::OpacityFromOne, UnderAnimatedNode::BackdropFilter);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert!(+ planned+ .placement+ .placed_effects+ .iter()+ .all(|placed| placed.why_composited_regardless_of_layer_content.is_some())+ );+ }++ #[test]+ fn a_color_filter_animation_is_composited_and_a_blur_animation_is_not() {+ let (tree, list, element) = page_with_animated_element(Animated::ColorFilter, UnderAnimatedNode::Fill);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(+ whys_of_composited_effects(&planned),+ [(element.effect, WhyEffectIsComposited::TheCompositorAnimatesIt)]+ );++ let (tree, list, element) = page_with_animated_element(Animated::BlurFilter, UnderAnimatedNode::Fill);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert!(planned.stack.composited_effects.is_empty());+ assert_eq!(+ planned.placement.animations_without_layers,+ [(+ AnimatedNode::Effect(element.effect),+ WhyAnimationHasNoLayer::ItsFilterSpreadsWhatItFilters+ )]+ );+ assert_eq!(+ planned.placement.why_compositor_cannot_composite_by_effect_index[element.effect.0 as usize],+ None+ );++ // Also where the tree holds no filter, as the first keyframe gives none.+ let (tree, list, element) = page_with_animated_element(Animated::BlurFilterFromNone, UnderAnimatedNode::Fill);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(+ planned.placement.animations_without_layers,+ [(+ AnimatedNode::Effect(element.effect),+ WhyAnimationHasNoLayer::ItsFilterSpreadsWhatItFilters+ )]+ );+ }++ #[test]+ fn an_element_with_its_own_blur_animated_between_color_filters_is_planned_for_its_blur() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let element = element_with_filter(&mut tree, viewport, filter_bytes_of(&[blur(5.0)]));+ tree.set_visual_animations(vec![filter_animation_of(+ element.effect,+ vec![grayscale(0.0)],+ vec![grayscale(1.0)],+ )]);+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 200, 200), GREEN), viewport)+ .with(fill(ELEMENT, GREEN), element)+ .planned(&tree, &[]);+ assert!(planned.stack.composited_effects.is_empty());+ assert_eq!(+ planned.placement.animations_without_layers,+ [(+ AnimatedNode::Effect(element.effect),+ WhyAnimationHasNoLayer::ItsFilterSpreadsWhatItFilters+ )]+ );+ }++ #[test]+ fn a_blur_animation_whose_easing_overshoots_reads_farther_than_is_known() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let element = element_with_filter(&mut tree, viewport, filter_bytes_of(&[blur(0.0)]));+ let mut animation = filter_animation_of(element.effect, vec![blur(0.0)], vec![blur(4.0)]);+ animation.keyframes[0].easing = crate::easing::Easing::CubicBezier {+ x1: 0.3,+ y1: 1.6,+ x2: 0.6,+ y2: 1.0,+ };+ tree.set_visual_animations(vec![animation]);+ assert_eq!(+ ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 200, 200), GREEN), viewport)+ .with(fill(ELEMENT, GREEN), element)+ .planned(&tree, &[])+ .placement+ .why_compositor_cannot_composite_by_effect_index[element.effect.0 as usize],+ Some(WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed)+ );+ }++ #[test]+ fn transforms_that_stay_in_the_plane_get_spaces_and_one_that_leaves_it_keeps_its_canvas_from_a_layer() {+ for animated in [Animated::Translation, Animated::Rotation, Animated::Scale] {+ let (tree, list, element) = page_with_animated_element(animated, UnderAnimatedNode::Canvas);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(+ space_names(&planned.stack),+ ["viewport", &format!("animated@s{} in viewport", element.spatial.0)]+ );+ assert!(planned.placement.media_without_layers.is_empty());+ }+ let (tree, list, _) = page_with_animated_element(Animated::RotationOutOfPlane, UnderAnimatedNode::Canvas);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(space_names(&planned.stack), ["viewport"]);+ assert_eq!(+ planned.placement.media_without_layers,+ [(+ LiveContent::Canvas(CanvasId(1)),+ WhyMediaHasNoLayer::UnderTransformThatIsNot2DAffine+ )]+ );+ }++ #[test]+ fn a_backdrop_filter_moved_by_a_transform_animation_reads_anywhere() {+ let (tree, list, _) = page_with_animated_element(Animated::Translation, UnderAnimatedNode::BackdropFilter);+ let planned = layers_planned_alike_for_every_sample(&list, &tree);+ assert_eq!(space_names(&planned.stack), ["viewport"]);+ assert!(+ planned+ .placement+ .placed_effects+ .iter()+ .any(|placed| placed.backdrop_read_reach == Reach::Anywhere)+ );+ }++ #[test]+ fn a_plane_whose_animation_turns_it_out_of_its_sorting_context_is_sorted_by_depth_at_every_sample() {+ use crate::host::FfiVisualAnimationTransformOperationKind as Kind;+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let plane_of = |tree: &mut VisualContextTree, parent: SpatialNodeIndex, root: Option<SpatialNodeIndex>| {+ tree.append_spatial(+ SpatialData::Transform(TransformData {+ matrix: FloatMatrix4x4::identity(),+ origin: FloatPoint { x: 70.0, y: 70.0 },+ sorting_context_root_index: root,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: root.is_none(),+ bounds: ELEMENT.to_float(),+ }),+ parent,+ )+ };+ let root = plane_of(&mut tree, viewport.spatial, None);+ let still_plane = plane_of(&mut tree, root, Some(root));+ let turning_plane = plane_of(&mut tree, root, Some(root));+ tree.set_visual_animations(vec![played_once_after_a_delay(transform_animation_of(+ turning_plane,+ Kind::RotateY,+ 0.0,+ 180.0,+ ))]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 200, 200), GREEN), viewport)+ .with(+ fill(ELEMENT, GREEN),+ ContextRef {+ spatial: still_plane,+ ..viewport+ },+ )+ .with(+ fill(ELEMENT, GREEN),+ ContextRef {+ spatial: turning_plane,+ ..viewport+ },+ );+ // Replay sorts the planes by depth where they leave the plane of their context in the frame.+ assert!(!tree.with_visual_animation_samples(0).sorts_planes_by_depth());+ assert!(tree.with_visual_animation_samples(700_000_000).sorts_planes_by_depth());+ let storage = DisplayListStorage::of_builder(&list.builder);+ for time_ns in SAMPLE_TIMES_NS {+ let sample = tree.with_visual_animation_samples(time_ns);+ assert!(sample.may_sort_planes_by_depth());+ assert_eq!(+ sample.roots_of_contexts_sorting_planes_by_depth()[turning_plane.0 as usize],+ Some(root)+ );+ let run_groups = storage.run_groups(&sample);+ assert!(!run_groups.run_is_sorted_by_depth(0));+ assert!(run_groups.run_is_sorted_by_depth(1) && run_groups.run_is_sorted_by_depth(2));+ }+ let stack = layers_planned_alike_for_every_sample(&list, &tree).stack;+ assert!(stack.layering_obstacles.sorts_planes_by_depth);+ assert!(stack.why_list_is_one_layer.is_none());+ }++ #[test]+ fn a_rotation_out_of_the_plane_stays_in_it_only_where_it_keeps_its_angle() {+ use crate::display_list::animated_transform_spaces::transform_animation_stays_in_plane;+ use crate::host::FfiVisualAnimationTransformOperationKind as Kind;+ let node = SpatialNodeIndex(1);+ assert!(transform_animation_stays_in_plane(&transform_animation_of(+ node,+ Kind::Rotate,+ 0.0,+ 360.0+ )));+ assert!(transform_animation_stays_in_plane(&transform_animation_of(+ node,+ Kind::RotateX,+ 0.0,+ 0.0+ )));+ // Each keyframe is in the plane within the precision of a rotation matrix, but the angle changes.+ assert!(!transform_animation_stays_in_plane(&transform_animation_of(+ node,+ Kind::RotateX,+ 0.0,+ 1e-8+ )));+ assert!(!transform_animation_stays_in_plane(&transform_animation_of(+ node,+ Kind::RotateY,+ 0.0,+ 180.0+ )));+ }++ #[test]+ fn a_plan_holds_wherever_a_sticky_box_that_anchors_a_space_is_held() {+ use crate::visual_context::StickyData;+ let (mut tree, _, document) = tree_with_document_scroll();+ let mut sticky_data = StickyData::unconstrained(+ document.spatial,+ None,+ crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,+ NodeSlotId::INVALID,+ );+ sticky_data.position_relative_to_scroller = FloatPoint { x: 0.0, y: 100.0 };+ sticky_data.border_box_size = libgfx_rust::FloatSize {+ width: 800.0,+ height: 50.0,+ };+ sticky_data.scrollport_size = libgfx_rust::FloatSize {+ width: 800.0,+ height: 600.0,+ };+ sticky_data.containing_block_region = FloatRect::new(0.0, 0.0, 800.0, 2000.0);+ sticky_data.needs_parent_offset_adjustment = true;+ sticky_data.inset_top = Some(0.0);+ let (_, highest_offset) = sticky_data.offset_range_without_sticky_ancestors();+ let sticky_node = tree.append_spatial(SpatialData::Sticky(sticky_data), document.spatial);+ let sticky = ContextRef {+ spatial: sticky_node,+ ..document+ };+ // The box comes over what the document paints after it only once the document is scrolled.+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(0, 100, 800, 50), GREEN), sticky)+ .with(canvas(IntRect::new(10, 110, 30, 30), 1), sticky)+ .with(fill(IntRect::new(0, 900, 800, 100), GREEN), document);+ let stack_with_box_held_at = |offset: FloatPoint| {+ let mut offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];+ offsets[sticky_node.0 as usize] = offset;+ list.stack(&tree, &offsets)+ };++ let stack = stack_with_box_held_at(FloatPoint::default());+ assert!(+ stack+ .spaces+ .iter()+ .any(|space| matches!(space.anchor_kind, RasterSpaceAnchorKind::StickyBox { .. }))+ );+ assert!(highest_offset.y > 800.0);+ // The compositor holds the box at offsets of its own as it scrolls the document.+ for y in [800.0, highest_offset.y] {+ assert_eq!(stack_with_box_held_at(FloatPoint { x: 0.0, y }), stack);+ }++ // WebContent does not plan again as it publishes where the box is held.+ let storage = DisplayListStorage::of_builder(&list.builder);+ let tree = Arc::new(tree);+ let inputs_with_box_held_at = |y: f32| {+ let mut offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];+ offsets[sticky_node.0 as usize].y = y;+ InputsOfLayerPlan::new(storage.clone(), tree.clone(), &offsets, VIEWPORT)+ };+ assert!(inputs_with_box_held_at(0.0).plan_alike_as(&inputs_with_box_held_at(800.0)));+ }++ fn scroller_with_record(+ tree: &mut VisualContextTree,+ records: &mut Vec<CompositorScrollNodeRecord>,+ parent: ContextRef,+ scrollport: IntRect,+ max_scroll_offset_y: f32,+ ) -> ContextRef {+ let clipped_to_scrollport = clipped_context(tree, parent, scrollport, libgfx_rust::CornerRadii::default());+ let scroller = scroll_node(tree, parent.spatial);+ records.push(scroll_record(+ scroller,+ parent.spatial,+ scrollport,+ max_scroll_offset_y,+ false,+ ));+ ContextRef {+ spatial: scroller,+ ..clipped_to_scrollport+ }+ }++ #[test]+ fn a_backdrop_filter_that_the_compositor_scrolls_within_a_space_is_not_placed_under_its_composite_clips() {+ let (mut tree, _, document) = tree_with_document_scroll();+ let mut records = tree.compositor_scroll_table().nodes.to_vec();+ let outer_scroller =+ scroller_with_record(&mut tree, &mut records, document, IntRect::new(0, 0, 400, 400), 10.0);+ for index in 0..5 {+ scroller_with_record(+ &mut tree,+ &mut records,+ document,+ IntRect::new(420, 80 * index, 300, 70),+ 500.0,+ );+ }+ // The inner scroller is past the most scrollers that get spaces, so the compositor scrolls it within the space+ // of the outer scroller.+ let inner_scroller = scroller_with_record(+ &mut tree,+ &mut records,+ outer_scroller,+ IntRect::new(0, 100, 400, 200),+ 500.0,+ );+ assert!(tree.set_compositor_scroll_table(CompositorScrollTable {+ nodes: records.into(),+ ..CompositorScrollTable::default()+ }));+ let glass = frosted_glass(&mut tree, inner_scroller, IntRect::new(50, 150, 100, 100));+ let planned = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(0, 0, 400, 1000), GREEN), outer_scroller)+ .with(fill(IntRect::new(50, 150, 100, 100), GREEN), glass)+ .planned(&tree, &[]);+ let space_of_outer_scroller = planned+ .stack+ .spaces+ .iter()+ .position(|space| space.anchor == outer_scroller.spatial)+ .expect("the outer scroller anchors a space");+ assert!(+ planned+ .stack+ .spaces+ .iter()+ .all(|space| space.anchor != inner_scroller.spatial)+ );+ // Scrolled to the end of its range, the inner scroller moves the glass far past the outer scrollport, which+ // would cut what the glass reads where it is composited in the space of the outer scroller.+ let stretch_of_glass = planned+ .placement+ .record_stretches+ .last()+ .expect("the run of the glass is placed");+ let run_group_of_glass = &planned.placement.run_groups[stretch_of_glass.run_group_index.0];+ assert_ne!(run_group_of_glass.raster_space_index.0, space_of_outer_scroller);+ }++ #[test]+ fn content_painted_after_a_sticky_toolbar_covers_a_spinner_in_it() {+ use crate::visual_context::StickyData;+ let (mut tree, _, document) = tree_with_document_scroll();+ let mut sticky_data = StickyData::unconstrained(+ document.spatial,+ None,+ crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,+ NodeSlotId::INVALID,+ );+ sticky_data.position_relative_to_scroller = FloatPoint { x: 0.0, y: 100.0 };+ sticky_data.border_box_size = libgfx_rust::FloatSize {+ width: 800.0,+ height: 50.0,+ };+ sticky_data.scrollport_size = libgfx_rust::FloatSize {+ width: 800.0,+ height: 600.0,+ };+ sticky_data.containing_block_region = FloatRect::new(0.0, 0.0, 800.0, 2000.0);+ sticky_data.needs_parent_offset_adjustment = true;+ sticky_data.inset_top = Some(0.0);+ let toolbar = ContextRef {+ spatial: tree.append_spatial(SpatialData::Sticky(sticky_data), document.spatial),+ ..document+ };+ let spinner = transformed_context(&mut tree, toolbar, FloatRect::new(650.0, 105.0, 40.0, 40.0));+ tree.set_visual_animations(vec![spinning(spinner.spatial)]);+ // The label and the spinner of the toolbar are in different cells, and the card covers both of them.+ let label = IntRect::new(10, 110, 100, 30);+ let card = IntRect::new(0, 100, 800, 50);+ assert!(TILE_SIZE_IN_DEVICE_PIXELS < 650);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(label, GREEN), toolbar)+ .with(fill(IntRect::new(650, 105, 40, 40), GREEN), spinner)+ .with(fill(card, GREEN), document);+ let planned = list.planned(&tree, &[]);+ assert_eq!(+ space_names(&planned.stack),+ [+ "viewport",+ "document",+ "sticky@s2 in document",+ "animated@s3 in sticky@s2 in document"+ ]+ );+ let storage = DisplayListStorage::of_builder(&list.builder);+ let card_position = storage.span_of_run(3).begin;+ let layers_of_card = planned.layers_of_record(card_position);+ assert_eq!(+ layers_of_card.len(),+ 1,+ "the card goes into one layer in every cell: {layers_of_card:?}"+ );+ let band_of_card = planned+ .stack+ .bands+ .iter()+ .find(|band| band.record_spans.iter().any(|span| span.contains(card_position)))+ .expect("a band holds the card");+ let layers_tile_keying_puts_card_into_by_cell: Vec<LayerIndex> = CellRange::touched_by(card)+ .coords()+ .map(|coord| {+ CutsOfCell::of(band_of_card, coord.cell_rect())+ .layer_of_record(card_position)+ .0+ })+ .collect();+ assert!(+ layers_tile_keying_puts_card_into_by_cell+ .iter()+ .all(|&layer| layer == layers_of_card[0]),+ "tile keying puts the card into the layer the planner marks in every cell: \+ {layers_tile_keying_puts_card_into_by_cell:?}"+ );+ let layer_of_card = &planned.stack.layers[layers_of_card[0].0];+ assert!(matches!(+ layer_of_card.identity,+ LayerIdentity::Painted {+ above_barrier: Some(_),+ ..+ }+ ));+ }++ #[test]+ fn a_slide_farther_than_extents_reach_reaches_the_whole_viewport() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let slider = transformed_context(&mut tree, viewport, FloatRect::new(0.0, 0.0, 50.0, 50.0));+ tree.set_visual_animations(vec![transform_animation_of(+ slider.spatial,+ crate::host::FfiVisualAnimationTransformOperationKind::TranslateX,+ -3.0e9,+ 3.0e9,+ )]);+ let stack = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 50, 50), GREEN), slider)+ .with(fill(IntRect::new(0, 50, 100, 100), GREEN), viewport)+ .stack(&tree, &[]);+ assert_eq!(space_names(&stack), ["viewport", "animated@s1 in viewport"]);+ assert_eq!(+ stack.swept_reach_in_parent_space_by_space_index[1],+ Some(IntRect::new(0, 0, 800, 56))+ );+ }++ #[cfg(debug_assertions)]+ #[test]+ #[should_panic(expected = "the compositor refuses a plan of layers the planner made")]+ fn the_planner_runs_the_checks_of_the_compositor_on_a_plan_of_more_layers() {+ let (tree, _, document) = tree_with_document_scroll();+ let viewport_past_coordinate_limit = IntRect::new(0, 0, 600_000_000, 600);+ let list = ListOfOneChunk::default().with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document);+ plan_layer_stack(&LayerStackInputs {+ list: &DisplayListStorage::of_builder(&list.builder),+ tree: &tree,+ scroll_offsets: &[],+ viewport_rect: viewport_past_coordinate_limit,+ });+ }++ #[test]+ fn a_plan_holds_for_a_tree_that_differs_only_in_what_the_main_thread_keeps_of_its_nodes() {+ let (tree, _, document) = tree_with_document_scroll();+ let list = ListOfOneChunk::default().with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document);+ let storage = DisplayListStorage::of_builder(&list.builder);+ let mut tree_of_other_paintable = tree.clone();+ let SpatialData::Scroll(scroll) = &mut tree_of_other_paintable.spatial_nodes[document.spatial.0 as usize].data+ else {+ unreachable!("the document scrolls");+ };+ scroll.state_slot = 3;+ scroll.owner_paintable = NodeSlotId::new(5, 1);+ let inputs = InputsOfLayerPlan::new(storage.clone(), Arc::new(tree), &[], VIEWPORT);+ assert!(inputs.plan_alike_as(&InputsOfLayerPlan::new(+ storage,+ Arc::new(tree_of_other_paintable),+ &[],+ VIEWPORT+ )));+ }++ #[test]+ fn a_plan_holds_for_inputs_that_differ_only_in_what_it_does_not_read() {+ let (mut tree, _, document) = tree_with_document_scroll();+ let scroller = scroll_node(&mut tree, document.spatial);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(+ fill(IntRect::new(0, 0, 100, 100), GREEN),+ ContextRef {+ spatial: scroller,+ ..document+ },+ );+ let storage = DisplayListStorage::of_builder(&list.builder);+ let tree = Arc::new(tree);+ let offsets = |document_y: f32, scroller_y: f32| {+ let mut offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];+ offsets[document.spatial.0 as usize].y = document_y;+ offsets[scroller.0 as usize].y = scroller_y;+ offsets+ };+ let inputs = InputsOfLayerPlan::new(storage.clone(), tree.clone(), &offsets(0.0, 0.0), VIEWPORT);++ // The compositor scrolls the document, which has a row in its scroll table, and not the scroller.+ assert!(inputs.plan_alike_as(&inputs.with_scroll_offsets_and_viewport_rect(&offsets(700.0, 0.0), VIEWPORT)));+ // Inputs made after these for the same tree take what plans work out of the tree alone from them.+ let inputs_after = InputsOfLayerPlan::new_after(+ Some(&inputs),+ storage.clone(),+ tree.clone(),+ &offsets(700.0, 0.0),+ VIEWPORT,+ );+ assert!(Arc::ptr_eq(&inputs.anchors_of_tree, &inputs_after.anchors_of_tree));+ assert!(inputs.plan_alike_as(&inputs_after));+ assert!(!inputs.plan_alike_as(&inputs.with_scroll_offsets_and_viewport_rect(&offsets(0.0, 30.0), VIEWPORT)));+ assert!(!inputs.plan_alike_as(+ &inputs.with_scroll_offsets_and_viewport_rect(&offsets(0.0, 0.0), IntRect::new(0, 0, 800, 500))+ ));+ // A list is told apart by its chunks, and a tree by its content.+ let list_of_same_chunks = DisplayListStorage::of_builder(&list.builder);+ let tree_of_same_content = Arc::new((*tree).clone());+ assert!(inputs.plan_alike_as(&InputsOfLayerPlan::new(+ list_of_same_chunks,+ tree_of_same_content,+ &[],+ VIEWPORT+ )));+ let mut tree_of_other_content = (*tree).clone();+ scroll_node(&mut tree_of_other_content, document.spatial);+ assert!(!inputs.plan_alike_as(&InputsOfLayerPlan::new(+ storage,+ Arc::new(tree_of_other_content),+ &[],+ VIEWPORT+ )));+ let other_list = ListOfOneChunk::default().with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document);+ assert!(!inputs.plan_alike_as(&InputsOfLayerPlan::new(+ DisplayListStorage::of_builder(&other_list.builder),+ tree.clone(),+ &[],+ VIEWPORT+ )));+ assert_eq!(inputs.plan().stack, list.stack(&tree, &offsets(700.0, 0.0)));+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rsnew file mode 100644index 00000000000..691f53aba3e--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs@@ -0,0 +1,256 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The lines the dump tells of a plan, and the layers the dump names for each record.++use super::{AnimatedNode, PlacedEffect, PlannedLayers, WhyEffectIsComposited, for_each_layer_records_go_into};+use crate::display_list::commands::EffectNodeIndex;+use crate::display_list::layers::{+ CompositedEffect, LayerContent, LayerIndex, VisualContextNodeNamer, WindowServerPresentationOfMedia, media_name,+};+use crate::display_list::reach::Reach;+use crate::display_list::storage::ListPosition;+use libgfx_rust::{CornerRadii, IntRect};+use std::collections::HashMap;++impl PlannedLayers {+ // Each effect the stack composites, with why it is composited and what it reads of what is composited below it, as+ // where it is placed tells.+ pub(super) fn composited_effects_with_why_and_backdrop_read_reach(+ &self,+ ) -> impl Iterator<Item = (&CompositedEffect, WhyEffectIsComposited, Reach<IntRect>)> + '_ {+ let placed_effect_by_effect: HashMap<EffectNodeIndex, &PlacedEffect> = self+ .placement+ .placed_effects+ .iter()+ .map(|placed_effect| (placed_effect.effect, placed_effect))+ .collect();+ self.stack.composited_effects.iter().filter_map(move |composited| {+ let placed_effect = placed_effect_by_effect.get(&composited.effect)?;+ // A placed effect whose layer content decides whether it is composited is composited only for this.+ let why = placed_effect+ .why_composited_regardless_of_layer_content+ .unwrap_or(WhyEffectIsComposited::ItReadsWhatItsOwnLayerDoesNotHold);+ Some((composited, why, placed_effect.backdrop_read_reach))+ })+ }++ /// What the dump says of each effect the compositor composites: the space of its node, what it reads of what is+ /// composited below it, and why it is composited.+ pub fn lines_of_composited_effects<'a>(+ &'a self,+ node_namer: &'a dyn VisualContextNodeNamer,+ ) -> impl Iterator<Item = String> + 'a {+ let stack = &self.stack;+ self.composited_effects_with_why_and_backdrop_read_reach()+ .map(move |(composited, why, backdrop_read_reach)| {+ let parent_node_index = stack.nodes[composited.placement_node_index.0]+ .parent_index+ .expect("a composited node is inside another");+ let backdrop_read_text = match backdrop_read_reach {+ Reach::Nothing => String::new(),+ Reach::Within(rect) => format!(" reads=[{},{} {}x{}]", rect.x, rect.y, rect.width, rect.height),+ Reach::Anywhere => " reads=anywhere".into(),+ };+ format!(+ "composited {} space={}{backdrop_read_text}: {}",+ node_namer.name_of_effect_node(composited.effect),+ stack.name_of_node(parent_node_index, node_namer),+ why+ )+ })+ }++ /// What the dump says of each backdrop filter or blend mode that finds all it reads in the layer it goes into, and+ /// reads it there rather than the compositor compositing it, in paint order.+ pub fn lines_of_effects_reading_only_own_layer<'a>(+ &'a self,+ node_namer: &'a dyn VisualContextNodeNamer,+ ) -> impl Iterator<Item = String> + 'a {+ let composited_effects = &self.stack.composited_effects;+ self.placement+ .backdrop_readers_in_paint_order+ .iter()+ .filter(|reader| {+ composited_effects+ .iter()+ .all(|composited| composited.effect != **reader)+ })+ .map(|effect| {+ format!(+ "{} is not composited: it reads only its own layer",+ node_namer.name_of_effect_node(*effect)+ )+ })+ }++ /// What the dump says of each canvas, video or nested context that was not given a layer, and why.+ pub fn lines_of_media_without_layers(&self) -> impl Iterator<Item = String> + '_ {+ self.placement+ .media_without_layers+ .iter()+ .map(|(content, why_no_layer)| format!("no layer for {}: {why_no_layer}", media_name(*content)))+ }++ /// What the dump says of each node the compositor animates whose content was not given layers of its own, and why.+ pub fn lines_of_animations_without_layers<'a>(+ &'a self,+ node_namer: &'a dyn VisualContextNodeNamer,+ ) -> impl Iterator<Item = String> + 'a {+ self.placement+ .animations_without_layers+ .iter()+ .map(|(animated_node, why_no_layer)| {+ let node_name = match animated_node {+ AnimatedNode::Transform(spatial) => node_namer.name_of_spatial_node(*spatial),+ AnimatedNode::Effect(effect) => node_namer.name_of_effect_node(*effect),+ };+ format!("no layer for animated {node_name}: {why_no_layer}")+ })+ }++ /// The lines of the Layers section of the dump, each with the layer it is about, if it is about one. There is one+ /// line per layer, bottom to top: its index, what it holds, the space it is rastered in, what it sits above, the+ /// records `describe_records` names for it, what it is clipped to as it is composited, and for a canvas or video+ /// whether the window server shows it, as `presentation` tells. A layer below the base layer, or one that can hold+ /// nothing, is left out. Then a line for each effect the compositor composites, each canvas, video or nested context+ /// without a layer, each animation without a layer, and each effect that reads only its own layer.+ pub fn layer_lines(+ &self,+ presentation: &WindowServerPresentationOfMedia,+ node_namer: &dyn VisualContextNodeNamer,+ describe_records: impl Fn(LayerIndex) -> Option<String>,+ ) -> Vec<(Option<LayerIndex>, String)> {+ let stack = &self.stack;+ let records_suffix_of = |layer_index: LayerIndex| {+ describe_records(layer_index).map_or_else(String::new, |records| format!(" records={records}"))+ };+ if let Some(why_list_is_one_layer) = stack.why_list_is_one_layer {+ let only_layer = LayerIndex(0);+ return vec![(+ Some(only_layer),+ format!(+ "{}{}: {why_list_is_one_layer}",+ stack.name_of_layer(only_layer, node_namer),+ records_suffix_of(only_layer)+ ),+ )];+ }+ let mut lines = Vec::new();+ for (index, layer) in stack.layers.iter().enumerate() {+ let layer_index = LayerIndex(index);+ if layer_index < stack.base_layer || (layer_index != stack.base_layer && !layer.may_hold_content) {+ continue;+ }+ let node = &stack.nodes[layer.placement_node_index.0];+ let mut line = format!(+ "{}{}",+ stack.name_of_layer(layer_index, node_namer),+ records_suffix_of(layer_index)+ );+ for clip in &node.composite_clips {+ let clip_rect = clip.rect;+ line.push_str(&format!(+ " composited within [{},{} {}x{}]{} of {}",+ clip_rect.x,+ clip_rect.y,+ clip_rect.width,+ clip_rect.height,+ text_of_corner_radii_if_any(clip.corner_radii),+ stack.name_of_space(clip.raster_space_index, node_namer)+ ));+ }+ if matches!(layer.content, LayerContent::Media { .. }) {+ match presentation.placements.of_layer(layer_index) {+ Some(Ok(placement)) if presentation.layer_is_shown_by_window_server(layer_index) => {+ line.push_str(&format!(" shown by the window server: {placement}"));+ }+ Some(Ok(_)) if stack.layer_is_inside_composited_effects(layer_index) => {+ line.push_str(" replayed: inside an effect the compositor composites");+ }+ Some(Ok(_)) => line.push_str(" replayed: under a layer the frame holds"),+ Some(Err(why_window_server_cannot_show)) => {+ line.push_str(&format!(" replayed: {why_window_server_cannot_show}"));+ }+ None => {}+ }+ }+ lines.push((Some(layer_index), line));+ }+ lines.extend(+ self.lines_of_composited_effects(node_namer)+ .chain(self.lines_of_media_without_layers())+ .chain(self.lines_of_animations_without_layers(node_namer))+ .chain(self.lines_of_effects_reading_only_own_layer(node_namer))+ .map(|line| (None, line)),+ );+ lines+ }++ /// The layers that the record at `position` can be drawn into, in the tiles it reaches.+ pub fn layers_of_record(&self, position: ListPosition) -> Vec<LayerIndex> {+ let stack = &self.stack;+ if stack.replays_whole_list() {+ return vec![LayerIndex(0)];+ }+ for (index, layer) in stack.layers.iter().enumerate() {+ let LayerContent::Media { record_span, .. } = &layer.content else {+ continue;+ };+ if record_span.contains(position) {+ return vec![LayerIndex(index)];+ }+ }+ let Some(stretch) = self+ .placement+ .record_stretches+ .iter()+ .find(|stretch| stretch.record_span.contains(position))+ else {+ return Vec::new();+ };+ let Some(band_index) = stack+ .bands+ .iter()+ .position(|band| band.record_spans.iter().any(|span| span.contains(position)))+ else {+ return Vec::new();+ };+ let band = &stack.bands[band_index];+ let mut layers = Vec::new();+ for_each_layer_records_go_into(+ &band.cuts,+ band.layer_below_all_cuts,+ stretch.record_span.begin,+ stretch.reach,+ |layer, _| layers.push(layer),+ );+ layers.sort_unstable();+ layers.dedup();+ layers+ }+}++fn text_of_corner_radii_if_any(radii: CornerRadii) -> String {+ if !radii.has_any_radius() {+ return String::new();+ }+ let corners = [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left];+ let every_corner_is_circular = corners+ .iter()+ .all(|corner| corner.horizontal_radius == corner.vertical_radius);+ let corner_texts: Vec<String> = corners+ .iter()+ .map(|corner| {+ if every_corner_is_circular {+ corner.horizontal_radius.to_string()+ } else {+ format!("{}x{}", corner.horizontal_radius, corner.vertical_radius)+ }+ })+ .collect();+ format!(" radii=({})", corner_texts.join(","))+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning/placement_tables.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/placement_tables.rsnew file mode 100644index 00000000000..fae7ff5a73f--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/placement_tables.rs@@ -0,0 +1,563 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What placing a list reads of the raster spaces at a set of anchors: the clips that rasters of each visual context+//! leave to apply when they are composited, the effects that keep content out of a space, and the runs whose records+//! reach outside their visual context.++use super::raster_spaces_for_placing::{+ RasterSpaceGeometryForPlacing, RasterSpacesForPlacing, rect_swept_over_translations,+};+use crate::display_list::animated_transform_spaces::spatial_nodes_under_transform_animations;+use crate::display_list::chunks::ReachOutsideRunContext;+use crate::display_list::commands::{ClipMode, ContextRef, DisplayListCommandRun, EffectNodeIndex, SpatialNodeIndex};+use crate::display_list::effect_geometry::backdrop_filter_read_reach;+use crate::display_list::placement::{+ CompositeClip, EXTENT_LIMIT_IN_DEVICE_PIXELS, RasterSpace, RasterSpaceAnchorKind, RasterSpaceIndex,+ space_and_ancestors_below_viewport, space_is_ancestor_or_self, translation_if_only_translates,+};+use crate::display_list::reach::Reach;+use crate::display_list::storage::{ChunkIndexInList, DisplayListStorage};+use crate::visual_context::{ClipNodeData, EffectNodeData, VisualContextTree};+use libgfx_rust::IntRect;+use std::cell::RefCell;+use std::collections::HashMap;+use std::rc::Rc;++const COMPOSITE_CLIP_EDGE_TOLERANCE_IN_DEVICE_PIXELS: f32 = 1.0 / 64.0;++impl CompositeClip {+ /// Whether the clip leaves all of `rect` unclipped: it lies within the clip's rect and outside its corner boxes.+ fn leaves_all_of(&self, rect: IntRect) -> bool {+ if !self.rect.contains_rect(rect) {+ return false;+ }+ let radii = self.corner_radii;+ let (left, top, right, bottom) = (self.rect.x, self.rect.y, self.rect.right(), self.rect.bottom());+ [+ IntRect::new(+ left,+ top,+ radii.top_left.horizontal_radius,+ radii.top_left.vertical_radius,+ ),+ IntRect::new(+ right - radii.top_right.horizontal_radius,+ top,+ radii.top_right.horizontal_radius,+ radii.top_right.vertical_radius,+ ),+ IntRect::new(+ right - radii.bottom_right.horizontal_radius,+ bottom - radii.bottom_right.vertical_radius,+ radii.bottom_right.horizontal_radius,+ radii.bottom_right.vertical_radius,+ ),+ IntRect::new(+ left,+ bottom - radii.bottom_left.vertical_radius,+ radii.bottom_left.horizontal_radius,+ radii.bottom_left.vertical_radius,+ ),+ ]+ .iter()+ .all(|corner_box| corner_box.is_empty() || corner_box.intersected(rect).is_empty())+ }+}++pub(super) fn lowest_common_ancestor_space(+ spaces: &[RasterSpace],+ first: RasterSpaceIndex,+ second: RasterSpaceIndex,+) -> RasterSpaceIndex {+ let mut candidate = first;+ while !space_is_ancestor_or_self(spaces, candidate, second) {+ candidate = spaces[candidate.0].parent_index;+ }+ candidate+}++type CompositeClipsOfContextInSpace = Option<Rc<[CompositeClip]>>;++/// Where content is placed among the spaces at a set of anchors: the spaces, the clips that can be left to apply when+/// rasters are composited, and the effects whose content reads its backdrop. Where each context is placed is worked out+/// as it is first asked for.+pub(super) struct PlacementTables {+ spaces: RasterSpacesForPlacing,+ /// Per spatial node, whether a sample of the compositor's animations can move it within the deepest space it is+ /// in, as it is under a node whose transform the compositor animates that anchors no space. Empty where the tree+ /// has no transform animations.+ spatial_node_moves_with_animation_samples: Vec<bool>,+ composite_form_of_clips: Vec<Option<CompositeClip>>,+ placement_constraint_of_effects: Vec<EffectPlacementConstraint>,+ deepest_space_and_backdrop_filter_read_rect_by_effect: Vec<Option<(RasterSpaceIndex, IntRect)>>,+ animated_space_holding_every_run_of_effect: Vec<Option<RasterSpaceIndex>>,+ refused_animated_spaces: RefCell<Vec<bool>>,+ cached_composite_clips_of_contexts:+ RefCell<HashMap<(ContextRef, RasterSpaceIndex), CompositeClipsOfContextInSpace>>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum EffectPlacementConstraint {+ ConstrainsNothing,+ MustMoveWithSpace,+ MustMoveWithSpaceAndKeepBackdropReadUncut,+}++impl PlacementTables {+ pub fn new(+ tree: &VisualContextTree,+ spaces: RasterSpacesForPlacing,+ geometries: &[RasterSpaceGeometryForPlacing],+ ) -> Self {+ let spaces_len = spaces.spaces().len();+ let spatial_node_moves_with_animation_samples = spatial_nodes_under_transform_animations(tree, |node| {+ spaces.spaces().iter().skip(1).all(|space| space.anchor != node)+ });+ let composite_form_of_clips = tree+ .clip_nodes+ .iter()+ .map(|node| {+ let ClipNodeData::Rect(data) = &node.data else {+ return None;+ };+ if data.mode != ClipMode::Intersect || spaces.spatial_moves_on_its_own(node.spatial) {+ return None;+ }+ let clip_space = spaces.deepest_space_of(node.spatial);+ let world = &geometries[clip_space.0].raster.world;+ translation_if_only_translates(&world.draw_matrix(node.spatial))?;+ let rect = world.map_rect_to_root(node.spatial, data.rect);+ // A clip of one axis alone clips as much at the extent limit as at its far edges on the other axis.+ let [left, top, right, bottom] = [rect.x, rect.y, rect.right(), rect.bottom()]+ .map(|edge| edge.clamp(-EXTENT_LIMIT_IN_DEVICE_PIXELS, EXTENT_LIMIT_IN_DEVICE_PIXELS));+ let edges_are_on_whole_device_pixels = [left, top, right, bottom]+ .iter()+ .all(|edge| (edge - edge.round()).abs() <= COMPOSITE_CLIP_EDGE_TOLERANCE_IN_DEVICE_PIXELS);+ if !edges_are_on_whole_device_pixels {+ return None;+ }+ Some(CompositeClip {+ raster_space_index: clip_space,+ rect: IntRect::new(+ left.round() as i32,+ top.round() as i32,+ right.round() as i32 - left.round() as i32,+ bottom.round() as i32 - top.round() as i32,+ ),+ corner_radii: data.corner_radii,+ })+ })+ .collect();+ let placement_constraint_of_effects = tree+ .effect_nodes+ .iter()+ .enumerate()+ .map(|(index, node)| {+ if tree.root_isolation_effect == Some(EffectNodeIndex(index as u32))+ || matches!(node.data, EffectNodeData::BackgroundColorAnimation)+ {+ return EffectPlacementConstraint::ConstrainsNothing;+ }+ let reads_backdrop = match &node.data {+ EffectNodeData::Effects(effects) => effects.backdrop_filter.is_some(),+ EffectNodeData::Mask(mask) => mask.masks_backdrop,+ _ => false,+ };+ if reads_backdrop {+ EffectPlacementConstraint::MustMoveWithSpaceAndKeepBackdropReadUncut+ } else {+ EffectPlacementConstraint::MustMoveWithSpace+ }+ })+ .collect();+ let deepest_space_and_backdrop_filter_read_rect_by_effect = tree+ .effect_nodes+ .iter()+ .enumerate()+ .map(|(index, node)| {+ if spaces.spatial_moves_on_its_own(node.spatial) {+ return None;+ }+ let space = spaces.deepest_space_of(node.spatial);+ match backdrop_filter_read_reach(tree, &geometries[space.0].raster, EffectNodeIndex(index as u32)) {+ Reach::Within(read_rect) => Some((space, read_rect)),+ _ => None,+ }+ })+ .collect();+ Self {+ spaces,+ spatial_node_moves_with_animation_samples,+ composite_form_of_clips,+ placement_constraint_of_effects,+ deepest_space_and_backdrop_filter_read_rect_by_effect,+ animated_space_holding_every_run_of_effect: Vec::new(),+ refused_animated_spaces: RefCell::new(vec![false; spaces_len]),+ cached_composite_clips_of_contexts: RefCell::new(HashMap::new()),+ }+ }++ /// Notes, per effect node, the space whose anchor the compositor animates that holds every run of the list under+ /// the effect, if one does: content of that space can be placed in it under such an effect although the effect+ /// does not move with the space, as the compositor composites the effect around the space's rasters.+ pub fn note_animated_spaces_holding_every_run_of_effects(+ &mut self,+ tree: &VisualContextTree,+ list: &DisplayListStorage,+ ) {+ #[derive(Clone, Copy, PartialEq)]+ enum SpacesOfRuns {+ NoRun,+ All(RasterSpaceIndex),+ Several,+ }+ let mut spaces_of_runs_by_effect = vec![SpacesOfRuns::NoRun; tree.effect_nodes.len()];+ for run_index in 0..list.run_count() {+ let context = list.run(run_index).context;+ let space_of_run = self.deepest_space_of(context.spatial);+ let mut effect = context.effect;+ while !effect.is_none() {+ let spaces_of_runs = &mut spaces_of_runs_by_effect[effect.0 as usize];+ *spaces_of_runs = match *spaces_of_runs {+ SpacesOfRuns::NoRun => SpacesOfRuns::All(space_of_run),+ SpacesOfRuns::All(space) if space == space_of_run => SpacesOfRuns::All(space),+ _ => SpacesOfRuns::Several,+ };+ effect = tree.effect_nodes[effect.0 as usize].parent;+ }+ }+ let spaces = self.spaces.spaces();+ self.animated_space_holding_every_run_of_effect = spaces_of_runs_by_effect+ .into_iter()+ .map(|spaces_of_runs| match spaces_of_runs {+ SpacesOfRuns::All(space)+ if matches!(+ spaces[space.0].anchor_kind,+ RasterSpaceAnchorKind::AnimatedTransform { .. }+ ) =>+ {+ Some(space)+ }+ _ => None,+ })+ .collect();+ }++ pub fn animated_space_holding_every_run_of_effect(&self, effect: EffectNodeIndex) -> Option<RasterSpaceIndex> {+ self.animated_space_holding_every_run_of_effect+ .get(effect.0 as usize)+ .copied()+ .flatten()+ }++ /// Keeps content out of a space whose anchor the compositor animates, which then goes into the space around it.+ /// Called before anything is placed in the space.+ pub fn refuse_animated_space(&self, space: RasterSpaceIndex) {+ self.refused_animated_spaces.borrow_mut()[space.0] = true;+ }++ pub fn spaces(&self) -> &[RasterSpace] {+ self.spaces.spaces()+ }++ pub fn deepest_space_of(&self, spatial: SpatialNodeIndex) -> RasterSpaceIndex {+ self.spaces.deepest_space_of(spatial)+ }++ pub fn moves_with(&self, spatial: SpatialNodeIndex, space: RasterSpaceIndex) -> bool {+ self.spaces.moves_with(spatial, space)+ }++ /// The clips that rasters of `context` in `space` leave to be applied as they are composited, in the order its+ /// clip chain names them, or none where the context cannot be rastered in the space: it does not move with the+ /// space, an effect of it does not, or a clip that does not cannot be applied as a rect of whole device pixels.+ pub fn composite_clips_in(+ &self,+ tree: &VisualContextTree,+ context: ContextRef,+ space: RasterSpaceIndex,+ ) -> Option<Rc<[CompositeClip]>> {+ if let Some(cached) = self.cached_composite_clips_of_contexts.borrow().get(&(context, space)) {+ return cached.clone();+ }+ let clips = self.compute_composite_clips_in(tree, context, space).map(Rc::from);+ self.cached_composite_clips_of_contexts+ .borrow_mut()+ .insert((context, space), clips.clone());+ clips+ }++ fn compute_composite_clips_in(+ &self,+ tree: &VisualContextTree,+ context: ContextRef,+ space: RasterSpaceIndex,+ ) -> Option<Vec<CompositeClip>> {+ if !self.moves_with(context.spatial, space) || self.refused_animated_spaces.borrow()[space.0] {+ return None;+ }+ let mut composite_clips = Vec::new();+ let mut clip = context.clip;+ while !clip.is_none() {+ let node = &tree.clip_nodes[clip.0 as usize];+ let composite_form = self.composite_form_of_clips[clip.0 as usize];+ clip = node.parent;+ if self.moves_with(node.spatial, space) {+ continue;+ }+ let composite_clip = composite_form?;+ if composite_clips.contains(&composite_clip) {+ continue;+ }+ let rounded_clip_shares_space_with_another = composite_clips.iter().any(|other: &CompositeClip| {+ other.raster_space_index == composite_clip.raster_space_index+ && (other.is_rounded() || composite_clip.is_rounded())+ });+ if rounded_clip_shares_space_with_another {+ return None;+ }+ composite_clips.push(composite_clip);+ }+ let mut effect = context.effect;+ while !effect.is_none() {+ let node = &tree.effect_nodes[effect.0 as usize];+ match self.placement_constraint_of_effects[effect.0 as usize] {+ EffectPlacementConstraint::ConstrainsNothing => {}+ constraint => {+ let composited_around_animated_space = constraint == EffectPlacementConstraint::MustMoveWithSpace+ && self.animated_space_holding_every_run_of_effect(effect) == Some(space);+ if !self.moves_with(node.spatial, space) && !composited_around_animated_space {+ return None;+ }+ if constraint == EffectPlacementConstraint::MustMoveWithSpaceAndKeepBackdropReadUncut+ && !self.composite_clips_cut_nothing_backdrop_filter_reads(effect, space, &composite_clips)+ {+ return None;+ }+ }+ }+ effect = node.parent;+ }+ Some(composite_clips)+ }++ fn composite_clips_cut_nothing_backdrop_filter_reads(+ &self,+ effect: EffectNodeIndex,+ space: RasterSpaceIndex,+ composite_clips: &[CompositeClip],+ ) -> bool {+ if composite_clips.is_empty() {+ return true;+ }+ let Some((space_of_read_rect, read_rect)) =+ self.deepest_space_and_backdrop_filter_read_rect_by_effect[effect.0 as usize]+ else {+ return false;+ };+ if space_of_read_rect != space {+ return false;+ }+ let spaces = self.spaces.spaces();+ composite_clips.iter().all(|clip| {+ let mut read_rect_swept_over_anchor_translations = read_rect;+ let mut space_swept_through = space;+ while space_swept_through != clip.raster_space_index {+ if space_swept_through == RasterSpaceIndex::VIEWPORT {+ return false;+ }+ read_rect_swept_over_anchor_translations = rect_swept_over_translations(+ read_rect_swept_over_anchor_translations,+ spaces[space_swept_through.0].lowest_anchor_translation,+ spaces[space_swept_through.0].highest_anchor_translation,+ );+ space_swept_through = spaces[space_swept_through.0].parent_index;+ }+ clip.leaves_all_of(read_rect_swept_over_anchor_translations)+ })+ }++ /// Whether a sample of the compositor's animations can change how rasters of `space`, which `spatial` moves with,+ /// draw what is drawn in `spatial`, as a transform the compositor animates is between them.+ pub fn animation_samples_move_spatial_within_space(+ &self,+ spatial: SpatialNodeIndex,+ space: RasterSpaceIndex,+ ) -> bool {+ if self+ .spatial_node_moves_with_animation_samples+ .get(spatial.0 as usize)+ .copied()+ .unwrap_or(false)+ {+ return true;+ }+ let spaces = self.spaces.spaces();+ let mut space_of_spatial = self.deepest_space_of(spatial);+ while space_of_spatial != space && space_of_spatial != RasterSpaceIndex::VIEWPORT {+ if matches!(+ spaces[space_of_spatial.0].anchor_kind,+ RasterSpaceAnchorKind::AnimatedTransform { .. }+ ) {+ return true;+ }+ space_of_spatial = spaces[space_of_spatial.0].parent_index;+ }+ false+ }++ /// Whether what is drawn in `spatial` moves within rasters of `space`: it is in a space inside it, or moves on its+ /// own.+ pub fn spatial_moves_within_space(&self, spatial: SpatialNodeIndex, space: RasterSpaceIndex) -> bool {+ let deepest = self.deepest_space_of(spatial);+ (deepest != space && space_is_ancestor_or_self(self.spaces.spaces(), space, deepest))+ || self.spaces.spatial_moves_on_its_own(spatial)+ }++ /// Whether content of `context` rastered in `space` moves within it as an anchor of a space inside it scrolls, a+ /// sticky box sticks or the compositor animates a transform or a filter, so that where it lands holds at the+ /// current values only.+ pub fn context_moves_within_space(+ &self,+ tree: &VisualContextTree,+ context: ContextRef,+ space: RasterSpaceIndex,+ ) -> bool {+ let moves_within_space = |spatial: SpatialNodeIndex| self.spatial_moves_within_space(spatial, space);+ if self.spaces.effect_spread_moves_on_its_own(context.effect) {+ return true;+ }+ if moves_within_space(context.spatial) {+ return true;+ }+ let mut clip = context.clip;+ while !clip.is_none() {+ let node = &tree.clip_nodes[clip.0 as usize];+ if moves_within_space(node.spatial) {+ return true;+ }+ clip = node.parent;+ }+ let mut effect = context.effect;+ while !effect.is_none() {+ let node = &tree.effect_nodes[effect.0 as usize];+ if tree.root_isolation_effect != Some(effect) && moves_within_space(node.spatial) {+ return true;+ }+ effect = node.parent;+ }+ false+ }+}++/// The records of runs that a space whose anchor what they draw does not move with cannot raster: records with inline+/// clips in spaces of their own, and scroll bars, alone in their runs, whose thumbs follow a scroll offset, as the+/// chunks they are in know.+pub(super) struct RunsReachingOutsideTheirContext {+ inline_clip_spaces_of_runs: HashMap<usize, Vec<SpatialNodeIndex>>,+ scroll_nodes_moving_scroll_bar_thumbs_of_runs: HashMap<usize, Vec<SpatialNodeIndex>>,+}++impl RunsReachingOutsideTheirContext {+ pub fn new(list: &DisplayListStorage) -> Self {+ let mut inline_clip_spaces_of_runs: HashMap<usize, Vec<SpatialNodeIndex>> = HashMap::new();+ let mut scroll_nodes_moving_scroll_bar_thumbs_of_runs: HashMap<usize, Vec<SpatialNodeIndex>> = HashMap::new();+ for (chunk_index, chunk) in list.chunks().iter().enumerate() {+ let first_run_index_of_chunk = list.first_run_of_chunk(ChunkIndexInList(chunk_index as u32));+ for record in chunk.records_reaching_outside_run_context() {+ let run_index = first_run_index_of_chunk + record.run_index as usize;+ match record.reach_outside_run_context {+ ReachOutsideRunContext::InlineClipInSpaceOf(space) => {+ inline_clip_spaces_of_runs.entry(run_index).or_default().push(space);+ }+ ReachOutsideRunContext::ScrollbarThumbFollowsScrollOffsetOf(scroll_node_index) => {+ scroll_nodes_moving_scroll_bar_thumbs_of_runs+ .entry(run_index)+ .or_default()+ .push(scroll_node_index);+ }+ }+ }+ }+ Self {+ inline_clip_spaces_of_runs,+ scroll_nodes_moving_scroll_bar_thumbs_of_runs,+ }+ }++ /// The clips rasters of the run in `space` leave to be composited, or none where the run cannot be rastered there.+ pub fn composite_clips_of_run_in(+ &self,+ tree: &VisualContextTree,+ tables: &PlacementTables,+ run_index: usize,+ run: &DisplayListCommandRun,+ space: RasterSpaceIndex,+ ) -> Option<Rc<[CompositeClip]>> {+ let composite_clips = tables.composite_clips_in(tree, run.context, space)?;+ let has_inline_clip_not_moving_with_space =+ self.inline_clip_spaces_of_runs+ .get(&run_index)+ .is_some_and(|clip_spaces| {+ clip_spaces.iter().any(|&clip_space| {+ (clip_space.0 as usize) < tree.spatial_nodes.len() && !tables.moves_with(clip_space, space)+ })+ });+ if has_inline_clip_not_moving_with_space {+ return None;+ }+ let has_scroll_bar_thumb_following_anchor_of_space = self+ .scroll_nodes_moving_scroll_bar_thumbs_of_runs+ .get(&run_index)+ .is_some_and(|scroll_nodes| {+ space_and_ancestors_below_viewport(tables.spaces(), space)+ .any(|space_or_ancestor| scroll_nodes.contains(&tables.spaces()[space_or_ancestor.0].anchor))+ });+ if has_scroll_bar_thumb_following_anchor_of_space {+ return None;+ }+ Some(composite_clips)+ }++ /// Whether an inline clip of the run in a space of its own moves within rasters of `space`, which then read where+ /// the clip is.+ pub fn inline_clips_of_run_move_within_space(+ &self,+ tree: &VisualContextTree,+ tables: &PlacementTables,+ run_index: usize,+ space: RasterSpaceIndex,+ ) -> bool {+ self.inline_clip_spaces_of_runs+ .get(&run_index)+ .is_some_and(|clip_spaces| {+ clip_spaces.iter().any(|&clip_space| {+ (clip_space.0 as usize) < tree.spatial_nodes.len()+ && tables.spatial_moves_within_space(clip_space, space)+ })+ })+ }++ /// The deepest space the run can be rastered in.+ pub fn deepest_space_of_run(+ &self,+ tree: &VisualContextTree,+ tables: &PlacementTables,+ run_index: usize,+ run: &DisplayListCommandRun,+ ) -> RasterSpaceIndex {+ let mut space = tables.deepest_space_of(run.context.spatial);+ while space != RasterSpaceIndex::VIEWPORT+ && self+ .composite_clips_of_run_in(tree, tables, run_index, run, space)+ .is_none()+ {+ space = tables.spaces()[space.0].parent_index;+ }+ space+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning/raster_spaces_for_placing.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/raster_spaces_for_placing.rsnew file mode 100644index 00000000000..abf55ea9cd7--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/raster_spaces_for_placing.rs@@ -0,0 +1,337 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The raster spaces that a plan places a list among, and the geometry of each, with what placing reads past what+//! rastering reads: the spatial nodes that move on their own relative to the spaces, the effects whose filters can+//! spread their content farther on their own, the bounds of the clip chains fixed in a space, and the extent of each+//! space.++use crate::display_list::commands::{ContextRef, EffectNodeIndex, SpatialNodeIndex};+use crate::display_list::effect_geometry::filter_may_spread_at_some_sample;+use crate::display_list::layers::anchors_of_layer_plans;+use crate::display_list::placement::{+ FiltersAndClipsOfList, RasterSpace, RasterSpaceAnchorKind, RasterSpaceGeometry, RasterSpaceIndex, RasterSpaces,+ WhatEverySpaceOfTreeShares, antialiased_reach_in_device_pixels, chain_bounds_of_clip, compositor_scroll_record_of,+ enclosing_int_rect_within_extent_limit, extent_limit_rect, intersect_bounds, is_finite_rect, raster_scroll_offsets,+ space_is_ancestor_or_self, spatial_nodes_that_move_on_their_own_relative_to_spaces_at,+ spatial_nodes_whose_scroll_offset_placement_leaves_out_of_nodes_moving, translation_if_only_translates,+};+use crate::display_list::reach::Reach;+use crate::host::FfiVisualAnimationTargetKind;+use crate::visual_context::{VisualContextTree, WorldTransforms};+use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect};+use std::rc::Rc;+use std::sync::Arc;++const ANCHOR_TRANSLATION_ROUNDING_OVERSHOOT_IN_DEVICE_PIXELS: i32 = 1;++/// The rect that content within `rect` covers wherever a translation between `lowest` and `highest` takes it, with the+/// rounding of that translation to whole device pixels.+pub(super) fn rect_swept_over_translations(rect: IntRect, lowest: FloatPoint, highest: FloatPoint) -> IntRect {+ if rect.is_empty() {+ return rect;+ }+ let swept = FloatRect::new(+ rect.x as f32 + lowest.x,+ rect.y as f32 + lowest.y,+ rect.width as f32 + highest.x - lowest.x,+ rect.height as f32 + highest.y - lowest.y,+ );+ if !is_finite_rect(swept) {+ return enclosing_int_rect_within_extent_limit(extent_limit_rect());+ }+ let margin = ANCHOR_TRANSLATION_ROUNDING_OVERSHOOT_IN_DEVICE_PIXELS;+ enclosing_int_rect_within_extent_limit(swept).inflated_edges(margin, margin, margin, margin)+}++/// Per effect node, whether how far its filters spread its content can change while the list and the tree's structure+/// stay, as the compositor animates the filter of it or of an effect above it, and the filter spreads at some sample.+fn effects_whose_spread_moves_on_its_own(tree: &VisualContextTree) -> Vec<bool> {+ let mut spread_moves = vec![false; tree.effect_nodes.len()];+ if !tree+ .visual_animations()+ .iter()+ .any(|animation| animation.target_kind == FfiVisualAnimationTargetKind::Filter)+ {+ return spread_moves;+ }+ tree.visit_effect_nodes_parents_first(|index| {+ let node = &tree.effect_nodes[index];+ let effect = EffectNodeIndex(index as u32);+ let spread_of_parent_moves = !node.parent.is_none() && spread_moves[node.parent.0 as usize];+ spread_moves[index] = spread_of_parent_moves+ || (tree.effect_filter_is_animated(effect) && filter_may_spread_at_some_sample(tree, effect));+ });+ spread_moves+}++fn extent_of_space(+ tree: &VisualContextTree,+ spaces: &[RasterSpace],+ space: RasterSpaceIndex,+ world_with_anchors_of_space_at_origin: &WorldTransforms,+ viewport_rect: IntRect,+) -> IntRect {+ let world = world_with_anchors_of_space_at_origin;+ let unbounded = enclosing_int_rect_within_extent_limit(extent_limit_rect());+ let space = &spaces[space.0];+ if let RasterSpaceAnchorKind::AnimatedTransform { .. } = space.anchor_kind {+ return unbounded;+ }+ if let RasterSpaceAnchorKind::StickyBox { .. } = space.anchor_kind {+ let extent_of_parent = if space.parent_index == RasterSpaceIndex::VIEWPORT {+ viewport_rect+ } else {+ extent_of_space(tree, spaces, space.parent_index, world, viewport_rect)+ };+ let negated = |point: FloatPoint| FloatPoint {+ x: -point.x,+ y: -point.y,+ };+ let extent_of_parent_translated_back_by_every_box_offset = rect_swept_over_translations(+ extent_of_parent,+ negated(space.highest_anchor_translation),+ negated(space.lowest_anchor_translation),+ );+ return extent_of_parent_translated_back_by_every_box_offset;+ }+ let Some(record) = compositor_scroll_record_of(tree, space.anchor) else {+ return unbounded;+ };+ let Some(scrollport_offset) =+ translation_if_only_translates(&world.draw_matrix(tree.spatial_nodes[space.anchor.0 as usize].parent))+ else {+ return unbounded;+ };+ let scrollport = record+ .scrollport_rect+ .to_float()+ .translated(scrollport_offset.x, scrollport_offset.y);+ let (minimum, maximum) = (record.min_scroll_offset, record.max_scroll_offset);+ let extent = FloatRect::new(+ scrollport.x + minimum.x.min(0.0),+ scrollport.y + minimum.y.min(0.0),+ scrollport.width + (maximum.x.max(0.0) - minimum.x.min(0.0)),+ scrollport.height + (maximum.y.max(0.0) - minimum.y.min(0.0)),+ );+ if !is_finite_rect(extent) {+ return unbounded;+ }+ enclosing_int_rect_within_extent_limit(extent)+}++/// What plans of layers work out of a tree alone, once for every plan under the tree: the anchors of the raster spaces+/// it offers, and per spatial node, whether the node moves on its own relative to those spaces, and whether a plan+/// leaves out the scroll offset of the node.+#[derive(Debug)]+pub(super) struct RasterSpaceAnchorsOfTree {+ pub(super) anchors: Vec<SpatialNodeIndex>,+ spatial_node_moves_on_its_own: Arc<[bool]>,+ pub(super) leaves_out_scroll_offset_of_node: Vec<bool>,+}++impl RasterSpaceAnchorsOfTree {+ pub(super) fn of(tree: &VisualContextTree) -> Self {+ let anchors = anchors_of_layer_plans(tree);+ let spatial_node_moves_on_its_own =+ spatial_nodes_that_move_on_their_own_relative_to_spaces_at(tree, Some(&anchors));+ Self {+ leaves_out_scroll_offset_of_node: spatial_nodes_whose_scroll_offset_placement_leaves_out_of_nodes_moving(+ tree,+ &anchors,+ spatial_node_moves_on_its_own.clone(),+ ),+ anchors,+ spatial_node_moves_on_its_own: spatial_node_moves_on_its_own.into(),+ }+ }+}++/// The raster spaces of a tree at a set of anchors, with what placing a list among them reads past what rastering+/// reads: per spatial node, whether it moves on its own relative to the spaces, and per effect node, whether how far+/// its filters spread its content moves on its own.+#[derive(Debug)]+pub(super) struct RasterSpacesForPlacing {+ raster_spaces: RasterSpaces,+ spatial_node_moves_on_its_own: Arc<[bool]>,+ effect_node_spread_moves_on_its_own: Vec<bool>,+}++impl RasterSpacesForPlacing {+ /// The spaces at the anchors of `tree`, without the extent of each but the viewport's, which placing reads of the+ /// geometry of each space.+ fn at_anchors(+ tree: &VisualContextTree,+ anchors_of_tree: &RasterSpaceAnchorsOfTree,+ viewport_rect: IntRect,+ ) -> Self {+ let raster_spaces = RasterSpaces::of_spaces(+ tree,+ RasterSpaces::spaces_at_anchors(tree, &anchors_of_tree.anchors, viewport_rect),+ );+ debug_assert!(+ raster_spaces+ .spaces()+ .iter()+ .skip(1)+ .map(|space| space.anchor)+ .eq(anchors_of_tree.anchors.iter().copied()),+ "every anchor of a tree has a space"+ );+ Self {+ spatial_node_moves_on_its_own: anchors_of_tree.spatial_node_moves_on_its_own.clone(),+ effect_node_spread_moves_on_its_own: effects_whose_spread_moves_on_its_own(tree),+ raster_spaces,+ }+ }++ pub(super) fn spaces(&self) -> &[RasterSpace] {+ self.raster_spaces.spaces()+ }++ pub(super) fn deepest_space_of(&self, spatial: SpatialNodeIndex) -> RasterSpaceIndex {+ self.raster_spaces.deepest_space_of(spatial)+ }++ pub(super) fn moves_with(&self, spatial: SpatialNodeIndex, space: RasterSpaceIndex) -> bool {+ space_is_ancestor_or_self(self.spaces(), space, self.deepest_space_of(spatial))+ }++ pub(super) fn spatial_moves_on_its_own(&self, spatial: SpatialNodeIndex) -> bool {+ self.spatial_node_moves_on_its_own+ .get(spatial.0 as usize)+ .copied()+ .unwrap_or(false)+ }++ pub(super) fn effect_spread_moves_on_its_own(&self, effect: EffectNodeIndex) -> bool {+ !effect.is_none()+ && self+ .effect_node_spread_moves_on_its_own+ .get(effect.0 as usize)+ .copied()+ .unwrap_or(false)+ }+}++/// The geometry of one raster space, with what placing a list in it reads past what rastering reads: the bounds of+/// the clip chains fixed in the space, and the extent of the space.+pub(super) struct RasterSpaceGeometryForPlacing {+ pub(super) raster: RasterSpaceGeometry,+ clip_chain_bounds_fixed_in_space_by_clip: Vec<Option<FloatRect>>,+ pub(super) extent: IntRect,+}++impl RasterSpaceGeometryForPlacing {+ fn new(+ tree: &VisualContextTree,+ spaces: &RasterSpacesForPlacing,+ space: RasterSpaceIndex,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+ what_every_space_of_tree_shares: &Rc<WhatEverySpaceOfTreeShares>,+ world_of_viewport_space: Option<&Rc<WorldTransforms>>,+ ) -> Self {+ let raster = match world_of_viewport_space {+ Some(world) if spaces.spaces()[space.0].raster_root().is_none() => RasterSpaceGeometry::with_world(+ tree,+ &spaces.raster_spaces,+ space,+ raster_scroll_offsets(spaces.spaces(), space, scroll_offsets),+ world.clone(),+ what_every_space_of_tree_shares,+ ),+ _ => RasterSpaceGeometry::new(+ tree,+ &spaces.raster_spaces,+ space,+ scroll_offsets,+ FloatMatrix4x4::identity(),+ what_every_space_of_tree_shares,+ ),+ };+ let mut clip_chain_bounds_fixed_in_space_by_clip: Vec<Option<FloatRect>> = vec![None; tree.clip_nodes.len()];+ tree.visit_clip_nodes_parents_first(|index| {+ let node = &tree.clip_nodes[index];+ let own_bounds_if_fixed_in_space = raster.rastered_affine_own_clip_bounds_by_clip[index].filter(|_| {+ spaces.deepest_space_of(node.spatial) == space && !spaces.spatial_moves_on_its_own(node.spatial)+ });+ clip_chain_bounds_fixed_in_space_by_clip[index] = intersect_bounds(+ own_bounds_if_fixed_in_space,+ chain_bounds_of_clip(node.parent, &clip_chain_bounds_fixed_in_space_by_clip),+ );+ });+ let extent = if space == RasterSpaceIndex::VIEWPORT {+ viewport_rect+ } else {+ extent_of_space(tree, spaces.spaces(), space, &raster.world, viewport_rect)+ };+ Self {+ raster,+ clip_chain_bounds_fixed_in_space_by_clip,+ extent,+ }+ }++ /// As `RasterSpaceGeometry::reach_of_content`, or without `drawn_within`, where content of `context` can show+ /// anywhere it can move: within the clips fixed in the space, which are some of those that rasters of the space+ /// apply.+ pub(super) fn reach_of_content(+ &self,+ list: &FiltersAndClipsOfList<'_>,+ drawn_within: Option<FloatRect>,+ context: ContextRef,+ ) -> Reach<IntRect> {+ match drawn_within {+ Some(drawn_within) => self.raster.reach_of_content(list, drawn_within, context),+ None => antialiased_reach_in_device_pixels(chain_bounds_of_clip(+ list.clip_bounding_filter_spread(context),+ &self.clip_chain_bounds_fixed_in_space_by_clip,+ )),+ }+ }++ pub(super) fn part_of_extent_reached_by(&self, reach: Reach<IntRect>) -> IntRect {+ reach.part_of(self.extent)+ }+}++/// The spaces at the anchors of `tree` and the geometry of each, in the device pixels of the viewport.+pub(super) fn spaces_with_geometries(+ tree: &VisualContextTree,+ anchors_of_tree: &RasterSpaceAnchorsOfTree,+ scroll_offsets: &[FloatPoint],+ viewport_rect: IntRect,+) -> (RasterSpacesForPlacing, Vec<RasterSpaceGeometryForPlacing>) {+ let spaces = RasterSpacesForPlacing::at_anchors(tree, anchors_of_tree, viewport_rect);+ let what_every_space_of_tree_shares = WhatEverySpaceOfTreeShares::of(tree);+ let geometry_of_viewport_space = RasterSpaceGeometryForPlacing::new(+ tree,+ &spaces,+ RasterSpaceIndex::VIEWPORT,+ scroll_offsets,+ viewport_rect,+ &what_every_space_of_tree_shares,+ None,+ );+ // The scroll offsets a plan reads leave out that of every anchor, so every space whose anchor the compositor does+ // not animate has the world transforms of the viewport's space.+ let world_of_viewport_space = geometry_of_viewport_space.raster.world.clone();+ let geometries: Vec<RasterSpaceGeometryForPlacing> = std::iter::once(geometry_of_viewport_space)+ .chain((1..spaces.spaces().len()).map(|space| {+ RasterSpaceGeometryForPlacing::new(+ tree,+ &spaces,+ RasterSpaceIndex(space),+ scroll_offsets,+ viewport_rect,+ &what_every_space_of_tree_shares,+ Some(&world_of_viewport_space),+ )+ }))+ .collect();+ (spaces, geometries)+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rsnew file mode 100644index 00000000000..ecad0f36f71--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs@@ -0,0 +1,2410 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A plan of the layers of a list as it goes from WebContent to the compositor: what of its stack the compositor cannot+//! work out of the list and the tree, and the checks that a plan from another process passes before anything reads it.++use super::{+ BandOfPlan, BarrierOfPlan, COORDINATE_LIMIT_IN_DEVICE_PIXELS, CutOfPlan, LayerContent, LayerIdentity, LayerStack,+ LayeredPlan, LayeringObstacles, MAXIMUM_MEDIA_LAYER_COUNT, MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS, NodeOfPlan,+ PlacementNodeIndex, StackLayer, WhyCompositorCannotCompositeEffect, WhyListIsOneLayer, anchors_of_layer_plans,+};+use crate::display_list::commands::{+ CanvasId, CompositorContextId, EffectNodeIndex, ImageFrameResourceId, VideoSinkHandle,+};+use crate::display_list::placement::{+ CompositeClip, MAXIMUM_RASTER_SPACE_COUNT, RasterSpace, RasterSpaceAnchorKind, RasterSpaceIndex, RasterSpaces,+};+use crate::display_list::reach::Reach;+use crate::display_list::storage::{ChunkIndexInList, DisplayListStorage, ListPosition, ListSpan};+use crate::display_list::summary::{LiveContent, live_content_of};+use crate::display_list::tape::DisplayListCommandRun;+use crate::visual_context::VisualContextTree;+use crate::visual_context::queries::NestingOfLiveEffects;+use libgfx_rust::IntRect;+use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};+use std::collections::HashSet;++// Caps on a received stack, which bound what decoding allocates. The values per space, and the composite clips of a node,+// which are one per space, are capped at the most spaces a plan makes. A plan holds nodes, bands, cuts and spans as many+// as the runs of a list ask for, and the planner gives a list one layer where they are more than these caps. Keying a+// cell looks through every cut of its band and keeps those that cut it, so the cuts of a band are capped lower: the+// pages of the tests cut a band at most 90 times.+const MAXIMUM_NODE_COUNT_OF_RECEIVED_STACK: usize = 1 << 16;+const MAXIMUM_BAND_COUNT_OF_RECEIVED_STACK: usize = 1 << 16;+const MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND: usize = 256;+const MAXIMUM_SPAN_COUNT_OF_RECEIVED_BAND: usize = 1 << 20;++/// A stack decoded from another process: why it is one layer that replays the whole list, or the plan of a stack of+/// more layers. Nothing reads it until `validated_stack` checks it and works out the stack.+#[derive(Debug)]+enum StackOnWire {+ OneLayer(WhyListIsOneLayer),+ Layered(LayeredPlan),+}++/// A plan of the layers of a list as WebContent sends it to the compositor: the stack, the display list it was planned+/// for, and the viewport, in device pixels, it was planned within.+#[derive(Clone, Debug, PartialEq)]+pub struct LayerPlan {+ pub display_list_id: u64,+ pub viewport_rect: IntRect,+ pub stack: LayerStack,+}++/// A plan of layers decoded from another process, whose stack nothing reads until it is checked.+#[derive(Debug)]+pub struct UnvalidatedLayerPlan {+ pub display_list_id: u64,+ pub viewport_rect: IntRect,+ stack: StackOnWire,+}++impl UnvalidatedLayerPlan {+ /// The plan, once its stack passes `validated_stack` for `list` under `tree` within the viewport the plan+ /// names. The receiver makes sure that `list` is the list that `display_list_id` names.+ pub fn validated(self, list: &DisplayListStorage, tree: &VisualContextTree) -> Result<LayerPlan, &'static str> {+ Ok(LayerPlan {+ display_list_id: self.display_list_id,+ viewport_rect: self.viewport_rect,+ stack: validated_stack(self.stack, list, tree, self.viewport_rect)?,+ })+ }+}++macro_rules! impl_codec_of_index_going_as_u32 {+ ($($type:ident),*) => {+ $(+ impl Encode for $type {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&u32::try_from(self.0).map_err(|_| EncodeError::SizeTooLarge(self.0))?)+ }+ }++ impl Decode for $type {+ const MIN_ENCODED_SIZE: usize = size_of::<u32>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self(decoder.decode::<u32>()? as usize))+ }+ }+ )*+ };+}++impl_codec_of_index_going_as_u32!(RasterSpaceIndex, PlacementNodeIndex);++impl Encode for ListPosition {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.chunk_index.0)?;+ encoder.encode(&self.offset)+ }+}++impl Decode for ListPosition {+ const MIN_ENCODED_SIZE: usize = 2 * size_of::<u32>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self::new(ChunkIndexInList(decoder.decode()?), decoder.decode()?))+ }+}++impl Encode for ListSpan {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.begin)?;+ encoder.encode(&self.end)+ }+}++impl Decode for ListSpan {+ const MIN_ENCODED_SIZE: usize = 2 * ListPosition::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ begin: decoder.decode()?,+ end: decoder.decode()?,+ })+ }+}++const REACH_KIND_NOTHING: u8 = 0;+const REACH_KIND_WITHIN: u8 = 1;+const REACH_KIND_ANYWHERE: u8 = 2;++impl Encode for Reach<IntRect> {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ match self {+ Reach::Nothing => encoder.encode(&REACH_KIND_NOTHING),+ Reach::Within(rect) => {+ encoder.encode(&REACH_KIND_WITHIN)?;+ encoder.encode(rect)+ }+ Reach::Anywhere => encoder.encode(&REACH_KIND_ANYWHERE),+ }+ }+}++impl Decode for Reach<IntRect> {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(match decoder.decode::<u8>()? {+ REACH_KIND_NOTHING => Reach::Nothing,+ REACH_KIND_WITHIN => Reach::Within(decoder.decode()?),+ REACH_KIND_ANYWHERE => Reach::Anywhere,+ _ => return Err(DecodeError::InvalidValue("Reach")),+ })+ }+}++const LIVE_CONTENT_KIND_CANVAS: u8 = 0;+const LIVE_CONTENT_KIND_VIDEO_FRAME: u8 = 1;+const LIVE_CONTENT_KIND_IMAGE_FRAME: u8 = 2;+const LIVE_CONTENT_KIND_COMPOSITED_CONTEXT: u8 = 3;++impl Encode for LiveContent {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ let (kind, id) = match self {+ LiveContent::Canvas(id) => (LIVE_CONTENT_KIND_CANVAS, id.0),+ LiveContent::VideoFrame(id) => (LIVE_CONTENT_KIND_VIDEO_FRAME, id.0),+ LiveContent::ImageFrame(id) => (LIVE_CONTENT_KIND_IMAGE_FRAME, id.0),+ LiveContent::CompositedContext(id) => (LIVE_CONTENT_KIND_COMPOSITED_CONTEXT, id.0),+ };+ encoder.encode(&kind)?;+ encoder.encode(&id)+ }+}++impl Decode for LiveContent {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>() + size_of::<u64>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let kind = decoder.decode::<u8>()?;+ let id = decoder.decode::<u64>()?;+ Ok(match kind {+ LIVE_CONTENT_KIND_CANVAS => LiveContent::Canvas(CanvasId(id)),+ LIVE_CONTENT_KIND_VIDEO_FRAME => LiveContent::VideoFrame(VideoSinkHandle(id)),+ LIVE_CONTENT_KIND_IMAGE_FRAME => LiveContent::ImageFrame(ImageFrameResourceId(id)),+ LIVE_CONTENT_KIND_COMPOSITED_CONTEXT => LiveContent::CompositedContext(CompositorContextId(id)),+ _ => return Err(DecodeError::InvalidValue("LiveContent")),+ })+ }+}++impl Encode for CompositeClip {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.raster_space_index)?;+ encoder.encode(&self.rect)?;+ encoder.encode(&self.corner_radii)+ }+}++impl Decode for CompositeClip {+ const MIN_ENCODED_SIZE: usize =+ RasterSpaceIndex::MIN_ENCODED_SIZE + IntRect::MIN_ENCODED_SIZE + libgfx_rust::CornerRadii::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ raster_space_index: decoder.decode()?,+ rect: decoder.decode()?,+ corner_radii: decoder.decode()?,+ })+ }+}++impl Decode for NodeOfPlan {+ const MIN_ENCODED_SIZE: usize = RasterSpaceIndex::MIN_ENCODED_SIZE+ + Vec::<CompositeClip>::MIN_ENCODED_SIZE+ + Option::<EffectNodeIndex>::MIN_ENCODED_SIZE+ + Option::<PlacementNodeIndex>::MIN_ENCODED_SIZE+ + Reach::<IntRect>::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ raster_space_index: decoder.decode()?,+ composite_clips: decoder.decode_with_max_size(MAXIMUM_RASTER_SPACE_COUNT)?,+ composited_effect: decoder.decode()?,+ parent_index: decoder.decode()?,+ reach_in_parent_node: decoder.decode()?,+ })+ }+}++const BARRIER_KIND_MEDIA: u8 = 0;+const BARRIER_KIND_NESTED_BAND: u8 = 1;++impl Decode for CutOfPlan {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>() + IntRect::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let barrier = match decoder.decode::<u8>()? {+ BARRIER_KIND_MEDIA => BarrierOfPlan::Media {+ content: decoder.decode()?,+ ordinal: decoder.decode()?,+ record_span: decoder.decode()?,+ reach: decoder.decode()?,+ },+ BARRIER_KIND_NESTED_BAND => BarrierOfPlan::NestedBand,+ _ => return Err(DecodeError::InvalidValue("BarrierOfPlan")),+ };+ Ok(Self {+ barrier,+ reach_of_layer_above_cut: decoder.decode()?,+ })+ }+}++impl Decode for BandOfPlan {+ const MIN_ENCODED_SIZE: usize = PlacementNodeIndex::MIN_ENCODED_SIZE+ + Vec::<ListSpan>::MIN_ENCODED_SIZE+ + IntRect::MIN_ENCODED_SIZE+ + Vec::<CutOfPlan>::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ placement_node_index: decoder.decode()?,+ record_spans: decoder.decode_with_max_size(MAXIMUM_SPAN_COUNT_OF_RECEIVED_BAND)?,+ reach_of_layer_below_all_cuts: decoder.decode()?,+ cuts: decoder.decode_with_max_size(MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND)?,+ })+ }+}++impl Encode for WhyCompositorCannotCompositeEffect {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ let kind: u8 = match self {+ WhyCompositorCannotCompositeEffect::FilterMovesWhatItFilters => 0,+ WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed => 1,+ };+ encoder.encode(&kind)+ }+}++impl Decode for WhyCompositorCannotCompositeEffect {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(match decoder.decode::<u8>()? {+ 0 => WhyCompositorCannotCompositeEffect::FilterMovesWhatItFilters,+ 1 => WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed,+ _ => return Err(DecodeError::InvalidValue("WhyCompositorCannotCompositeEffect")),+ })+ }+}++impl Encode for WhyListIsOneLayer {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ let kind: u8 = match self {+ WhyListIsOneLayer::EmptyViewport => 0,+ WhyListIsOneLayer::EmptyDisplayList => 1,+ WhyListIsOneLayer::SortingContext3D => 2,+ WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup => 3,+ WhyListIsOneLayer::MaskDeclaredUnderEffectsItsMaskIsNotUnder => 4,+ WhyListIsOneLayer::RecordsBlendWithWhatOtherLayersHoldBelowThem => 5,+ WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(_) => 6,+ WhyListIsOneLayer::FrameIsNotDrawnAsPlanned => 7,+ WhyListIsOneLayer::CompositedEffectsNestTooDeep => 8,+ WhyListIsOneLayer::PlanShowsTooManyTiles => 9,+ WhyListIsOneLayer::PlanFailsChecksOfCompositor => 10,+ WhyListIsOneLayer::PlanHoldsMoreThanCompositorDecodes => 11,+ };+ encoder.encode(&kind)?;+ if let WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(why) = self {+ encoder.encode(why)?;+ }+ Ok(())+ }+}++impl Decode for WhyListIsOneLayer {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(match decoder.decode::<u8>()? {+ 0 => WhyListIsOneLayer::EmptyViewport,+ 1 => WhyListIsOneLayer::EmptyDisplayList,+ 2 => WhyListIsOneLayer::SortingContext3D,+ 3 => WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup,+ 4 => WhyListIsOneLayer::MaskDeclaredUnderEffectsItsMaskIsNotUnder,+ 5 => WhyListIsOneLayer::RecordsBlendWithWhatOtherLayersHoldBelowThem,+ 6 => WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(decoder.decode()?),+ 7 => WhyListIsOneLayer::FrameIsNotDrawnAsPlanned,+ 8 => WhyListIsOneLayer::CompositedEffectsNestTooDeep,+ 9 => WhyListIsOneLayer::PlanShowsTooManyTiles,+ 10 => WhyListIsOneLayer::PlanFailsChecksOfCompositor,+ 11 => WhyListIsOneLayer::PlanHoldsMoreThanCompositorDecodes,+ _ => return Err(DecodeError::InvalidValue("WhyListIsOneLayer")),+ })+ }+}++const PLAN_KIND_ONE_LAYER: u8 = 0;+const PLAN_KIND_LAYERED: u8 = 1;++impl Decode for StackOnWire {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>() + WhyListIsOneLayer::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(match decoder.decode::<u8>()? {+ PLAN_KIND_ONE_LAYER => StackOnWire::OneLayer(decoder.decode()?),+ PLAN_KIND_LAYERED => StackOnWire::Layered(LayeredPlan {+ nodes: decoder.decode_with_max_size(MAXIMUM_NODE_COUNT_OF_RECEIVED_STACK)?,+ bands: decoder.decode_with_max_size(MAXIMUM_BAND_COUNT_OF_RECEIVED_STACK)?,+ tiles_hold_content_moving_within_space_by_space_index: decoder+ .decode_with_max_size(MAXIMUM_RASTER_SPACE_COUNT)?,+ swept_reach_in_parent_space_by_space_index: decoder.decode_with_max_size(MAXIMUM_RASTER_SPACE_COUNT)?,+ }),+ _ => return Err(DecodeError::InvalidValue("StackOnWire")),+ })+ }+}++// A stack of one layer that replays the whole list goes as why it is one layer. A stack of more layers goes as its+// plan: its nodes without their identities, and its bands in the order of the walk that its layers are in, each with+// what only it knows of its layers. In that order, the layer of a canvas, video or nested context comes right below the+// layer above its cut, and the last layer of a nested band comes right below the layer above the cut that enters it.+impl Encode for LayerStack {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ if let Some(why_list_is_one_layer) = self.why_list_is_one_layer {+ encoder.encode(&PLAN_KIND_ONE_LAYER)?;+ return encoder.encode(&why_list_is_one_layer);+ }+ encoder.encode(&PLAN_KIND_LAYERED)?;+ encoder.encode_size(self.nodes.len())?;+ for node in &self.nodes {+ encoder.encode(&node.raster_space_index)?;+ encoder.encode(&node.composite_clips)?;+ encoder.encode(&node.composited_effect)?;+ encoder.encode(&node.parent_index)?;+ encoder.encode(&node.reach_in_parent_node)?;+ }+ encoder.encode_size(self.bands.len())?;+ for band in &self.bands {+ encoder.encode(&band.placement_node_index)?;+ encoder.encode(&band.record_spans)?;+ encoder.encode(&self.layers[band.layer_below_all_cuts.0].reach)?;+ encoder.encode_size(band.cuts.len())?;+ for cut in &band.cuts {+ match &self.layers[cut.layer_above_cut.0 - 1] {+ StackLayer {+ identity: LayerIdentity::Media { content, ordinal },+ content: LayerContent::Media { record_span },+ reach,+ ..+ } => {+ encoder.encode(&BARRIER_KIND_MEDIA)?;+ encoder.encode(content)?;+ encoder.encode(ordinal)?;+ encoder.encode(record_span)?;+ encoder.encode(reach)?;+ }+ _ => encoder.encode(&BARRIER_KIND_NESTED_BAND)?,+ }+ encoder.encode(&self.layers[cut.layer_above_cut.0].reach)?;+ }+ }+ encoder.encode(&self.tiles_hold_content_moving_within_space_by_space_index)?;+ encoder.encode(&self.swept_reach_in_parent_space_by_space_index)+ }+}++impl Encode for LayerPlan {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.display_list_id)?;+ encoder.encode(&self.viewport_rect)?;+ encoder.encode(&self.stack)+ }+}++impl Decode for UnvalidatedLayerPlan {+ const MIN_ENCODED_SIZE: usize = size_of::<u64>() + IntRect::MIN_ENCODED_SIZE + StackOnWire::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ display_list_id: decoder.decode()?,+ viewport_rect: decoder.decode()?,+ stack: decoder.decode()?,+ })+ }+}++fn rect_is_within_coordinate_limit(rect: IntRect) -> bool {+ let limit = i64::from(COORDINATE_LIMIT_IN_DEVICE_PIXELS);+ let (x, y, width, height) = (+ i64::from(rect.x),+ i64::from(rect.y),+ i64::from(rect.width),+ i64::from(rect.height),+ );+ width >= 0 && height >= 0 && x >= -limit && y >= -limit && x + width <= limit && y + height <= limit+}++fn reach_is_within_coordinate_limit(reach: Reach<IntRect>) -> bool {+ match reach {+ Reach::Within(rect) => rect_is_within_coordinate_limit(rect),+ Reach::Nothing | Reach::Anywhere => true,+ }+}++fn run_starting_at(list: &DisplayListStorage, position: ListPosition) -> Option<&DisplayListCommandRun> {+ list.chunks()+ .get(position.chunk_index.0 as usize)?+ .run_starting_at(position.offset)+}++fn position_starts_run(list: &DisplayListStorage, position: ListPosition) -> bool {+ run_starting_at(list, position).is_some()+}++fn position_ends_run(list: &DisplayListStorage, position: ListPosition) -> bool {+ let Some(chunk) = list.chunks().get(position.chunk_index.0 as usize) else {+ return false;+ };+ let runs_ending_at_or_before_position = &chunk.runs()[..chunk.index_of_first_run_ending_after(position.offset)];+ runs_ending_at_or_before_position+ .last()+ .is_some_and(|run| run.offset.checked_add(run.size) == Some(position.offset))+}++fn span_is_of_whole_runs(list: &DisplayListStorage, span: ListSpan) -> bool {+ span.begin <= span.end && position_starts_run(list, span.begin) && position_ends_run(list, span.end)+}++// The span of a canvas, video or nested context with a layer is one run of the list, which starts with a record that+// draws that content.+fn span_is_run_drawing_content(list: &DisplayListStorage, span: ListSpan, content: LiveContent) -> bool {+ if matches!(content, LiveContent::ImageFrame(_)) {+ return false;+ }+ let Some(run) = run_starting_at(list, span.begin) else {+ return false;+ };+ if run.size == 0 || span.end != ListPosition::new(span.begin.chunk_index, run.offset.saturating_add(run.size)) {+ return false;+ }+ let (header, payload) = list.record_at(span.begin);+ live_content_of(header.command_type, payload) == Some(content)+}++/// Whether `plan` holds more nodes or bands, or a band of it more cuts or spans, than the compositor decodes.+pub(super) fn plan_holds_more_than_compositor_decodes(plan: &LayeredPlan) -> bool {+ plan.nodes.len() > MAXIMUM_NODE_COUNT_OF_RECEIVED_STACK+ || plan.bands.len() > MAXIMUM_BAND_COUNT_OF_RECEIVED_STACK+ || plan.bands.iter().any(|band| {+ band.cuts.len() > MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND+ || band.record_spans.len() > MAXIMUM_SPAN_COUNT_OF_RECEIVED_BAND+ })+}++fn check_viewport_rect(viewport_rect: IntRect) -> Result<(), &'static str> {+ if !rect_is_within_coordinate_limit(viewport_rect) {+ return Err("the viewport of the plan lies past the limit a plan keeps to");+ }+ Ok(())+}++fn check_rects_and_coordinates(plan: &LayeredPlan) -> Result<(), &'static str> {+ let within = rect_is_within_coordinate_limit;+ let radius_limit = i64::from(COORDINATE_LIMIT_IN_DEVICE_PIXELS);+ let radius_is_within = |radius: i32| i64::from(radius) >= 0 && i64::from(radius) <= radius_limit;+ let nodes_are_within = plan.nodes.iter().all(|node| {+ reach_is_within_coordinate_limit(node.reach_in_parent_node)+ && node.composite_clips.iter().all(|clip| {+ let radii = clip.corner_radii;+ within(clip.rect)+ && [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left]+ .iter()+ .all(|corner| {+ radius_is_within(corner.horizontal_radius) && radius_is_within(corner.vertical_radius)+ })+ })+ });+ let layers_are_within = plan.bands.iter().all(|band| {+ within(band.reach_of_layer_below_all_cuts)+ && band.cuts.iter().all(|cut| {+ within(cut.reach_of_layer_above_cut)+ && match cut.barrier {+ BarrierOfPlan::Media { reach, .. } => within(reach),+ BarrierOfPlan::NestedBand => true,+ }+ })+ });+ let swept_reaches_are_within = plan+ .swept_reach_in_parent_space_by_space_index+ .iter()+ .flatten()+ .all(|swept_reach| within(*swept_reach));+ if !nodes_are_within || !layers_are_within || !swept_reaches_are_within {+ return Err("a rect or a coordinate of the stack lies past the limit a plan keeps to");+ }+ Ok(())+}++fn check_values_per_space(plan: &LayeredPlan, spaces: &[RasterSpace]) -> Result<(), &'static str> {+ if plan.tiles_hold_content_moving_within_space_by_space_index.len() != spaces.len()+ || plan.swept_reach_in_parent_space_by_space_index.len() != spaces.len()+ {+ return Err("a value the stack holds per space is not there for every space");+ }+ let only_animated_spaces_are_swept =+ spaces+ .iter()+ .zip(&plan.swept_reach_in_parent_space_by_space_index)+ .all(|(space, swept_reach)| {+ swept_reach.is_none() || matches!(space.anchor_kind, RasterSpaceAnchorKind::AnimatedTransform { .. })+ });+ if !only_animated_spaces_are_swept {+ return Err("a space whose anchor the compositor does not animate has a swept reach");+ }+ Ok(())+}++fn check_nodes(+ nodes: &[NodeOfPlan],+ spaces: &[RasterSpace],+ list: &DisplayListStorage,+ tree: &VisualContextTree,+) -> Result<(), &'static str> {+ let mut effects_of_composited_nodes = HashSet::new();+ for (index, node) in nodes.iter().enumerate() {+ if node.raster_space_index.0 >= spaces.len() {+ return Err("a node is in a space the stack does not hold");+ }+ if node.parent_index.is_some_and(|parent_index| parent_index.0 >= index) {+ return Err("a node is not after the node it is in");+ }+ // A node that is not composited is in the node of the space its space is in, and a composited node is in a node+ // of its own space. So nodes nest no deeper than spaces, plus composited effects, which nest as the tree nests+ // them.+ let parent = node.parent_index.map(|parent_index| &nodes[parent_index.0]);+ let is_in_node_a_plan_puts_it_in = match (node.composited_effect, parent) {+ (None, None) => node.raster_space_index == RasterSpaceIndex::VIEWPORT,+ (None, Some(parent)) => {+ node.raster_space_index != RasterSpaceIndex::VIEWPORT+ && parent.composited_effect.is_none()+ && parent.raster_space_index == spaces[node.raster_space_index.0].parent_index+ }+ (Some(_), Some(parent)) => parent.raster_space_index == node.raster_space_index,+ (Some(_), None) => return Err("a composited node is in no other node"),+ };+ if !is_in_node_a_plan_puts_it_in {+ return Err("a node is not in the node of its space or of the space its space is in");+ }+ let clips_are_one_per_space_in_order = node+ .composite_clips+ .iter()+ .all(|clip| clip.raster_space_index.0 < spaces.len())+ && node+ .composite_clips+ .windows(2)+ .all(|pair| pair[0].raster_space_index < pair[1].raster_space_index);+ if !clips_are_one_per_space_in_order {+ return Err("the composite clips of a node are not one per space of the stack, in order");+ }+ let Some(effect) = node.composited_effect else {+ continue;+ };+ let effect_takes_part_in_replay = tree.effect_is_live(effect)+ && list+ .effect_clip_plan(tree)+ .output_clip_if_participating(effect)+ .is_some();+ if !effect_takes_part_in_replay {+ return Err("a node is composited inside an effect that a replay of the list does not enter");+ }+ if !effects_of_composited_nodes.insert(effect) {+ return Err("two nodes are composited inside one effect");+ }+ }+ Ok(())+}++// A frame composites a layer inside each composited effect around it, and the planner gives a list one layer where they+// nest deeper than `MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS`. Each node comes after the node it is in.+fn check_nesting_of_composited_effects(nodes: &[NodeOfPlan]) -> Result<(), &'static str> {+ let mut nesting_by_node_index: Vec<usize> = Vec::with_capacity(nodes.len());+ for node in nodes {+ let nesting_around = node+ .parent_index+ .and_then(|parent_index| nesting_by_node_index.get(parent_index.0).copied())+ .unwrap_or(0);+ let nesting = nesting_around + usize::from(node.composited_effect.is_some());+ if nesting > MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS {+ return Err("composited effects nest deeper than a plan nests them");+ }+ nesting_by_node_index.push(nesting);+ }+ Ok(())+}++// A frame enters the effects of the nodes around a layer outermost first, each from the one around it.+fn check_composited_effects_nest_as_in_tree(+ nodes: &[NodeOfPlan],+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+) -> Result<(), &'static str> {+ if nodes.iter().all(|node| node.composited_effect.is_none()) {+ return Ok(());+ }+ let mut innermost_effect_around_by_node_index: Vec<Option<EffectNodeIndex>> = Vec::with_capacity(nodes.len());+ for node in nodes {+ let innermost_effect_around = node.parent_index.and_then(|parent_index| {+ nodes[parent_index.0]+ .composited_effect+ .or(innermost_effect_around_by_node_index[parent_index.0])+ });+ if let (Some(effect), Some(effect_around)) = (node.composited_effect, innermost_effect_around)+ && !nesting_of_live_effects.is_strictly_inside(effect, effect_around)+ {+ return Err("the composited effects around a node are not nested as the tree nests them");+ }+ innermost_effect_around_by_node_index.push(innermost_effect_around);+ }+ Ok(())+}++// The walk of the bands enters the first band, and at each cut whose barrier is a nested band, the next band. So it+// enters each band once exactly where each band but the first has a cut before it left to enter it from, and no cut is+// left after the last band.+fn check_bands(plan: &LayeredPlan, list: &DisplayListStorage) -> Result<(), &'static str> {+ const NOT_ENTERED_ONCE: &str = "the walk of the bands does not enter each band of the stack once";+ let mut bands_left_to_enter = 1usize;+ let mut media_of_layers: Vec<(ListPosition, LiveContent, u32)> = Vec::new();+ for (index, band) in plan.bands.iter().enumerate() {+ bands_left_to_enter = bands_left_to_enter.checked_sub(1).ok_or(NOT_ENTERED_ONCE)?;+ if band.placement_node_index.0 >= plan.nodes.len() {+ return Err("a band is of a node the stack does not hold");+ }+ // A plan opens each band but the first for a stretch of records that goes into that band or into a band inside+ // it. The first band holds nothing where no record can show.+ if index != 0 && band.record_spans.is_empty() && band.cuts.is_empty() {+ return Err("a band other than the first holds no span and no cut");+ }+ let spans_are_of_whole_runs_in_paint_order =+ band.record_spans.iter().all(|span| span_is_of_whole_runs(list, *span))+ && band.record_spans.windows(2).all(|pair| pair[0].end <= pair[1].begin);+ if !spans_are_of_whole_runs_in_paint_order {+ return Err("the spans of a band are not of whole runs of the list, in paint order");+ }+ for cut in &band.cuts {+ match cut.barrier {+ BarrierOfPlan::Media {+ content,+ ordinal,+ record_span,+ ..+ } => {+ if !span_is_run_drawing_content(list, record_span, content) {+ return Err("a canvas, video or nested context is not a run of the list that draws it");+ }+ if media_of_layers.len() == MAXIMUM_MEDIA_LAYER_COUNT {+ return Err("the stack holds more canvas, video and nested context layers than a plan makes");+ }+ media_of_layers.push((record_span.begin, content, ordinal));+ }+ BarrierOfPlan::NestedBand => bands_left_to_enter += 1,+ }+ }+ }+ if bands_left_to_enter != 0 {+ return Err(NOT_ENTERED_ONCE);+ }+ check_ordinals_of_media(media_of_layers)+}++// A plan numbers the drawings of a canvas, video or nested context that have layers in paint order: each has as its+// ordinal how many of them with the same content are painted before it. The window server tells the media apart by+// their ordinals.+fn check_ordinals_of_media(mut media_of_layers: Vec<(ListPosition, LiveContent, u32)>) -> Result<(), &'static str> {+ media_of_layers.sort_unstable_by_key(|(position, _, _)| *position);+ for (index, (_, content, ordinal)) in media_of_layers.iter().enumerate() {+ let count_of_same_content_painted_before = media_of_layers[..index]+ .iter()+ .filter(|(_, earlier_content, _)| earlier_content == content)+ .count();+ if *ordinal as usize != count_of_same_content_painted_before {+ return Err("a canvas, video or nested context is not numbered by the drawings of it painted before it");+ }+ }+ Ok(())+}++// A plan puts each stretch of records into one band, or for a canvas, video or nested context with a layer, into that+// layer, and a stretch holds at least one run. So no record is in two spans, and a stack holds no more spans than the+// list holds runs.+fn check_no_record_is_held_twice(plan: &LayeredPlan) -> Result<(), &'static str> {+ let spans_of_media_layers = plan+ .bands+ .iter()+ .flat_map(|band| &band.cuts)+ .filter_map(|cut| match cut.barrier {+ BarrierOfPlan::Media { record_span, .. } => Some(record_span),+ BarrierOfPlan::NestedBand => None,+ });+ let mut spans: Vec<ListSpan> = plan+ .bands+ .iter()+ .flat_map(|band| band.record_spans.iter().copied())+ .chain(spans_of_media_layers)+ .collect();+ if spans.iter().any(|span| span.begin >= span.end) {+ return Err("a span of the stack holds no record");+ }+ spans.sort_unstable_by_key(|span| span.begin);+ if spans.windows(2).any(|pair| pair[1].begin < pair[0].end) {+ return Err("two spans of the stack hold the same record");+ }+ Ok(())+}++// What only the walk of the bands tells: the node of a band the walk enters at a cut of another band is in the node of+// that band, and the first band is of a node in no other node; the cuts of a band are in paint order; and the identities+// of layers, so of bands too, are unique.+fn check_stack_of_plan(stack: &LayerStack) -> Result<(), &'static str> {+ for band in &stack.bands {+ let node_of_band_around = band+ .parent_band_holding_this_band_as_barrier+ .map(|band_around| stack.bands[band_around.0].placement_node_index);+ if node_of_band_around != stack.nodes[band.placement_node_index.0].parent_index {+ return Err("a band is not of a node in the node of the band that holds it as a barrier");+ }+ let cuts_are_in_paint_order = band+ .cuts+ .windows(2)+ .all(|pair| pair[0].barrier_first_record_position <= pair[1].barrier_first_record_position);+ if !cuts_are_in_paint_order {+ return Err("the cuts of a band are not in paint order");+ }+ }+ let mut identities_of_layers = HashSet::with_capacity(stack.layers.len());+ if !stack+ .layers+ .iter()+ .all(|layer| identities_of_layers.insert(layer.identity))+ {+ return Err("two layers share an identity");+ }+ Ok(())+}++/// The stack of a plan that another process made for `list` under `tree` within `viewport_rect`, if the plan passes the+/// checks.+///+/// The wire holds only what the plan alone knows. The rest is built here with the functions the planner calls: a stack+/// of one layer is the one `LayerStack::one_layer_replaying_whole_list` makes, and the spaces of a stack of more layers+/// are those `RasterSpaces::spaces_at_anchors` makes at the anchors of the tree, from which+/// `LayerStack::of_layered_plan` builds the rest. The layering obstacles are those of the list and the tree.+///+/// After the checks, every consumer can read the stack without a panic, an index out of range, an overflow, or work+/// without a bound. Each index names an item of the stack, the list or the tree, and each rect lies within twice the+/// extent limit of a plan. The nodes, bands, cuts and spans nest and follow each other as a plan makes them, the spans+/// are of whole runs, and no record is in two spans. So the stack holds no more spans than the list holds runs, no+/// more canvas, video and nested context layers than a plan makes, and its nodes nest no deeper than its spaces plus+/// `MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS`. The layers of a band are next to each other, so a frame that composites+/// the layers in order enters each composited band once. The base layer is never of a space whose anchor the+/// compositor animates, and no two layers share an identity.+///+/// The checks leave out what can only make pixels wrong: whether reaches and composite clips hold what the records+/// draw, which effects must be composited, which layers can hold content, whether every record is in a span, which+/// spaces hold content that moves within them, and where the window server can show media. The list and the tree pass+/// their own checks first.+fn validated_stack(+ stack: StackOnWire,+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ viewport_rect: IntRect,+) -> Result<LayerStack, &'static str> {+ let nesting_of_live_effects = NestingOfLiveEffects::of(tree);+ let layering_obstacles = LayeringObstacles::of_with_nesting_of_live_effects(list, tree, &nesting_of_live_effects);+ match stack {+ StackOnWire::OneLayer(why_list_is_one_layer) => {+ check_viewport_rect(viewport_rect)?;+ Ok(LayerStack::one_layer_replaying_whole_list(+ viewport_rect,+ list.whole_span(),+ Some(why_list_is_one_layer),+ layering_obstacles,+ ))+ }+ StackOnWire::Layered(plan) => LayerStack::of_plan_passing_checks(+ plan,+ RasterSpaces::spaces_at_anchors(tree, &anchors_of_layer_plans(tree), viewport_rect),+ list,+ tree,+ viewport_rect,+ layering_obstacles,+ &nesting_of_live_effects,+ ),+ }+}++impl LayerStack {+ /// The stack of `plan`, a plan of more layers for `list` under `tree` within `viewport_rect` at `spaces`, once the+ /// plan passes the checks of `validated_stack`. The planner runs them on a plan before it goes to the compositor, so the+ /// compositor never refuses a plan the planner makes.+ pub(super) fn of_plan_passing_checks(+ plan: LayeredPlan,+ spaces: Vec<RasterSpace>,+ list: &DisplayListStorage,+ tree: &VisualContextTree,+ viewport_rect: IntRect,+ layering_obstacles: LayeringObstacles,+ nesting_of_live_effects: &NestingOfLiveEffects<'_>,+ ) -> Result<LayerStack, &'static str> {+ check_viewport_rect(viewport_rect)?;+ check_rects_and_coordinates(&plan)?;+ check_values_per_space(&plan, &spaces)?;+ check_nodes(&plan.nodes, &spaces, list, tree)?;+ check_nesting_of_composited_effects(&plan.nodes)?;+ check_composited_effects_nest_as_in_tree(&plan.nodes, nesting_of_live_effects)?;+ check_bands(&plan, list)?;+ check_no_record_is_held_twice(&plan)?;+ let stack = LayerStack::of_layered_plan(plan, spaces, tree, layering_obstacles);+ check_stack_of_plan(&stack)?;+ Ok(stack)+ }+}++/// Whether the compositor takes a plan made within `viewport_rect`, of one layer or more.+pub fn compositor_takes_plans_within(viewport_rect: IntRect) -> bool {+ check_viewport_rect(viewport_rect).is_ok()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::builder::DisplayListBuilder;+ use crate::display_list::commands::{+ ClipNodeIndex, ContextRef, DeclareMaskContent, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,+ };+ use crate::display_list::layers::planning::{LayerStackInputs, PlannedLayers, plan_layer_stack};+ use crate::display_list::layers::{+ BandIndex, CutsOfCell, LARGEST_SUMMED_READ_REACH_OF_COMPOSITED_FILTERS_IN_DEVICE_PIXELS, LayerIndex,+ MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS, NodeNamesFromIndices, PlacementNodeBand,+ WindowServerPresentationOfMedia,+ };+ use crate::display_list::placement::{RasterSpace, RasterSpaceGeometry, WhatEverySpaceOfTreeShares};+ use crate::display_list::test_fixtures::{+ GREEN, ListOfOneChunk, NO_FRAME_STATE, VIEWPORT, canvas, chunk_of, effects, fill, frosted_glass,+ opacity_animation_of, raster_settings_hash_by_layer, scroll_node, scroll_record, spinning, transform,+ tree_with_document_scroller, tree_with_root_isolation_effect,+ };+ use crate::display_list::tile_keys::{TileKeyingOfList, TileKeyingOfRasterSpace};+ use crate::node_slot_id::NodeSlotId;+ use crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT;+ use crate::visual_context::{CompositorScrollTable, EffectNodeData, EffectsData, SpatialData, StickyData};+ use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize};+ use std::sync::Arc;++ struct Page {+ tree: VisualContextTree,+ list: Arc<DisplayListStorage>,+ }++ impl Page {+ fn planned(&self) -> PlannedLayers {+ plan_layer_stack(&LayerStackInputs {+ list: &self.list,+ tree: &self.tree,+ scroll_offsets: &[],+ viewport_rect: VIEWPORT,+ })+ }++ fn validated(&self, stack: LayerStack) -> Result<LayerStack, &'static str> {+ validated_stack(on_wire(&stack), &self.list, &self.tree, VIEWPORT)+ }++ fn planned_plan(&self) -> LayeredPlan {+ let StackOnWire::Layered(plan) = on_wire(&self.planned().stack) else {+ panic!("the page is planned in more than one layer");+ };+ plan+ }++ fn validated_plan(&self, plan: LayeredPlan) -> Result<LayerStack, &'static str> {+ validated_stack(StackOnWire::Layered(plan), &self.list, &self.tree, VIEWPORT)+ }+ }++ // The stack as decoding its wire form gives it.+ fn on_wire(stack: &LayerStack) -> StackOnWire {+ let mut encoder = Encoder::new();+ encoder.encode(stack).expect("a planned stack encodes");+ Decoder::new(&encoder.finish().0, [])+ .decode()+ .expect("a planned stack decodes")+ }++ // A long page of fills in the document, each in a chunk of its own, under a header fixed to the viewport.+ fn plain_page() -> Page {+ let (tree, viewport, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let mut chunks = vec![chunk_of(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)];+ for line in 0..40 {+ chunks.push(chunk_of(+ fill(IntRect::new(10, 60 + line * 60, 700, 20), GREEN),+ document,+ ));+ }+ chunks.push(chunk_of(fill(IntRect::new(0, 0, 800, 50), GREEN), viewport));+ Page {+ tree,+ list: DisplayListStorage::of_chunks(chunks).unwrap(),+ }+ }++ fn page_with_two_canvases() -> Page {+ let (tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(canvas(IntRect::new(100, 100, 200, 100), 1), document)+ .with(fill(IntRect::new(150, 150, 200, 100), GREEN), document)+ .with(canvas(IntRect::new(100, 400, 200, 100), 2), document)+ .with(fill(IntRect::new(150, 450, 200, 100), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_drawing_one_canvas_twice() -> Page {+ let (tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(canvas(IntRect::new(100, 100, 200, 100), 1), document)+ .with(fill(IntRect::new(150, 150, 200, 100), GREEN), document)+ .with(canvas(IntRect::new(100, 400, 200, 100), 1), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_with_canvas_in_nested_scroller() -> Page {+ let (tree, _, contexts) = tree_with_document_scroller(&[IntRect::new(100, 100, 300, 200)]);+ let (document, nested) = (contexts[0], contexts[1]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(100, 100, 300, 700), GREEN), nested)+ .with(canvas(IntRect::new(120, 150, 100, 100), 1), nested)+ .with(fill(IntRect::new(150, 200, 100, 100), GREEN), nested)+ .with(fill(IntRect::new(0, 900, 800, 100), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_with_sticky_header() -> Page {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let mut sticky_data =+ StickyData::unconstrained(document.spatial, None, NO_SCROLL_STATE_SLOT, NodeSlotId::INVALID);+ sticky_data.position_relative_to_scroller = FloatPoint { x: 0.0, y: 100.0 };+ sticky_data.border_box_size = FloatSize {+ width: 800.0,+ height: 50.0,+ };+ sticky_data.scrollport_size = FloatSize {+ width: 800.0,+ height: 600.0,+ };+ sticky_data.containing_block_region = FloatRect::new(0.0, 0.0, 800.0, 2000.0);+ sticky_data.needs_parent_offset_adjustment = true;+ sticky_data.inset_top = Some(0.0);+ let sticky_node = tree.append_spatial(SpatialData::Sticky(sticky_data), document.spatial);+ let sticky = ContextRef {+ spatial: sticky_node,+ ..document+ };+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(0, 100, 800, 50), GREEN), sticky)+ .with(fill(IntRect::new(0, 300, 800, 50), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // An element whose opacity the compositor animates holds another whose opacity it animates.+ fn page_with_nested_composited_effects() -> Page {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let outer = tree.append_effect_node_under(document, effects(1.0, CompositingAndBlendingOperator::Normal));+ let inner = tree.append_effect_node_under(outer, effects(1.0, CompositingAndBlendingOperator::Normal));+ tree.set_visual_animations(vec![+ opacity_animation_of(outer.effect, 1.0, 0.0),+ opacity_animation_of(inner.effect, 1.0, 0.0),+ ]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(100, 100, 300, 300), GREEN), outer)+ .with(fill(IntRect::new(150, 150, 100, 100), GREEN), inner)+ .with(fill(IntRect::new(0, 500, 800, 50), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_with_spinner() -> Page {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner_node = tree.append_spatial(+ SpatialData::Transform(transform(FloatRect::new(50.0, 50.0, 40.0, 40.0))),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ tree.set_visual_animations(vec![spinning(spinner_node)]);+ let spinner = ContextRef {+ spatial: spinner_node,+ ..viewport+ };+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner)+ .with(fill(IntRect::new(0, 100, 100, 100), GREEN), viewport);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // The background is painted below the root group, which a spinner holds all of, so the compositor composites the+ // root isolation effect over the spinner's transform.+ fn page_with_spinner_holding_the_root_group() -> Page {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let spinner_node = tree.append_spatial(+ SpatialData::Transform(transform(FloatRect::new(50.0, 50.0, 40.0, 40.0))),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ tree.set_visual_animations(vec![spinning(spinner_node)]);+ let spinner = ContextRef {+ spatial: spinner_node,+ ..viewport+ };+ let list = ListOfOneChunk::default()+ .with(fill(VIEWPORT, GREEN), ContextRef::default())+ .with(fill(IntRect::new(50, 50, 40, 40), GREEN), spinner);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_under_translucent_root() -> Page {+ let (tree, viewport) = tree_with_root_isolation_effect(0.5);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 600), GREEN), viewport)+ .with(canvas(IntRect::new(100, 100, 200, 100), 1), viewport);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn page_without_records() -> Page {+ let (tree, _) = tree_with_root_isolation_effect(1.0);+ Page {+ tree,+ list: DisplayListStorage::of_chunks(Vec::new()).unwrap(),+ }+ }++ // A record that draws nothing, which no band holds, so that the only band of the stack holds nothing.+ fn page_whose_records_draw_nothing() -> Page {+ let (tree, viewport) = tree_with_root_isolation_effect(1.0);+ let list = ListOfOneChunk::default().with(fill(IntRect::new(10, 10, 0, 0), GREEN), viewport);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // More scrollers in the document than get spaces.+ const NESTED_SCROLLER_COUNT_OF_CROWDED_PAGE: i32 = 80;++ fn page_with_many_nested_scrollers() -> Page {+ let scrollport_rects: Vec<IntRect> = (0..NESTED_SCROLLER_COUNT_OF_CROWDED_PAGE)+ .map(|index| IntRect::new(10, 100 + index * 220, 300, 200))+ .collect();+ let (tree, _, contexts) = tree_with_document_scroller(&scrollport_rects);+ let mut list = ListOfOneChunk::default().with(fill(IntRect::new(0, 0, 800, 20000), GREEN), contexts[0]);+ for (scrollport_rect, context) in scrollport_rects.iter().zip(&contexts[1..]) {+ list = list.with(fill(*scrollport_rect, GREEN), *context);+ }+ Page {+ tree,+ list: list.storage(),+ }+ }++ // One canvas more than get layers, the last after a fill.+ fn page_with_nine_canvases() -> Page {+ let (tree, viewport) = tree_with_root_isolation_effect(1.0);+ let mut list = ListOfOneChunk::default().with(fill(VIEWPORT, GREEN), viewport);+ for index in 0..9 {+ list = list+ .with(fill(IntRect::new(10 + index * 80, 10, 60, 60), GREEN), viewport)+ .with(+ canvas(IntRect::new(10 + index * 80, 100, 60, 60), index as u64 + 1),+ viewport,+ );+ }+ Page {+ tree,+ list: list.storage(),+ }+ }++ // Two elements side by side whose opacity the compositor animates.+ fn page_with_two_fading_siblings() -> Page {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let left = tree.append_effect_node_under(document, effects(1.0, CompositingAndBlendingOperator::Normal));+ let right = tree.append_effect_node_under(document, effects(1.0, CompositingAndBlendingOperator::Normal));+ tree.set_visual_animations(vec![+ opacity_animation_of(left.effect, 1.0, 0.0),+ opacity_animation_of(right.effect, 1.0, 0.0),+ ]);+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(100, 100, 200, 200), GREEN), left)+ .with(fill(IntRect::new(400, 100, 200, 200), GREEN), right)+ .with(fill(IntRect::new(0, 500, 800, 50), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // A backdrop filter over the document alone, which reads only its own layer, and one over an earlier canvas, which+ // the compositor composites.+ fn page_with_frosted_glass() -> Page {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let over_document = frosted_glass(&mut tree, document, IntRect::new(400, 100, 200, 100));+ let over_canvas = frosted_glass(&mut tree, document, IntRect::new(100, 100, 200, 100));+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(fill(IntRect::new(400, 100, 200, 100), GREEN), over_document)+ .with(canvas(IntRect::new(100, 100, 200, 100), 1), document)+ .with(fill(IntRect::new(100, 100, 200, 100), GREEN), over_canvas)+ .with(fill(IntRect::new(0, 500, 800, 50), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // A spinner in a group scaled up eighty times, whose space a plan rasters at that scale.+ fn page_with_spinner_in_large_scale() -> Page {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let mut scaling = transform(FloatRect::new(0.0, 0.0, 10.0, 10.0));+ scaling.matrix = libgfx_rust::scale_matrix(80.0, 80.0, 1.0);+ let scaled_node = tree.append_spatial(SpatialData::Transform(scaling), VISUAL_VIEWPORT_NODE_INDEX);+ let spinner_node = tree.append_spatial(+ SpatialData::Transform(transform(FloatRect::new(1.0, 1.0, 4.0, 4.0))),+ scaled_node,+ );+ tree.set_visual_animations(vec![spinning(spinner_node)]);+ let spinner = ContextRef {+ spatial: spinner_node,+ ..viewport+ };+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 100, 100), GREEN), viewport)+ .with(fill(IntRect::new(1, 1, 4, 4), GREEN), spinner)+ .with(fill(IntRect::new(0, 100, 100, 100), GREEN), viewport);+ Page {+ tree,+ list: list.storage(),+ }+ }++ // Translucent groups nested in each other, with a canvas in the group `canvas_depth` deep, so that the compositor+ // composites the groups around it, and a fill in the innermost group.+ fn page_with_canvas_in_nested_groups(group_count: usize, canvas_depth: usize) -> Page {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let mut groups = vec![document];+ for _ in 0..group_count {+ groups.push(tree.append_effect_node_under(+ groups[groups.len() - 1],+ effects(0.5, CompositingAndBlendingOperator::Normal),+ ));+ }+ let list = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 800, 2600), GREEN), document)+ .with(canvas(IntRect::new(100, 100, 200, 100), 1), groups[canvas_depth])+ .with(fill(IntRect::new(150, 150, 200, 100), GREEN), groups[group_count])+ .with(fill(IntRect::new(0, 500, 800, 50), GREEN), document);+ Page {+ tree,+ list: list.storage(),+ }+ }++ fn every_page() -> Vec<(&'static str, Page)> {+ vec![+ ("plain page", plain_page()),+ ("two canvases", page_with_two_canvases()),+ ("canvas in nested scroller", page_with_canvas_in_nested_scroller()),+ ("sticky header", page_with_sticky_header()),+ ("nested composited effects", page_with_nested_composited_effects()),+ ("spinner", page_with_spinner()),+ (+ "spinner holding the root group",+ page_with_spinner_holding_the_root_group(),+ ),+ ("translucent root", page_under_translucent_root()),+ ("no records", page_without_records()),+ ("records that draw nothing", page_whose_records_draw_nothing()),+ ("frosted glass", page_with_frosted_glass()),+ ]+ }++ // The plan WebContent sends of what it planned.+ fn plan_sent_of(planned: &PlannedLayers) -> LayerPlan {+ LayerPlan {+ display_list_id: 42,+ viewport_rect: VIEWPORT,+ stack: planned.stack.clone(),+ }+ }++ fn encoded(plan: &LayerPlan) -> Vec<u8> {+ let mut encoder = Encoder::new();+ encoder.encode(plan).expect("a planned stack encodes");+ encoder.finish().0+ }++ fn decoded_and_validated_plan(page: &Page, bytes: &[u8]) -> Result<LayerPlan, &'static str> {+ let mut decoder = Decoder::new(bytes, []);+ let plan: UnvalidatedLayerPlan = decoder.decode().map_err(|_| "the plan does not decode")?;+ if !decoder.is_at_end() {+ return Err("bytes follow the plan");+ }+ plan.validated(&page.list, &page.tree)+ }++ fn kinds_of_anchors(stack: &LayerStack) -> Vec<&'static str> {+ stack+ .spaces+ .iter()+ .map(|space| match space.anchor_kind {+ RasterSpaceAnchorKind::Viewport => "viewport",+ RasterSpaceAnchorKind::ViewportScroller => "document",+ RasterSpaceAnchorKind::Scroller => "scroller",+ RasterSpaceAnchorKind::StickyBox { .. } => "sticky",+ RasterSpaceAnchorKind::AnimatedTransform { .. } => "animated",+ })+ .collect()+ }++ fn media_layer_count(stack: &LayerStack) -> usize {+ stack+ .layers+ .iter()+ .filter(|layer| matches!(layer.content, LayerContent::Media { .. }))+ .count()+ }++ #[test]+ fn the_pages_plan_the_stacks_the_tests_are_about() {+ let stack_of = |page: Page| page.planned().stack;+ let plain = stack_of(plain_page());+ assert_eq!(kinds_of_anchors(&plain), ["viewport", "document"]);+ assert!(plain.why_list_is_one_layer.is_none());+ assert_eq!(media_layer_count(&stack_of(page_with_two_canvases())), 2);+ let media_identities_of_one_canvas_drawn_twice: Vec<LayerIdentity> = stack_of(page_drawing_one_canvas_twice())+ .layers+ .iter()+ .filter(|layer| matches!(layer.content, LayerContent::Media { .. }))+ .map(|layer| layer.identity)+ .collect();+ let drawing = |ordinal| LayerIdentity::Media {+ content: LiveContent::Canvas(CanvasId(1)),+ ordinal,+ };+ assert_eq!(media_identities_of_one_canvas_drawn_twice, [drawing(0), drawing(1)]);+ let nested = stack_of(page_with_canvas_in_nested_scroller());+ assert_eq!(kinds_of_anchors(&nested), ["viewport", "document", "scroller"]);+ assert_eq!(media_layer_count(&nested), 1);+ assert_eq!(+ kinds_of_anchors(&stack_of(page_with_sticky_header())),+ ["viewport", "document", "sticky"]+ );+ let composited = stack_of(page_with_nested_composited_effects());+ assert_eq!(composited.composited_effects.len(), 2);+ assert_eq!(+ kinds_of_anchors(&stack_of(page_with_spinner())),+ ["viewport", "animated"]+ );+ let root_page = page_with_spinner_holding_the_root_group();+ let root_effect = root_page.tree.root_isolation_effect;+ let composited_effects_of_root_page: Vec<EffectNodeIndex> = stack_of(root_page)+ .composited_effects+ .iter()+ .map(|composited| composited.effect)+ .collect();+ assert_eq!(composited_effects_of_root_page, Vec::from_iter(root_effect));+ assert_eq!(+ stack_of(page_under_translucent_root()).why_list_is_one_layer,+ Some(WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup)+ );+ assert_eq!(+ stack_of(page_without_records()).why_list_is_one_layer,+ Some(WhyListIsOneLayer::EmptyDisplayList)+ );+ let nothing_drawn = stack_of(page_whose_records_draw_nothing());+ assert!(nothing_drawn.why_list_is_one_layer.is_none());+ assert_eq!(nothing_drawn.bands.len(), 1);+ assert!(nothing_drawn.bands[0].record_spans.is_empty() && nothing_drawn.bands[0].cuts.is_empty());+ let crowded = stack_of(page_with_many_nested_scrollers());+ assert_eq!(kinds_of_anchors(&crowded)[2..], ["scroller"; 6]);+ let nested_scrollers_without_spaces = NESTED_SCROLLER_COUNT_OF_CROWDED_PAGE as usize - 6;+ assert!(crowded.spaces.len() + nested_scrollers_without_spaces > MAXIMUM_RASTER_SPACE_COUNT);+ let nine_canvases = stack_of(page_with_nine_canvases());+ assert_eq!(nine_canvases.bands.len(), 1);+ assert_eq!(media_layer_count(&nine_canvases), MAXIMUM_MEDIA_LAYER_COUNT);+ let siblings = stack_of(page_with_two_fading_siblings());+ let parents_of_composited_nodes: Vec<Option<PlacementNodeIndex>> = siblings+ .composited_effects+ .iter()+ .map(|composited| siblings.nodes[composited.placement_node_index.0].parent_index)+ .collect();+ assert_eq!(parents_of_composited_nodes.len(), 2);+ assert_eq!(parents_of_composited_nodes[0], parents_of_composited_nodes[1]);+ let frosted = stack_of(page_with_frosted_glass());+ let reads_of_composited_effects: Vec<bool> = frosted+ .composited_effects+ .iter()+ .map(|composited| composited.reads_what_is_composited_below_it)+ .collect();+ assert_eq!(reads_of_composited_effects, [true]);+ // The spinner is rastered at the scale of its group, far past four times the scale of the viewport.+ let large_scale = stack_of(page_with_spinner_in_large_scale());+ assert!(matches!(+ large_scale.spaces[1..],+ [RasterSpace {+ anchor_kind: RasterSpaceAnchorKind::AnimatedTransform { raster_scale },+ ..+ }] if raster_scale > 64.0+ ));+ }++ #[test]+ fn a_planned_stack_round_trips_through_its_wire_form_and_its_checks() {+ let pages = every_page()+ .into_iter()+ .chain([("spinner in large scale", page_with_spinner_in_large_scale())]);+ for (name, page) in pages {+ let sent = plan_sent_of(&page.planned());+ let plan = decoded_and_validated_plan(&page, &encoded(&sent))+ .unwrap_or_else(|why| panic!("the plan of the {name} is rejected: {why}"));+ assert_eq!(plan, sent, "the plan of the {name} comes back otherwise");+ }+ }++ #[test]+ fn the_compositor_works_out_what_a_plan_on_the_wire_leaves_out() {+ for page in [+ page_with_sticky_header(),+ page_with_frosted_glass(),+ page_under_translucent_root(),+ ] {+ let planned = page.planned();+ let mut stack = planned.stack.clone();+ for space in &mut stack.spaces {+ space.identity ^= 1;+ space.extent = IntRect::new(1, 2, 3, 4);+ }+ for composited in &mut stack.composited_effects {+ composited.reads_what_is_composited_below_it ^= true;+ composited.filter_spreads_what_it_composites ^= true;+ }+ stack.layering_obstacles.sorts_planes_by_depth ^= true;+ assert_eq!(page.validated(stack), Ok(planned.stack));+ }+ }++ // Boxes of the document, each 1 px, alternating with boxes fixed to the viewport that overlap them, so that each fixed+ // box closes the band of the document's space and the next box opens another, cut into the band of the viewport.+ fn page_of_document_boxes_alternating_with_fixed_boxes(pair_count: usize) -> Page {+ let (tree, viewport, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let mut builder = DisplayListBuilder::new();+ for _ in 0..pair_count {+ builder.append(&fill(IntRect::new(0, 0, 1, 1), GREEN), &[], document);+ builder.append(&fill(IntRect::new(0, 0, 1, 1), GREEN), &[], viewport);+ }+ Page {+ tree,+ list: DisplayListStorage::of_builder(&builder),+ }+ }++ #[test]+ fn a_plan_holding_more_than_the_compositor_decodes_is_one_layer() {+ let page_at_limit = page_of_document_boxes_alternating_with_fixed_boxes(MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND);+ let planned_at_limit = page_at_limit.planned();+ assert_eq!(planned_at_limit.stack.why_list_is_one_layer, None);+ assert_eq!(+ planned_at_limit.stack.bands.iter().map(|band| band.cuts.len()).max(),+ Some(MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND)+ );+ let sent_at_limit = plan_sent_of(&planned_at_limit);+ assert_eq!(+ decoded_and_validated_plan(&page_at_limit, &encoded(&sent_at_limit)),+ Ok(sent_at_limit)+ );++ let page = page_of_document_boxes_alternating_with_fixed_boxes(MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND + 1);+ let planned = page.planned();+ assert_eq!(+ planned.stack.why_list_is_one_layer,+ Some(WhyListIsOneLayer::PlanHoldsMoreThanCompositorDecodes)+ );+ let sent = plan_sent_of(&planned);+ assert_eq!(decoded_and_validated_plan(&page, &encoded(&sent)), Ok(sent));+ }++ // A page can nest composited effects deeper than a walk over the nodes of its plan can hold frames of on a stack.+ #[test]+ fn composited_effects_nested_far_past_the_limit_give_one_layer() {+ let page = page_with_canvas_in_nested_groups(100_000, 100_000);+ assert_eq!(+ page.planned().stack.why_list_is_one_layer,+ Some(WhyListIsOneLayer::CompositedEffectsNestTooDeep)+ );+ }++ #[test]+ fn composited_effects_nest_in_a_plan_as_deep_as_the_limit() {+ let deepest = MAXIMUM_NESTING_OF_COMPOSITED_EFFECTS;+ let page_at_limit = page_with_canvas_in_nested_groups(deepest, deepest);+ let planned = page_at_limit.planned();+ let stack = &planned.stack;+ assert_eq!(stack.why_list_is_one_layer, None);+ let (canvas_layer_index, _) = stack+ .layers+ .iter()+ .enumerate()+ .find(|(_, layer)| matches!(layer.content, LayerContent::Media { .. }))+ .expect("the canvas has a layer");+ assert_eq!(+ stack+ .composited_bands_around_layer_innermost_first(LayerIndex(canvas_layer_index))+ .count(),+ deepest+ );+ let sent = plan_sent_of(&planned);+ assert_eq!(decoded_and_validated_plan(&page_at_limit, &encoded(&sent)), Ok(sent));++ let page_past_limit = page_with_canvas_in_nested_groups(deepest + 1, deepest + 1);+ assert_eq!(+ page_past_limit.planned().stack.why_list_is_one_layer,+ Some(WhyListIsOneLayer::CompositedEffectsNestTooDeep)+ );++ // The innermost group holds only a fill, so it is not composited, until a plan says it is.+ let page_with_group_past_limit = page_with_canvas_in_nested_groups(deepest + 1, deepest);+ let mut plan = page_with_group_past_limit.planned_plan();+ assert!(page_with_group_past_limit.validated_plan(plan.clone()).is_ok());+ let innermost_group = EffectNodeIndex(page_with_group_past_limit.tree.effect_nodes.len() as u32 - 1);+ let group_around = EffectNodeIndex(innermost_group.0 - 1);+ let node_of_group_around = plan+ .nodes+ .iter()+ .position(|node| node.composited_effect == Some(group_around))+ .expect("the group around the canvas is composited");+ plan.nodes.push(NodeOfPlan {+ composited_effect: Some(innermost_group),+ parent_index: Some(PlacementNodeIndex(node_of_group_around)),+ reach_in_parent_node: Reach::Nothing,+ ..plan.nodes[node_of_group_around].clone()+ });+ assert_eq!(+ page_with_group_past_limit.validated_plan(plan),+ Err("composited effects nest deeper than a plan nests them")+ );+ }++ #[test]+ fn the_read_reaches_of_the_composited_filters_around_a_layer_add_up_to_at_most_the_largest_sum() {+ let stack = page_with_nested_composited_effects().planned().stack;+ let read_reach_of_one_filter = 5000;+ let read_reach_by_layer =+ stack.summed_read_reach_of_composited_filters_by_layer(|_, _| read_reach_of_one_filter);+ let largest = LARGEST_SUMMED_READ_REACH_OF_COMPOSITED_FILTERS_IN_DEVICE_PIXELS;+ assert!(read_reach_of_one_filter < largest && 2 * read_reach_of_one_filter > largest);+ let expected: Vec<i32> = (0..stack.layers.len())+ .map(|layer_index| {+ let nesting = stack+ .composited_bands_around_layer_innermost_first(LayerIndex(layer_index))+ .count() as i32;+ (nesting * read_reach_of_one_filter).min(largest)+ })+ .collect();+ assert_eq!(read_reach_by_layer, expected);+ assert!(read_reach_by_layer.contains(&read_reach_of_one_filter));+ assert!(read_reach_by_layer.contains(&largest));+ }++ #[test]+ fn a_plan_for_a_viewport_past_the_coordinate_limit_is_refused() {+ let viewport_past_limit = IntRect::new(0, 0, COORDINATE_LIMIT_IN_DEVICE_PIXELS + 1, 600);+ for page in [plain_page(), page_under_translucent_root()] {+ let stack = page.planned().stack;+ assert!(validated_stack(on_wire(&stack), &page.list, &page.tree, VIEWPORT).is_ok());+ assert!(validated_stack(on_wire(&stack), &page.list, &page.tree, viewport_past_limit).is_err());+ }+ }++ #[test]+ fn every_reason_and_kind_round_trips() {+ fn round_trip<T: Encode + Decode + PartialEq + std::fmt::Debug>(value: T) {+ let mut encoder = Encoder::new();+ encoder.encode(&value).unwrap();+ let bytes = encoder.finish().0;+ let mut decoder = Decoder::new(&bytes, []);+ assert_eq!(decoder.decode::<T>().unwrap(), value);+ assert!(decoder.is_at_end());+ }+ for why in [+ WhyCompositorCannotCompositeEffect::FilterMovesWhatItFilters,+ WhyCompositorCannotCompositeEffect::FilterReadsFartherThanTilesAreFollowed,+ ] {+ round_trip(why);+ round_trip(WhyListIsOneLayer::EffectTheCompositorCannotCompositeIsComposited(why));+ }+ for why in [+ WhyListIsOneLayer::EmptyViewport,+ WhyListIsOneLayer::EmptyDisplayList,+ WhyListIsOneLayer::SortingContext3D,+ WhyListIsOneLayer::RootIsolationEffectIsNotPlainGroup,+ WhyListIsOneLayer::MaskDeclaredUnderEffectsItsMaskIsNotUnder,+ WhyListIsOneLayer::RecordsBlendWithWhatOtherLayersHoldBelowThem,+ WhyListIsOneLayer::CompositedEffectsNestTooDeep,+ WhyListIsOneLayer::FrameIsNotDrawnAsPlanned,+ WhyListIsOneLayer::PlanShowsTooManyTiles,+ WhyListIsOneLayer::PlanFailsChecksOfCompositor,+ ] {+ round_trip(why);+ }+ for content in [+ LiveContent::Canvas(CanvasId(1)),+ LiveContent::VideoFrame(VideoSinkHandle(2)),+ LiveContent::ImageFrame(ImageFrameResourceId(3)),+ LiveContent::CompositedContext(CompositorContextId(4)),+ ] {+ round_trip(content);+ }+ for reach in [Reach::Nothing, Reach::Within(IntRect::new(1, 2, 3, 4)), Reach::Anywhere] {+ round_trip(reach);+ }+ }++ #[test]+ fn a_count_or_a_length_past_its_maximum_is_refused_before_anything_is_allocated() {+ let mut encoder = Encoder::new();+ encoder.encode(&PLAN_KIND_LAYERED).unwrap();+ encoder.encode_size(MAXIMUM_NODE_COUNT_OF_RECEIVED_STACK + 1).unwrap();+ let bytes = encoder.finish().0;+ assert!(matches!(+ Decoder::new(&bytes, []).decode::<StackOnWire>(),+ Err(DecodeError::SizeTooLarge(_))+ ));+ let page = page_with_two_canvases();+ // A count of many spans that the bytes cannot hold is refused too.+ let mut bytes = encoded(&plan_sent_of(&page.planned()));+ bytes.truncate(bytes.len() / 2);+ assert!(decoded_and_validated_plan(&page, &bytes).is_err());+ }++ // The band and the cut of the first canvas, video or nested context of the plan.+ fn first_media_cut(plan: &LayeredPlan) -> (usize, usize) {+ plan.bands+ .iter()+ .enumerate()+ .find_map(|(band_index, band)| {+ band.cuts+ .iter()+ .position(|cut| matches!(cut.barrier, BarrierOfPlan::Media { .. }))+ .map(|cut_index| (band_index, cut_index))+ })+ .expect("the plan has a canvas")+ }++ fn first_media_of(plan: &mut LayeredPlan) -> (&mut LiveContent, &mut u32, &mut ListSpan, &mut IntRect) {+ let (band_index, cut_index) = first_media_cut(plan);+ let BarrierOfPlan::Media {+ content,+ ordinal,+ record_span,+ reach,+ } = &mut plan.bands[band_index].cuts[cut_index].barrier+ else {+ unreachable!()+ };+ (content, ordinal, record_span, reach)+ }++ fn band_with_cuts(plan: &LayeredPlan) -> usize {+ plan.bands+ .iter()+ .position(|band| band.cuts.len() >= 2)+ .expect("the plan has a band with two cuts")+ }++ fn band_with_spans(plan: &LayeredPlan) -> usize {+ plan.bands+ .iter()+ .position(|band| !band.record_spans.is_empty())+ .expect("the plan has a band with spans")+ }++ fn composited_node_indices(plan: &LayeredPlan) -> Vec<usize> {+ (0..plan.nodes.len())+ .filter(|&index| plan.nodes[index].composited_effect.is_some())+ .collect()+ }++ fn band_of_node(plan: &LayeredPlan, node: usize) -> usize {+ plan.bands+ .iter()+ .position(|band| band.placement_node_index.0 == node)+ .expect("the node has a band")+ }++ // Gives the last canvas of the page with nine canvases a layer as a plan gives a canvas one, past the most a plan+ // gives.+ fn give_last_of_nine_canvases_a_layer(plan: &mut LayeredPlan) {+ let (band_index, cut_index) = first_media_cut(plan);+ let BarrierOfPlan::Media {+ record_span: span_of_first_canvas,+ reach,+ ..+ } = plan.bands[band_index].cuts[cut_index].barrier+ else {+ unreachable!()+ };+ let band = &mut plan.bands[band_index];+ let span_holding_last_canvas = band.record_spans.last_mut().expect("the band holds the last canvas");+ let canvas_size = span_of_first_canvas.end.offset - span_of_first_canvas.begin.offset;+ let span_of_last_canvas = ListSpan {+ begin: ListPosition::new(+ span_holding_last_canvas.end.chunk_index,+ span_holding_last_canvas.end.offset - canvas_size,+ ),+ end: span_holding_last_canvas.end,+ };+ span_holding_last_canvas.end = span_of_last_canvas.begin;+ band.cuts.push(CutOfPlan {+ barrier: BarrierOfPlan::Media {+ content: LiveContent::Canvas(CanvasId(9)),+ ordinal: 0,+ record_span: span_of_last_canvas,+ reach,+ },+ reach_of_layer_above_cut: IntRect::default(),+ });+ }++ // Moves the records of the band of the fixed header of the plain page into a band of a node of the viewport's space+ // that no cut enters.+ fn move_header_into_band_no_cut_enters(plan: &mut LayeredPlan) {+ let header_span = plan.bands[0]+ .record_spans+ .pop()+ .expect("the first band holds the header");+ plan.nodes.push(NodeOfPlan {+ raster_space_index: RasterSpaceIndex::VIEWPORT,+ composite_clips: vec![CompositeClip {+ raster_space_index: RasterSpaceIndex::VIEWPORT,+ rect: IntRect::new(0, 0, 800, 50),+ corner_radii: libgfx_rust::CornerRadii::default(),+ }],+ composited_effect: None,+ parent_index: None,+ reach_in_parent_node: Reach::Anywhere,+ });+ plan.bands.push(BandOfPlan {+ placement_node_index: PlacementNodeIndex(plan.nodes.len() - 1),+ record_spans: vec![header_span],+ reach_of_layer_below_all_cuts: IntRect::new(0, 0, 800, 50),+ cuts: Vec::new(),+ });+ }++ type Mutation = fn(&mut LayeredPlan);++ // The need a mutation breaks, the page whose plan it mutates, and the mutation.+ type Rejection = (&'static str, fn() -> Page, Mutation);++ fn rejections() -> Vec<Rejection> {+ fn space_count(plan: &LayeredPlan) -> usize {+ plan.tiles_hold_content_moving_within_space_by_space_index.len()+ }+ fn every_band_holds_every_record_the_bands_hold(plan: &mut LayeredPlan) {+ let spans_of_bands = plan.bands.iter().flat_map(|band| &band.record_spans);+ let every_record_the_bands_hold = ListSpan {+ begin: spans_of_bands+ .clone()+ .map(|span| span.begin)+ .min()+ .expect("a band holds records"),+ end: spans_of_bands.map(|span| span.end).max().expect("a band holds records"),+ };+ for band in &mut plan.bands {+ band.record_spans = vec![every_record_the_bands_hold];+ }+ }+ vec![+ ("node of a band out of range", page_with_two_canvases, |plan| {+ plan.bands[0].placement_node_index = PlacementNodeIndex(plan.nodes.len());+ }),+ ("space of a node out of range", page_with_two_canvases, |plan| {+ plan.nodes[0].raster_space_index = RasterSpaceIndex(space_count(plan));+ }),+ (+ "space of a composite clip out of range",+ page_with_two_canvases,+ |plan| {+ let raster_space_index = RasterSpaceIndex(space_count(plan));+ plan.nodes[0].composite_clips.push(CompositeClip {+ raster_space_index,+ rect: IntRect::new(0, 0, 10, 10),+ corner_radii: libgfx_rust::CornerRadii::default(),+ });+ },+ ),+ ("node in itself", page_with_two_canvases, |plan| {+ plan.nodes[1].parent_index = Some(PlacementNodeIndex(1));+ }),+ (+ "composited node in no node",+ page_with_nested_composited_effects,+ |plan| {+ let node = composited_node_indices(plan)[0];+ plan.nodes[node].parent_index = None;+ },+ ),+ (+ "composited effect out of range",+ page_with_nested_composited_effects,+ |plan| {+ let node = composited_node_indices(plan)[0];+ plan.nodes[node].composited_effect = Some(EffectNodeIndex(9999));+ },+ ),+ (+ "composited effects nested otherwise than in the tree",+ page_with_nested_composited_effects,+ |plan| {+ let [first, second] = composited_node_indices(plan)[..] else {+ unreachable!()+ };+ let first_effect = plan.nodes[first].composited_effect;+ plan.nodes[first].composited_effect = plan.nodes[second].composited_effect;+ plan.nodes[second].composited_effect = first_effect;+ },+ ),+ (+ "media layer at a run that draws a fill",+ page_with_two_canvases,+ |plan| {+ let (_, _, record_span, _) = first_media_of(plan);+ record_span.begin = ListPosition::default();+ },+ ),+ (+ "media layer that names another canvas",+ page_with_two_canvases,+ |plan| *first_media_of(plan).0 = LiveContent::Canvas(CanvasId(77)),+ ),+ ("media layer of an image", page_with_two_canvases, |plan| {+ *first_media_of(plan).0 = LiveContent::ImageFrame(ImageFrameResourceId(1));+ }),+ ("span that starts inside a run", page_with_two_canvases, |plan| {+ let band = band_with_spans(plan);+ plan.bands[band].record_spans[0].begin.offset += 1;+ }),+ ("span in a chunk the list does not hold", plain_page, |plan| {+ let band = band_with_spans(plan);+ plan.bands[band].record_spans[0].end.chunk_index = ChunkIndexInList(999);+ }),+ ("span that ends before it begins", plain_page, |plan| {+ let band = band_with_spans(plan);+ let span = &mut plan.bands[band].record_spans[0];+ std::mem::swap(&mut span.begin, &mut span.end);+ }),+ ("media layer that starts inside a run", page_with_two_canvases, |plan| {+ first_media_of(plan).2.begin.offset += 4+ }),+ ("spans out of paint order", page_with_two_canvases, |plan| {+ let band = band_with_cuts(plan);+ plan.bands[band].record_spans.reverse();+ }),+ ("cuts out of paint order", page_with_two_canvases, |plan| {+ let band = band_with_cuts(plan);+ plan.bands[band].cuts.reverse();+ }),+ ("two layers of one identity", page_drawing_one_canvas_twice, |plan| {+ let band = band_with_cuts(plan);+ let BarrierOfPlan::Media { ordinal, .. } = &mut plan.bands[band].cuts[1].barrier else {+ unreachable!()+ };+ *ordinal = 0;+ }),+ ("reach of a layer past the limit", page_with_two_canvases, |plan| {+ plan.bands[0].reach_of_layer_below_all_cuts = IntRect::new(i32::MAX - 10, 0, 100, 100);+ }),+ ("rect of negative size", page_with_two_canvases, |plan| {+ plan.bands[0].reach_of_layer_below_all_cuts = IntRect::new(0, 0, -10, 100);+ }),+ (+ "reach of a layer above a cut past the limit",+ page_with_two_canvases,+ |plan| {+ let band = band_with_cuts(plan);+ plan.bands[band].cuts[0].reach_of_layer_above_cut = IntRect::new(0, i32::MIN, 1, 1);+ },+ ),+ ("reach of a node past the limit", page_with_two_canvases, |plan| {+ plan.nodes[0].reach_in_parent_node = Reach::Within(IntRect::new(i32::MIN, i32::MIN, 10, 10));+ }),+ ("reach of a canvas past the limit", page_with_two_canvases, |plan| {+ *first_media_of(plan).3 = IntRect::new(0, 0, i32::MAX, 1);+ }),+ ("negative radius of a composite clip", page_with_two_canvases, |plan| {+ plan.nodes[1].composite_clips.push(CompositeClip {+ raster_space_index: RasterSpaceIndex(0),+ rect: IntRect::new(0, 0, 10, 10),+ corner_radii: libgfx_rust::CornerRadii::uniform(-5),+ });+ }),+ ("swept reach past the limit", page_with_spinner, |plan| {+ plan.swept_reach_in_parent_space_by_space_index[1] = Some(IntRect::new(1 << 30, 0, 1, 1));+ }),+ ("a value per space missing", page_with_two_canvases, |plan| {+ plan.tiles_hold_content_moving_within_space_by_space_index.pop();+ }),+ ("a swept reach per space too many", page_with_two_canvases, |plan| {+ plan.swept_reach_in_parent_space_by_space_index.push(None)+ }),+ (+ "a swept reach of a space the compositor does not animate",+ page_with_two_canvases,+ |plan| plan.swept_reach_in_parent_space_by_space_index[1] = Some(IntRect::new(0, 0, 1, 1)),+ ),+ ("record held by two bands", plain_page, |plan| {+ let span_of_document = plan.bands[1].record_spans[0];+ plan.bands[0].record_spans.insert(0, span_of_document);+ }),+ (+ "records held by every band",+ plain_page,+ every_band_holds_every_record_the_bands_hold,+ ),+ (+ "records held by every band",+ page_with_canvas_in_nested_scroller,+ every_band_holds_every_record_the_bands_hold,+ ),+ (+ "record held by a band and by a media layer",+ page_with_two_canvases,+ |plan| {+ let (band_index, _) = first_media_cut(plan);+ let record_span = *first_media_of(plan).2;+ let band = &mut plan.bands[band_index];+ let position = band.record_spans.partition_point(|span| span.end <= record_span.begin);+ band.record_spans.insert(position, record_span);+ },+ ),+ ("span that holds no record", page_with_two_canvases, |plan| {+ let band = band_with_spans(plan);+ let end_of_first_span = plan.bands[band].record_spans[0].end;+ plan.bands[band].record_spans.insert(+ 1,+ ListSpan {+ begin: end_of_first_span,+ end: end_of_first_span,+ },+ );+ }),+ ("band other than the first that holds nothing", plain_page, |plan| {+ plan.bands[1].record_spans.clear()+ }),+ (+ "more media layers than a plan makes",+ page_with_nine_canvases,+ give_last_of_nine_canvases_a_layer,+ ),+ (+ "two nodes composited inside one effect",+ page_with_two_fading_siblings,+ |plan| {+ let [first, second] = composited_node_indices(plan)[..] else {+ unreachable!()+ };+ plan.nodes[second].composited_effect = plan.nodes[first].composited_effect;+ },+ ),+ ("node in a node of its own space", plain_page, |plan| {+ plan.nodes[1].raster_space_index = RasterSpaceIndex::VIEWPORT;+ }),+ (+ "composited node in a node of another space",+ page_with_nested_composited_effects,+ |plan| {+ let node = composited_node_indices(plan)[0];+ plan.nodes[node].raster_space_index = RasterSpaceIndex::VIEWPORT;+ },+ ),+ ("no band", plain_page, |plan| plan.bands.clear()),+ (+ "bands in a band out of the order of their cuts",+ page_with_two_fading_siblings,+ |plan| {+ let [first, second] = composited_node_indices(plan)[..] else {+ unreachable!()+ };+ let (first_band, second_band) = (band_of_node(plan, first), band_of_node(plan, second));+ plan.bands.swap(first_band, second_band);+ },+ ),+ ("cut that enters no band", plain_page, |plan| {+ plan.bands+ .last_mut()+ .expect("the plan has a band")+ .cuts+ .push(CutOfPlan {+ barrier: BarrierOfPlan::NestedBand,+ reach_of_layer_above_cut: IntRect::default(),+ });+ }),+ (+ "band that no cut enters",+ plain_page,+ move_header_into_band_no_cut_enters,+ ),+ (+ "band entered at a cut of a band of a node it is not in",+ plain_page,+ |plan| plan.bands[1].placement_node_index = PlacementNodeIndex(0),+ ),+ ("first band of a node in another node", plain_page, |plan| {+ plan.bands[0].placement_node_index = PlacementNodeIndex(1);+ }),+ (+ "first drawing of a canvas numbered as if one came before it",+ page_with_two_canvases,+ |plan| *first_media_of(plan).1 = 1,+ ),+ (+ "second drawing of a canvas numbered past the bits a sublayer keeps for it",+ page_drawing_one_canvas_twice,+ |plan| {+ let band = band_with_cuts(plan);+ let BarrierOfPlan::Media { ordinal, .. } = &mut plan.bands[band].cuts[1].barrier else {+ unreachable!()+ };+ *ordinal = 1 << 16;+ },+ ),+ ]+ }++ #[test]+ fn a_plan_that_a_consumer_cannot_read_safely_is_rejected() {+ for (need, page, mutate) in rejections() {+ let page = page();+ let mut plan = page.planned_plan();+ assert!(+ page.validated_plan(plan.clone()).is_ok(),+ "{need}: the planned stack passes"+ );+ mutate(&mut plan);+ assert!(+ page.validated_plan(plan).is_err(),+ "{need}: the mutated plan is rejected"+ );+ }+ }++ // The layer the band's record at `record_position` goes into within the tile at `cell`: the one above the last barrier+ // painted before it that cuts the tile.+ fn layer_of_record_in_cell(band: &PlacementNodeBand, record_position: ListPosition, cell: IntRect) -> LayerIndex {+ band.cuts+ .iter()+ .take_while(|cut| cut.barrier_first_record_position <= record_position)+ .filter(|cut| cut.cuts_cell(cell))+ .last()+ .map_or(band.layer_below_all_cuts, |cut| cut.layer_above_cut)+ }++ // The cuts of a cell are worked out once for the cell, and a record finds its layer among them.+ #[test]+ fn the_cuts_of_a_cell_place_each_record_in_the_layer_the_band_places_it_in() {+ let pages = every_page().into_iter().chain([+ ("canvas drawn twice", page_drawing_one_canvas_twice()),+ ("nine canvases", page_with_nine_canvases()),+ ]);+ for (name, page) in pages {+ let stack = page.planned().stack;+ let record_positions: Vec<ListPosition> = (0..page.list.run_count())+ .map(|run_index| page.list.span_of_run(run_index).begin)+ .collect();+ for band in &stack.bands {+ for (column, row) in (-1..3).flat_map(|column| (-1..6).map(move |row| (column, row))) {+ let cell = crate::display_list::tiles::TileCoord::new(column, row).cell_rect();+ let cuts_of_cell = CutsOfCell::of(band, cell);+ for &position in &record_positions {+ let (layer, _) = cuts_of_cell.layer_of_record(position);+ assert_eq!(layer, layer_of_record_in_cell(band, position, cell), "{name}");+ }+ }+ }+ }+ }++ // Reads the stack as the compositor reads it for a frame over the whole viewport, and as the dump reads it.+ fn read_as_consumers_do(page: &Page, frame_tree: &VisualContextTree, planned: &PlannedLayers, stack: &LayerStack) {+ let list = &page.list;+ let scroll_offsets = [FloatPoint { x: 0.0, y: 300.0 }; 4];+ let composite_offsets = stack.composite_offsets(&scroll_offsets);+ let spaces_to_frame = stack.spaces_to_frame(&composite_offsets, |_| {+ libgfx_rust::affine_to_matrix(libgfx_rust::AffineTransform::new(0.5, 0.5, -0.5, 0.5, 10.0, 20.0))+ });+ for layer_index in (0..stack.layers.len()).map(LayerIndex) {+ stack.composited_bands_around_layer_innermost_first(layer_index).count();+ stack.composite_clip_of_layer_in_viewport(layer_index, &composite_offsets);+ stack.rounded_composite_clips_of_node_in_viewport(+ stack.layers[layer_index.0].placement_node_index,+ &composite_offsets,+ );+ stack.layer_is_in_animated_space(layer_index);+ stack.name_of_layer(layer_index, &NodeNamesFromIndices);+ let space_to_frame = spaces_to_frame[stack.space_of_layer(layer_index).0];+ space_to_frame.rect_in_frame(stack.layers[layer_index.0].reach);+ space_to_frame.rect_in_space(VIEWPORT);+ }+ for band_index in (0..stack.bands.len()).map(BandIndex) {+ stack.band_has_layer_at_or_above_base_layer(band_index);+ }+ stack.layers_the_window_server_shows(&composite_offsets, |_| true);+ let presentation = stack.window_server_presentation_of_media(list, frame_tree, &scroll_offsets, VIEWPORT);+ let planned_with_stack = PlannedLayers {+ stack: stack.clone(),+ placement: planned.placement.clone(),+ };+ planned_with_stack.layer_lines(&presentation, &NodeNamesFromIndices, |layer| {+ Some(format!("{}", layer.0))+ });+ planned_with_stack.layer_lines(+ &WindowServerPresentationOfMedia::default(),+ &NodeNamesFromIndices,+ |_| None,+ );+ for run_index in 0..list.run_count() {+ planned_with_stack.layers_of_record(list.span_of_run(run_index).begin);+ }+ for layer_index in 0..stack.layers.len() {+ stack.space_holds_content_that_moves_within_it(stack.space_of_layer(LayerIndex(layer_index)));+ }++ let tile_keying_of_list = TileKeyingOfList::new(list, frame_tree, stack, NO_FRAME_STATE);+ let raster_spaces = RasterSpaces::of_spaces(frame_tree, stack.spaces.clone());+ let what_every_space_of_tree_shares = WhatEverySpaceOfTreeShares::of(frame_tree);+ let geometries: Vec<RasterSpaceGeometry> = (0..stack.spaces.len())+ .map(|space_index| {+ RasterSpaceGeometry::new(+ frame_tree,+ &raster_spaces,+ RasterSpaceIndex(space_index),+ &scroll_offsets,+ FloatMatrix4x4::identity(),+ &what_every_space_of_tree_shares,+ )+ })+ .collect();+ let tile_keying_by_space: Vec<TileKeyingOfRasterSpace<'_>> = geometries+ .iter()+ .map(|geometry| TileKeyingOfRasterSpace::new(&tile_keying_of_list, geometry))+ .collect();+ let raster_settings_hash_by_layer = raster_settings_hash_by_layer(stack);+ for (band_position, band) in stack.bands.iter().enumerate() {+ let band_index = BandIndex(band_position);+ if !stack.band_has_layer_at_or_above_base_layer(band_index) {+ continue;+ }+ let space_index = stack.nodes[band.placement_node_index.0].raster_space_index;+ let tile_keying = &tile_keying_by_space[space_index.0];+ let shown_in_viewport = stack+ .composite_clip_of_layer_in_viewport(band.layer_below_all_cuts, &composite_offsets)+ .map_or(VIEWPORT, |clip| VIEWPORT.intersected(clip));+ let shown_rect = spaces_to_frame[space_index.0].rect_in_space(shown_in_viewport);+ let mut band_tile_keys = tile_keying.bind_band(stack, band_index);+ for _ in 0..2 {+ tile_keying.key_shown_tiles(+ &mut band_tile_keys,+ stack,+ band_index,+ &raster_settings_hash_by_layer,+ shown_rect,+ shown_rect,+ Some(VIEWPORT),+ );+ }+ for tile in band_tile_keys.tiles_within(shown_rect) {+ assert!(tile.layer_index.0 < stack.layers.len());+ tile_keying.coverage_of_tile(&band_tile_keys, tile, tile.coord.cell_rect(), Color::TRANSPARENT);+ band_tile_keys.record_spans_of_tiles([tile]);+ }+ }+ for composited in &stack.composited_effects {+ let space_index = stack.nodes[composited.placement_node_index.0].raster_space_index;+ tile_keying_by_space[space_index.0].content_hash_of_composited_effect(composited.effect);+ crate::display_list::effect_geometry::backdrop_filter_read_reach(+ frame_tree,+ &geometries[space_index.0],+ composited.effect,+ );+ }+ for (layer_index, layer) in stack.layers.iter().enumerate() {+ if let LayerContent::Media { record_span, .. } = layer.content {+ tile_keying_by_space[stack.space_of_layer(LayerIndex(layer_index)).0]+ .content_hash_of_records_within(record_span);+ }+ }+ }++ // A small generator of numbers that are far from random but alike from one run to the next.+ struct Xorshift(u64);++ impl Xorshift {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }++ fn below(&mut self, bound: usize) -> usize {+ (self.next() % bound as u64) as usize+ }+ }++ const BOUNDARY_VALUES: [u32; 12] = [+ 0,+ 1,+ 2,+ 3,+ u32::MAX,+ i32::MIN as u32,+ i32::MAX as u32,+ 0x7fc0_0000,+ 0x7f80_0000,+ 0xff80_0000,+ 0x7149_f2ca,+ 0x0080_0000,+ ];++ fn mutated(bytes: &[u8], generator: &mut Xorshift) -> Vec<u8> {+ let mut bytes = bytes.to_vec();+ for _ in 0..=generator.below(3) {+ if bytes.is_empty() {+ break;+ }+ match generator.below(5) {+ 0 => {+ let position = generator.below(bytes.len());+ bytes[position] ^= 1 << generator.below(8);+ }+ 1 if bytes.len() >= 4 => {+ let position = generator.below(bytes.len() - 3);+ let value = BOUNDARY_VALUES[generator.below(BOUNDARY_VALUES.len())];+ bytes[position..position + 4].copy_from_slice(&value.to_ne_bytes());+ }+ 2 => {+ let (first, second) = (generator.below(bytes.len()), generator.below(bytes.len()));+ bytes.swap(first, second);+ }+ 3 => {+ let position = generator.below(bytes.len());+ bytes[position] = generator.next() as u8;+ }+ _ => bytes.truncate(generator.below(bytes.len())),+ }+ }+ bytes+ }++ // Decoding a tree checks the parent of no dead node, and a mask declaration can name any node.+ #[test]+ fn a_mask_declared_for_a_dead_effect_node_lets_no_record_replay_alone_in_its_tiles() {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0];+ let effect_to_kill = tree.append_effect(+ effects(0.5, CompositingAndBlendingOperator::Normal),+ EffectNodeIndex::NONE,+ VISUAL_VIEWPORT_NODE_INDEX,+ ClipNodeIndex::NONE,+ );+ let list_declaring_content_of_mask = |mask_effect: EffectNodeIndex| {+ let mut builder = DisplayListBuilder::new();+ builder.append(&fill(IntRect::new(0, 0, 800, 2600), GREEN), &[], document);+ builder.append(&canvas(IntRect::new(100, 100, 200, 100), 1), &[], document);+ let declaration = builder.begin_group::<DeclareMaskContent>(Vec::new());+ builder.append(&fill(IntRect::new(0, 0, 10, 10), GREEN), &[], document);+ let content = builder.group_content_span(&declaration);+ builder.finish_group(+ declaration,+ &DeclareMaskContent {+ rect: IntRect::new(0, 0, 10, 10),+ effect: mask_effect,+ content,+ },+ document,+ );+ DisplayListStorage::of_builder(&builder)+ };+ let page_with_live_mask = Page {+ tree: tree.clone(),+ list: list_declaring_content_of_mask(document.effect),+ };+ assert!(!page_with_live_mask.planned().stack.replays_whole_list());+ for parent_of_dead_node in [effect_to_kill, EffectNodeIndex(1000)] {+ let mut tree_with_dead_node = tree.clone();+ tree_with_dead_node.effect_nodes[effect_to_kill.0 as usize].data = EffectNodeData::Dead;+ tree_with_dead_node.effect_nodes[effect_to_kill.0 as usize].parent = parent_of_dead_node;+ let page_with_dead_mask = Page {+ tree: VisualContextTree::from_bytes(&tree_with_dead_node.to_bytes())+ .expect("a dead node may have any parent"),+ list: list_declaring_content_of_mask(effect_to_kill),+ };+ let one_layer = LayerStack::one_layer_replaying_whole_list(+ VIEWPORT,+ page_with_dead_mask.list.whole_span(),+ Some(WhyListIsOneLayer::EmptyViewport),+ LayeringObstacles::default(),+ );+ for stack in [+ page_with_dead_mask.validated(one_layer),+ page_with_dead_mask.validated_plan(page_with_live_mask.planned_plan()),+ ] {+ let stack = stack.expect("the stack passes its checks");+ assert!(stack.layering_obstacles.every_tile_replays_every_record());+ }+ }+ }++ // A candidate turned away takes no space, so candidates after it still get one, however many are turned away.+ #[test]+ fn anchors_are_chosen_past_candidates_that_are_turned_away() {+ let (mut tree, _, contexts) = tree_with_document_scroller(&[]);+ let document = contexts[0].spatial;+ let scrollport = IntRect::new(0, 0, 100, 100);+ let mut records = tree.compositor_scroll_table().nodes.to_vec();+ let mut scrollers_without_wheel = Vec::new();+ let mut innermost_scroller = document;+ for _ in 0..8 {+ let node = scroll_node(&mut tree, innermost_scroller);+ let mut record = scroll_record(node, innermost_scroller, scrollport, 300.0, false);+ record.can_be_wheel_scrolled_vertically = false;+ records.push(record);+ scrollers_without_wheel.push(node);+ innermost_scroller = node;+ }+ let scroller_inside_too_many_scrollers = scroll_node(&mut tree, innermost_scroller);+ records.push(scroll_record(+ scroller_inside_too_many_scrollers,+ innermost_scroller,+ scrollport,+ 300.0,+ false,+ ));+ let scroller_in_document = scroll_node(&mut tree, document);+ records.push(scroll_record(scroller_in_document, document, scrollport, 300.0, false));+ assert!(tree.set_compositor_scroll_table(CompositorScrollTable {+ nodes: records.into(),+ ..CompositorScrollTable::default()+ }));+ let mut animations = Vec::new();+ for _ in 0..2000 {+ let node = tree.append_spatial(+ SpatialData::Transform(transform(FloatRect::new(0.0, 0.0, 10.0, 10.0))),+ document,+ );+ tree.append_effect(+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Multiply,+ filter: None,+ backdrop_filter: None,+ }),+ EffectNodeIndex::NONE,+ node,+ ClipNodeIndex::NONE,+ );+ animations.push(spinning(node));+ }+ let spinners: Vec<SpatialNodeIndex> = (0..3)+ .map(|_| {+ let node = tree.append_spatial(+ SpatialData::Transform(transform(FloatRect::new(0.0, 0.0, 10.0, 10.0))),+ document,+ );+ animations.push(spinning(node));+ node+ })+ .collect();+ tree.set_visual_animations(animations);++ let anchors = anchors_of_layer_plans(&tree);+ let [first, second, third, fourth, fifth, ..] = scrollers_without_wheel[..] else {+ unreachable!();+ };+ let mut expected_anchors = vec![document, first, scroller_in_document, second, third, fourth, fifth];+ expected_anchors.extend(&spinners);+ assert_eq!(anchors, expected_anchors);+ let parent_indices: Vec<usize> = RasterSpaces::spaces_at_anchors(&tree, &anchors, VIEWPORT)+ .iter()+ .skip(1)+ .map(|space| space.parent_index.0)+ .collect();+ assert_eq!(parent_indices, [0, 1, 1, 2, 4, 5, 6, 1, 1, 1]);+ }++ #[test]+ fn a_mutated_plan_that_passes_its_checks_is_read_without_a_panic() {+ let mut generator = Xorshift(0x9e37_79b9_7f4a_7c15);+ let mut validated_count = 0;+ for (name, page) in every_page() {+ let planned = page.planned();+ let frame_tree = page.tree.with_visual_animation_samples(250_000_000);+ read_as_consumers_do(&page, &frame_tree, &planned, &planned.stack);+ let bytes = encoded(&plan_sent_of(&planned));+ for trial in 0..3000 {+ let mutated_bytes = mutated(&bytes, &mut generator);+ let Ok(plan) = decoded_and_validated_plan(&page, &mutated_bytes) else {+ continue;+ };+ validated_count += 1;+ let reading = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ read_as_consumers_do(&page, &frame_tree, &planned, &plan.stack);+ }));+ assert!(reading.is_ok(), "trial {trial} of the {name} panics: {:?}", plan.stack);+ }+ }+ assert!(validated_count > 0, "some mutated plans pass their checks");+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/mod.rs b/Libraries/LibCompositing/Rust/src/display_list/mod.rsindex 74d7fcafd1e..c32ffc04290 100644--- a/Libraries/LibCompositing/Rust/src/display_list/mod.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/mod.rs@@ -4,12 +4,13 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub mod animated_content;+pub mod animated_transform_spaces;pub mod builder;pub mod canvas_2d;pub mod canvas_2d_recorder;pub mod chunks;pub mod commands;-pub mod damage;pub mod depth_sorted_plan;pub mod device_pixels;pub mod effect_clip_plan;@@ -18,11 +19,17 @@ pub mod ffi_bytes;pub mod ids;pub mod layers;pub mod nested_records;+pub mod placement;+pub mod reach;pub mod record_fields;pub mod replay;pub mod storage;pub mod summary;pub mod tape;+#[cfg(test)]+pub(crate) mod test_fixtures;+pub mod tile_keys;+pub mod tiles;pub mod validate;pub mod window;pub mod window_server_placement;diff --git a/Libraries/LibCompositing/Rust/src/display_list/placement.rs b/Libraries/LibCompositing/Rust/src/display_list/placement.rsnew file mode 100644index 00000000000..ea71f1d881c--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/placement.rs@@ -0,0 +1,1350 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Where the content of a display list can be rastered: the raster spaces a visual context tree offers, anchored at+//! the scroll nodes the compositor scrolls and at the sticky boxes within them, the space each visual+//! context is placed in and the clips left to apply when its rasters are composited, and the runs that are placed+//! together because they hold whole group effects.++use crate::display_list::animated_transform_spaces::{+ MAXIMUM_ANIMATED_TRANSFORM_SPACE_COUNT, animated_transform_anchors, raster_scale_of, roots_of_transform_animations,+};+use crate::display_list::commands::{+ ClipMode, ClipNodeIndex, ContextRef, DisplayListCommandRun, EffectNodeIndex, SpatialNodeIndex,+ VISUAL_VIEWPORT_NODE_INDEX,+};+use crate::display_list::effect_clip_plan::EffectClipPlan;+use crate::display_list::effect_geometry::{Extent, FiltersOfEffects, changed_extent_through_filters};+use crate::display_list::reach::Reach;+use crate::visual_context::queries::TreeCullingScratch;+use crate::visual_context::world_transforms::translation_on_whole_device_pixels;+use crate::visual_context::{+ ClipNodeData, CompositorScrollNodeRecord, EffectNodeData, RasterRoot, SpatialData, StickyData, VisualContextTree,+ WorldTransforms,+};+use libgfx_rust::{CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, IntPoint, IntRect, enclosing_int_rect};+use std::collections::HashMap;+use std::hash::{BuildHasher, Hasher};+use std::rc::Rc;++/// The index of a raster space among the spaces of a placement, each after the space it is in.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct RasterSpaceIndex(pub usize);++impl RasterSpaceIndex {+ pub const VIEWPORT: Self = Self(0);+}++const MAXIMUM_SCROLLER_SPACE_COUNT: usize = 7;+// Enough for twenty section headers and a row of sticky table headers.+const MAXIMUM_STICKY_BOX_SPACE_COUNT: usize = 32;+/// The most spaces a placement makes: the viewport's, and one at each anchor.+pub(super) const MAXIMUM_RASTER_SPACE_COUNT: usize =+ 1 + MAXIMUM_SCROLLER_SPACE_COUNT + MAXIMUM_STICKY_BOX_SPACE_COUNT + MAXIMUM_ANIMATED_TRANSFORM_SPACE_COUNT;+/// How far past its bounds antialiasing can show content.+pub(crate) const ANTIALIASING_MARGIN_IN_DEVICE_PIXELS: i32 = 3;+const LARGEST_DEVICE_PIXEL_RATIO_EXTENTS_COVER_PAGES_AT: f32 = 8.0;+// Small enough that a rect twice as wide still fits in an `IntRect`.+pub(crate) const EXTENT_LIMIT_IN_DEVICE_PIXELS: f32 =+ (crate::css_pixels::MAX_INTEGER_VALUE as f32 + 1.0) * LARGEST_DEVICE_PIXEL_RATIO_EXTENTS_COVER_PAGES_AT;++pub(crate) fn extent_limit_rect() -> FloatRect {+ FloatRect::new(+ -EXTENT_LIMIT_IN_DEVICE_PIXELS,+ -EXTENT_LIMIT_IN_DEVICE_PIXELS,+ 2.0 * EXTENT_LIMIT_IN_DEVICE_PIXELS,+ 2.0 * EXTENT_LIMIT_IN_DEVICE_PIXELS,+ )+}++/// What the anchor of a space is, which decides how its translation is rounded and what the dump calls the space.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum RasterSpaceAnchorKind {+ Viewport,+ /// The scroll node that scrolls the viewport, whose content is the document.+ ViewportScroller,+ Scroller,+ /// A sticky box, laid out at `border_box_origin`, which its translation is rounded relative to as world transforms+ /// round it.+ StickyBox {+ border_box_origin: FloatPoint,+ },+ /// A spatial node whose transform the compositor animates, whose content is rastered in its own coordinates times+ /// `raster_scale` and composited through the transform each frame.+ AnimatedTransform {+ raster_scale: f32,+ },+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct RasterSpace {+ pub anchor: SpatialNodeIndex,+ /// Names the space by its anchor's scroll node or sticky box as the page knows it, which outlives the tree and its+ /// indices.+ pub identity: u64,+ pub parent_index: RasterSpaceIndex,+ pub anchor_kind: RasterSpaceAnchorKind,+ /// How far the anchor can translate its content: the negated scroll range of a scroller, the offset range of a+ /// sticky box.+ pub lowest_anchor_translation: FloatPoint,+ pub highest_anchor_translation: FloatPoint,+ /// Where content that moves with the anchor can show, in the space's raster coordinates: a scroller's scrollport+ /// over the whole scroll range, and for a sticky box the extent of the space around it wherever the box is held.+ /// For the viewport's space, the viewport.+ pub extent: IntRect,+}++impl RasterSpace {+ pub(crate) fn of_viewport(viewport_rect: IntRect) -> Self {+ Self {+ anchor: VISUAL_VIEWPORT_NODE_INDEX,+ identity: 0,+ parent_index: RasterSpaceIndex::VIEWPORT,+ anchor_kind: RasterSpaceAnchorKind::Viewport,+ lowest_anchor_translation: FloatPoint::default(),+ highest_anchor_translation: FloatPoint::default(),+ extent: viewport_rect,+ }+ }++ /// For a space whose anchor the compositor animates, the root its rasters map its anchor's content from.+ pub fn raster_root(&self) -> Option<RasterRoot> {+ match self.anchor_kind {+ RasterSpaceAnchorKind::AnimatedTransform { raster_scale } => Some(RasterRoot {+ anchor: self.anchor,+ raster_scale,+ }),+ _ => None,+ }+ }++ pub fn anchor_translation_on_whole_device_pixels(&self, offset: FloatPoint) -> IntPoint {+ let sticky_box_origin = match self.anchor_kind {+ RasterSpaceAnchorKind::StickyBox { border_box_origin } => Some(border_box_origin),+ _ => None,+ };+ let translation = translation_on_whole_device_pixels(offset, sticky_box_origin);+ IntPoint {+ x: translation.x as i32,+ y: translation.y as i32,+ }+ }+}++/// A rect, with rounded corners or not, that rasters of content are clipped to as they are composited, in the raster+/// coordinates of a space whose anchor the content does not move with.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct CompositeClip {+ pub raster_space_index: RasterSpaceIndex,+ pub rect: IntRect,+ pub corner_radii: CornerRadii,+}++impl CompositeClip {+ pub fn is_rounded(&self) -> bool {+ self.corner_radii.has_any_radius()+ }+}++pub(crate) fn space_and_ancestors_below_viewport(+ spaces: &[RasterSpace],+ mut space: RasterSpaceIndex,+) -> impl Iterator<Item = RasterSpaceIndex> + '_ {+ std::iter::from_fn(move || {+ if space == RasterSpaceIndex::VIEWPORT {+ return None;+ }+ let current = space;+ space = spaces[space.0].parent_index;+ Some(current)+ })+}++pub(crate) fn space_is_ancestor_or_self(+ spaces: &[RasterSpace],+ ancestor: RasterSpaceIndex,+ mut space: RasterSpaceIndex,+) -> bool {+ loop {+ if space == ancestor {+ return true;+ }+ if space == RasterSpaceIndex::VIEWPORT {+ return false;+ }+ space = spaces[space.0].parent_index;+ }+}++/// The scroll offsets content of `space` is rastered under: those of the frame, with the anchors of the space and of+/// the spaces it is in at their origin.+pub fn raster_scroll_offsets(+ spaces: &[RasterSpace],+ space: RasterSpaceIndex,+ scroll_offsets: &[FloatPoint],+) -> Vec<FloatPoint> {+ let mut offsets = scroll_offsets.to_vec();+ for space in space_and_ancestors_below_viewport(spaces, space) {+ if let Some(offset) = offsets.get_mut(spaces[space.0].anchor.0 as usize) {+ *offset = FloatPoint::default();+ }+ }+ offsets+}++pub(crate) fn translation_if_only_translates(matrix: &FloatMatrix4x4) -> Option<FloatPoint> {+ if !matrix.is_2d_affine() {+ return None;+ }+ let affine = matrix.extract_2d_affine();+ affine.is_identity_or_translation().then(|| FloatPoint {+ x: affine.e(),+ y: affine.f(),+ })+}++fn node_keeps_whole_pixel_translations_below_it(data: &SpatialData) -> bool {+ match data {+ SpatialData::Scroll(_) | SpatialData::BackfaceVisibility(_) => true,+ SpatialData::Transform(transform) => transform.matrix_including_origin() == FloatMatrix4x4::identity(),+ _ => false,+ }+}++/// A value per spatial node that is worked out of the node and the value of its parent, for each node asked about and+/// the nodes above it, each once, so that questions about many nodes of a deep tree take one walk of each chain. The+/// visual viewport's node has the value given for it. A node whose chain leaves the tree or loops has none.+pub(crate) struct ValuesFoldedDownSpatialChains<T> {+ value_by_spatial_index: Vec<Option<T>>,+ chain_without_values: Vec<SpatialNodeIndex>,+}++impl<T: Copy> ValuesFoldedDownSpatialChains<T> {+ // The table takes its memory at the first question.+ pub(crate) fn new() -> Self {+ Self {+ value_by_spatial_index: Vec::new(),+ chain_without_values: Vec::new(),+ }+ }++ /// The value of `node`, where the value of the viewport's node is `value_of_viewport` and that of any other node+ /// is what `fold` gives for it and the value of its parent. Every question to one table gives the same two.+ pub(crate) fn value_of(+ &mut self,+ tree: &VisualContextTree,+ node: SpatialNodeIndex,+ value_of_viewport: T,+ fold: impl Fn(SpatialNodeIndex, T) -> T,+ ) -> Option<T> {+ if node == VISUAL_VIEWPORT_NODE_INDEX {+ return Some(value_of_viewport);+ }+ if self.value_by_spatial_index.is_empty() {+ self.value_by_spatial_index = vec![None; tree.spatial_nodes.len()];+ }+ let mut node_on_chain = node;+ let mut value = loop {+ let Some(&known_value) = self.value_by_spatial_index.get(node_on_chain.0 as usize) else {+ self.chain_without_values.clear();+ return None;+ };+ if let Some(known_value) = known_value {+ break known_value;+ }+ if node_on_chain == VISUAL_VIEWPORT_NODE_INDEX {+ break value_of_viewport;+ }+ if self.chain_without_values.len() == self.value_by_spatial_index.len() {+ self.chain_without_values.clear();+ return None;+ }+ self.chain_without_values.push(node_on_chain);+ node_on_chain = tree.spatial_nodes[node_on_chain.0 as usize].parent;+ };+ self.value_by_spatial_index[node_on_chain.0 as usize] = Some(value);+ while let Some(node_below) = self.chain_without_values.pop() {+ value = fold(node_below, value);+ self.value_by_spatial_index[node_below.0 as usize] = Some(value);+ }+ Some(value)+ }+}++/// Per spatial node, whether where it lands can change while the list and the tree's structure stay: it is under a+/// sticky box, an anchor scroll shift or a transform the compositor animates.+pub fn spatial_nodes_that_move_on_their_own(tree: &VisualContextTree) -> Vec<bool> {+ spatial_nodes_that_move_on_their_own_relative_to_spaces_at(tree, None)+}++pub(crate) fn spatial_nodes_that_move_on_their_own_relative_to_spaces_at(+ tree: &VisualContextTree,+ anchors: Option<&[SpatialNodeIndex]>,+) -> Vec<bool> {+ let is_anchor = |node: SpatialNodeIndex| anchors.is_some_and(|anchors| anchors.contains(&node));+ let mut roots_of_subtrees_moving_on_their_own: Vec<SpatialNodeIndex> =+ roots_of_transform_animations(tree, |node| !is_anchor(node)).collect();+ if let Some(anchors) = anchors {+ roots_of_subtrees_moving_on_their_own.extend(compositor_scrolled_nodes_without_own_space(tree, anchors));+ }+ roots_of_subtrees_moving_on_their_own.extend(tree.spatial_nodes.iter().enumerate().filter_map(|(index, node)| {+ let node_index = SpatialNodeIndex(index as u32);+ let moves = match node.data {+ SpatialData::Sticky(_) => !is_anchor(node_index),+ SpatialData::AnchorScrollShift(_) => true,+ _ => false,+ };+ moves.then_some(node_index)+ }));+ tree.spatial_nodes_in_subtrees_of(&roots_of_subtrees_moving_on_their_own)+}++/// Per spatial node, whether placing a list among the spaces at `anchors` leaves out the node's scroll offset: the+/// node is one of the anchors, the compositor scrolls the node, or the node moves on its own in those spaces. What+/// moves with such a node is placed in a space that follows it, or wherever the node can take it.+pub fn spatial_nodes_whose_scroll_offset_placement_leaves_out(+ tree: &VisualContextTree,+ anchors: &[SpatialNodeIndex],+) -> Vec<bool> {+ spatial_nodes_whose_scroll_offset_placement_leaves_out_of_nodes_moving(+ tree,+ anchors,+ spatial_nodes_that_move_on_their_own_relative_to_spaces_at(tree, Some(anchors)),+ )+}++/// As `spatial_nodes_whose_scroll_offset_placement_leaves_out`, from whether each spatial node moves on its own+/// relative to the spaces at `anchors`.+pub(crate) fn spatial_nodes_whose_scroll_offset_placement_leaves_out_of_nodes_moving(+ tree: &VisualContextTree,+ anchors: &[SpatialNodeIndex],+ spatial_node_moves_on_its_own: Vec<bool>,+) -> Vec<bool> {+ let mut leaves_out_by_node = spatial_node_moves_on_its_own;+ let nodes_the_compositor_scrolls = tree+ .compositor_scroll_table()+ .nodes+ .iter()+ .map(|record| record.scroll_node_index);+ // The compositor also moves a sticky box at an anchor as it scrolls the scroller of the box.+ for node in nodes_the_compositor_scrolls.chain(anchors.iter().copied()) {+ if let Some(leaves_out) = leaves_out_by_node.get_mut(node.0 as usize) {+ *leaves_out = true;+ }+ }+ leaves_out_by_node+}++fn compositor_scrolled_nodes_without_own_space<'a>(+ tree: &'a VisualContextTree,+ scrollers_with_spaces: &'a [SpatialNodeIndex],+) -> impl Iterator<Item = SpatialNodeIndex> + 'a {+ tree.compositor_scroll_table()+ .nodes+ .iter()+ .map(|record| record.scroll_node_index)+ .filter(move |node| *node != VISUAL_VIEWPORT_NODE_INDEX && !scrollers_with_spaces.contains(node))+}++fn visual_viewport_only_translates(tree: &VisualContextTree) -> bool {+ let Some(SpatialData::Transform(transform)) = tree.spatial_nodes.first().map(|node| &node.data) else {+ return false;+ };+ translation_if_only_translates(&transform.matrix_including_origin()).is_some()+}++// How deep below the viewport each node is, where nothing between it and the viewport transforms or moves on its own,+// so that content of the node lands on whole device pixels wherever it is scrolled to.+struct DepthsBelowViewportOnWholeDevicePixels<'a> {+ spatial_node_moves_on_its_own: &'a [bool],+ // Per node, how many nodes from it up to the viewport there are, where none of them breaks whole pixels.+ node_count_of_chain_on_whole_device_pixels: ValuesFoldedDownSpatialChains<Option<usize>>,+}++impl<'a> DepthsBelowViewportOnWholeDevicePixels<'a> {+ fn new(spatial_node_moves_on_its_own: &'a [bool]) -> Self {+ Self {+ spatial_node_moves_on_its_own,+ node_count_of_chain_on_whole_device_pixels: ValuesFoldedDownSpatialChains::new(),+ }+ }++ fn depth_of(&mut self, tree: &VisualContextTree, node: SpatialNodeIndex) -> Option<usize> {+ let parent = tree.spatial_nodes.get(node.0 as usize)?.parent;+ let spatial_node_moves_on_its_own = self.spatial_node_moves_on_its_own;+ let node_count_of_chain_from_parent = self.node_count_of_chain_on_whole_device_pixels.value_of(+ tree,+ parent,+ Some(0),+ |node, node_count_of_chain_from_parent| {+ let node_breaks_whole_pixels =+ !node_keeps_whole_pixel_translations_below_it(&tree.spatial_nodes[node.0 as usize].data)+ || spatial_node_moves_on_its_own[node.0 as usize];+ node_count_of_chain_from_parent+ .filter(|_| !node_breaks_whole_pixels)+ .map(|count| count + 1)+ },+ )??;+ Some(node_count_of_chain_from_parent + 1)+ }+}++fn shallowest_first_up_to(+ mut depths_and_nodes: Vec<(usize, SpatialNodeIndex)>,+ maximum_count: usize,+) -> Vec<SpatialNodeIndex> {+ depths_and_nodes.sort_by_key(|&(depth, node)| (depth, node.0));+ depths_and_nodes.truncate(maximum_count);+ depths_and_nodes.into_iter().map(|(_, node)| node).collect()+}++fn spatial_nodes_moving_on_their_own_or_under_scrollers_without_space(+ tree: &VisualContextTree,+ spatial_nodes_that_move_on_their_own: &[bool],+ scrollers_with_spaces: &[SpatialNodeIndex],+) -> Vec<bool> {+ let scrolled_nodes_without_own_space: Vec<SpatialNodeIndex> =+ compositor_scrolled_nodes_without_own_space(tree, scrollers_with_spaces).collect();+ if scrolled_nodes_without_own_space.is_empty() {+ return spatial_nodes_that_move_on_their_own.to_vec();+ }+ spatial_nodes_that_move_on_their_own+ .iter()+ .zip(tree.spatial_nodes_in_subtrees_of(&scrolled_nodes_without_own_space))+ .map(|(&moves_on_its_own, under_scroller_without_own_space)| {+ moves_on_its_own || under_scroller_without_own_space+ })+ .collect()+}++fn sticky_boxes_that_can_be_held_with_depths(+ tree: &VisualContextTree,+ spatial_nodes_that_move_on_their_own: &[bool],+ scrollers_with_spaces: &[SpatialNodeIndex],+) -> Vec<(usize, SpatialNodeIndex)> {+ if !tree+ .spatial_nodes+ .iter()+ .any(|node| matches!(node.data, SpatialData::Sticky(_)))+ {+ return Vec::new();+ }+ let spatial_node_moves_on_its_own = spatial_nodes_moving_on_their_own_or_under_scrollers_without_space(+ tree,+ spatial_nodes_that_move_on_their_own,+ scrollers_with_spaces,+ );+ let mut depths_below_viewport = DepthsBelowViewportOnWholeDevicePixels::new(&spatial_node_moves_on_its_own);+ const _: () = assert!(MAXIMUM_SCROLLER_SPACE_COUNT <= u64::BITS as usize);+ let mut scrollers_with_spaces_at_or_above = ValuesFoldedDownSpatialChains::<u64>::new();+ let bit_of_scroller_with_space = |node: SpatialNodeIndex| {+ scrollers_with_spaces+ .iter()+ .position(|&scroller| scroller == node)+ .map_or(0, |position| 1u64 << position)+ };+ tree.spatial_nodes+ .iter()+ .enumerate()+ .filter_map(|(index, node)| {+ let SpatialData::Sticky(sticky) = &node.data else {+ return None;+ };+ let node_index = SpatialNodeIndex(index as u32);+ if !sticky.non_scrolling_scroll_container.is_invalid() || !scrollers_with_spaces.contains(&sticky.scroller)+ {+ return None;+ }+ let depth = depths_below_viewport.depth_of(tree, node_index)?;+ let moves_with_its_scroller = scrollers_with_spaces_at_or_above+ .value_of(tree, node.parent, 0, |node, scrollers_above| {+ scrollers_above | bit_of_scroller_with_space(node)+ })+ .is_some_and(|scrollers| scrollers & bit_of_scroller_with_space(sticky.scroller) != 0);+ let (lowest, highest) = sticky.offset_range_without_sticky_ancestors();+ let can_be_held = lowest.x < 0.0 || lowest.y < 0.0 || highest.x > 0.0 || highest.y > 0.0;+ (moves_with_its_scroller && can_be_held).then_some((depth, node_index))+ })+ .collect()+}++struct ScrollerThatCanHaveSpace {+ depth: usize,+ node: SpatialNodeIndex,+ can_be_wheel_scrolled: bool,+}++// A candidate that gets a space takes spaces for the candidates around it too, so it gets one only where those fit.+fn scrollers_to_give_spaces_parents_first(+ tree: &VisualContextTree,+ mut candidates: Vec<ScrollerThatCanHaveSpace>,+ maximum_count: usize,+) -> Vec<SpatialNodeIndex> {+ // Zero for a node that is not a candidate, as every candidate is at least one deep.+ let mut candidate_depth_by_spatial_index = vec![0usize; tree.spatial_nodes.len()];+ for candidate in &candidates {+ candidate_depth_by_spatial_index[candidate.node.0 as usize] = candidate.depth;+ }+ candidates.sort_by_key(|candidate| (!candidate.can_be_wheel_scrolled, candidate.depth, candidate.node.0));+ let mut nearest_candidate_at_or_above = ValuesFoldedDownSpatialChains::<Option<SpatialNodeIndex>>::new();+ let mut is_chosen = vec![false; tree.spatial_nodes.len()];+ let mut chosen_depths_and_nodes: Vec<(usize, SpatialNodeIndex)> = Vec::new();+ let mut candidate_and_unchosen_candidate_ancestors = Vec::new();+ for candidate in &candidates {+ if chosen_depths_and_nodes.len() == maximum_count {+ break;+ }+ if is_chosen[candidate.node.0 as usize] {+ continue;+ }+ candidate_and_unchosen_candidate_ancestors.clear();+ let mut candidate_on_chain = Some(candidate.node);+ let mut fits = true;+ while let Some(node) = candidate_on_chain {+ let index = node.0 as usize;+ if !is_chosen[index] {+ candidate_and_unchosen_candidate_ancestors.push((candidate_depth_by_spatial_index[index], node));+ if chosen_depths_and_nodes.len() + candidate_and_unchosen_candidate_ancestors.len() > maximum_count {+ fits = false;+ break;+ }+ }+ candidate_on_chain = nearest_candidate_at_or_above+ .value_of(+ tree,+ tree.spatial_nodes[index].parent,+ None,+ |node, nearest_candidate_above| {+ if candidate_depth_by_spatial_index[node.0 as usize] != 0 {+ Some(node)+ } else {+ nearest_candidate_above+ }+ },+ )+ .flatten();+ }+ if !fits {+ continue;+ }+ for &(_, node) in &candidate_and_unchosen_candidate_ancestors {+ is_chosen[node.0 as usize] = true;+ }+ chosen_depths_and_nodes.extend_from_slice(&candidate_and_unchosen_candidate_ancestors);+ }+ chosen_depths_and_nodes.sort_by_key(|&(depth, node)| (depth, node.0));+ chosen_depths_and_nodes.into_iter().map(|(_, node)| node).collect()+}++/// The nodes that layers can be rastered at, parents first, which the tree alone decides. First the scroll nodes the+/// compositor scrolls, over a scroll range, whose content lands on whole device pixels of the viewport wherever they+/// are scrolled to, since nothing between them and the viewport transforms, or can be animated to. Those the user can+/// scroll with a wheel go ahead of the rest, with the scrollers they are nested in. Then the sticky boxes within those+/// scrollers that can be held at a sticky edge, held or not, so that a box that starts or stops being held moves its+/// space rather than changing the spaces. Each kind goes shallowest first and then in tree order up to as many as it+/// may have.+pub fn raster_space_anchors(+ tree: &VisualContextTree,+ spatial_nodes_that_move_on_their_own: &[bool],+) -> Vec<SpatialNodeIndex> {+ if !visual_viewport_only_translates(tree) {+ return Vec::new();+ }+ let mut depths_below_viewport = DepthsBelowViewportOnWholeDevicePixels::new(spatial_nodes_that_move_on_their_own);+ let candidate_scrollers: Vec<ScrollerThatCanHaveSpace> = tree+ .compositor_scroll_table()+ .nodes+ .iter()+ .filter_map(|record| {+ let node = record.scroll_node_index;+ if node == VISUAL_VIEWPORT_NODE_INDEX || record.min_scroll_offset == record.max_scroll_offset {+ return None;+ }+ if !matches!(tree.spatial_nodes.get(node.0 as usize)?.data, SpatialData::Scroll(_)) {+ return None;+ }+ Some(ScrollerThatCanHaveSpace {+ depth: depths_below_viewport.depth_of(tree, node)?,+ node,+ can_be_wheel_scrolled: record.can_be_wheel_scrolled_horizontally+ || record.can_be_wheel_scrolled_vertically,+ })+ })+ .collect();+ let mut anchors = scrollers_to_give_spaces_parents_first(tree, candidate_scrollers, MAXIMUM_SCROLLER_SPACE_COUNT);+ let holdable_sticky_boxes =+ sticky_boxes_that_can_be_held_with_depths(tree, spatial_nodes_that_move_on_their_own, &anchors);+ anchors.extend(shallowest_first_up_to(+ holdable_sticky_boxes,+ MAXIMUM_STICKY_BOX_SPACE_COUNT,+ ));+ anchors.extend(animated_transform_anchors(tree));+ anchors+}++pub(crate) fn compositor_scroll_record_of(+ tree: &VisualContextTree,+ node: SpatialNodeIndex,+) -> Option<&CompositorScrollNodeRecord> {+ tree.compositor_scroll_table()+ .nodes+ .iter()+ .find(|record| record.scroll_node_index == node)+}++const SCROLLER_ANCHOR_IDENTITY_SEED: u64 = 0x7261_7374_6572_5f73;+const ANIMATED_TRANSFORM_ANCHOR_IDENTITY_SEED: u64 = 0x616e_696d_6174_6564;++// A node index names the node for as long as the tree keeps it, which outlives lists and animation samples.+fn identity_of_animated_transform_anchor(anchor: SpatialNodeIndex, raster_scale: f32) -> u64 {+ let mut hasher = foldhash::fast::FixedState::with_seed(ANIMATED_TRANSFORM_ANCHOR_IDENTITY_SEED).build_hasher();+ hasher.write_u32(anchor.0);+ hasher.write_u32(raster_scale.to_bits());+ hasher.finish()+}+const STICKY_BOX_ANCHOR_IDENTITY_SEED: u64 = 0x7374_6963_6b79_5f62;++fn identity_of_scroller_anchor(record: &CompositorScrollNodeRecord) -> u64 {+ let mut hasher = foldhash::fast::FixedState::with_seed(SCROLLER_ANCHOR_IDENTITY_SEED).build_hasher();+ hasher.write_i64(record.scrollable_node_id.0);+ hasher.write_u8(record.scroll_node_kind as u8);+ hasher.write_u8(record.pseudo_element_type);+ let page_leaves_node_unnamed = record.scrollable_node_id.0 == 0;+ if page_leaves_node_unnamed {+ hasher.write_u32(record.scroll_node_index.0);+ }+ hasher.finish() | 1+}++fn identity_of_sticky_box_anchor(sticky: &StickyData, node: SpatialNodeIndex) -> u64 {+ let mut hasher = foldhash::fast::FixedState::with_seed(STICKY_BOX_ANCHOR_IDENTITY_SEED).build_hasher();+ hasher.write_i64(sticky.box_node_id.0);+ hasher.write_u8(sticky.box_pseudo_element_type);+ let page_leaves_box_unnamed = sticky.box_node_id.0 == 0;+ if page_leaves_box_unnamed {+ hasher.write_u32(node.0);+ }+ hasher.finish() | 1+}++pub(crate) fn enclosing_int_rect_within_extent_limit(rect: FloatRect) -> IntRect {+ enclosing_int_rect(rect.intersected(extent_limit_rect()))+}++// The space anchored at `anchor` inside the space at `parent`, unless the anchor is a scroller the compositor does not+// scroll.+fn space_at_anchor(+ tree: &VisualContextTree,+ anchor: SpatialNodeIndex,+ parent: RasterSpaceIndex,+) -> Option<RasterSpace> {+ if let SpatialData::Transform(_) = &tree.spatial_nodes[anchor.0 as usize].data {+ let raster_scale = raster_scale_of(tree, anchor);+ return Some(RasterSpace {+ anchor,+ identity: identity_of_animated_transform_anchor(anchor, raster_scale),+ parent_index: parent,+ anchor_kind: RasterSpaceAnchorKind::AnimatedTransform { raster_scale },+ lowest_anchor_translation: FloatPoint::default(),+ highest_anchor_translation: FloatPoint::default(),+ extent: IntRect::default(),+ });+ }+ if let SpatialData::Sticky(sticky) = &tree.spatial_nodes[anchor.0 as usize].data {+ let (lowest_anchor_translation, highest_anchor_translation) = sticky.offset_range_without_sticky_ancestors();+ return Some(RasterSpace {+ anchor,+ identity: identity_of_sticky_box_anchor(sticky, anchor),+ parent_index: parent,+ anchor_kind: RasterSpaceAnchorKind::StickyBox {+ border_box_origin: sticky.border_box_origin,+ },+ lowest_anchor_translation,+ highest_anchor_translation,+ extent: IntRect::default(),+ });+ }+ let record = compositor_scroll_record_of(tree, anchor)?;+ let mut lowest_anchor_translation = FloatPoint {+ x: -record.max_scroll_offset.x,+ y: -record.max_scroll_offset.y,+ };+ let mut highest_anchor_translation = FloatPoint {+ x: -record.min_scroll_offset.x,+ y: -record.min_scroll_offset.y,+ };+ if record.shows_overscroll_effect_horizontally {+ lowest_anchor_translation.x -= record.scrollport_rect.width as f32;+ highest_anchor_translation.x += record.scrollport_rect.width as f32;+ }+ if record.shows_overscroll_effect_vertically {+ lowest_anchor_translation.y -= record.scrollport_rect.height as f32;+ highest_anchor_translation.y += record.scrollport_rect.height as f32;+ }+ Some(RasterSpace {+ anchor,+ identity: identity_of_scroller_anchor(record),+ parent_index: parent,+ anchor_kind: if record.is_viewport {+ RasterSpaceAnchorKind::ViewportScroller+ } else {+ RasterSpaceAnchorKind::Scroller+ },+ lowest_anchor_translation,+ highest_anchor_translation,+ extent: IntRect::default(),+ })+}++/// The raster spaces of a tree at a set of anchors, and the deepest of them that each spatial node moves with.+#[derive(Clone, Debug)]+pub struct RasterSpaces {+ spaces: Vec<RasterSpace>,+ deepest_space_of_spatial_node: Vec<RasterSpaceIndex>,+ clips_left_to_composite_by_space: Vec<std::cell::OnceCell<Rc<[bool]>>>,+}++impl RasterSpaces {+ /// The spaces at `anchors`, without what `of_spaces` works out of every node of the tree for them.+ pub fn spaces_at_anchors(+ tree: &VisualContextTree,+ anchors: &[SpatialNodeIndex],+ viewport_rect: IntRect,+ ) -> Vec<RasterSpace> {+ let mut spaces = vec![RasterSpace::of_viewport(viewport_rect)];+ let mut nearest_anchor_at_or_above = ValuesFoldedDownSpatialChains::<Option<SpatialNodeIndex>>::new();+ for &anchor in anchors {+ // The space is in the space of the nearest anchor above it that has a space already.+ let mut parent = RasterSpaceIndex::VIEWPORT;+ let mut ancestor = tree.spatial_nodes[anchor.0 as usize].parent;+ while ancestor != VISUAL_VIEWPORT_NODE_INDEX {+ let Some(nearest_anchor) = nearest_anchor_at_or_above+ .value_of(tree, ancestor, None, |node, nearest_anchor_above| {+ if anchors.contains(&node) {+ Some(node)+ } else {+ nearest_anchor_above+ }+ })+ .flatten()+ else {+ break;+ };+ if let Some(space) = spaces.iter().position(|space| space.anchor == nearest_anchor) {+ parent = RasterSpaceIndex(space);+ break;+ }+ ancestor = tree.spatial_nodes[nearest_anchor.0 as usize].parent;+ }+ let Some(space) = space_at_anchor(tree, anchor, parent) else {+ continue;+ };+ spaces.push(space);+ }+ spaces+ }++ /// The given spaces, which a tree offers, and the deepest of them each spatial node of the tree moves with.+ pub fn of_spaces(tree: &VisualContextTree, spaces: Vec<RasterSpace>) -> Self {+ let mut first_space_anchored_at_spatial_node: Vec<Option<RasterSpaceIndex>> =+ vec![None; tree.spatial_nodes.len()];+ for (space_index, space) in spaces.iter().enumerate().skip(1) {+ if let Some(first_space) = first_space_anchored_at_spatial_node.get_mut(space.anchor.0 as usize) {+ first_space.get_or_insert(RasterSpaceIndex(space_index));+ }+ }+ let mut deepest_space_of_spatial_node = vec![RasterSpaceIndex::VIEWPORT; tree.spatial_nodes.len()];+ tree.visit_spatial_nodes_parents_first(|index| {+ if index == VISUAL_VIEWPORT_NODE_INDEX.0 as usize {+ return;+ }+ let node = &tree.spatial_nodes[index];+ deepest_space_of_spatial_node[index] =+ if let Some(space_anchored_at_node) = first_space_anchored_at_spatial_node[index] {+ space_anchored_at_node+ } else if matches!(node.data, SpatialData::AnchorScrollShift(_)) {+ RasterSpaceIndex::VIEWPORT+ } else {+ deepest_space_of_spatial_node[node.parent.0 as usize]+ };+ });+ Self {+ clips_left_to_composite_by_space: vec![std::cell::OnceCell::new(); spaces.len()],+ spaces,+ deepest_space_of_spatial_node,+ }+ }++ pub fn spaces(&self) -> &[RasterSpace] {+ &self.spaces+ }++ pub fn len(&self) -> usize {+ self.spaces.len()+ }++ pub fn is_empty(&self) -> bool {+ self.spaces.is_empty()+ }++ pub fn deepest_space_of(&self, spatial: SpatialNodeIndex) -> RasterSpaceIndex {+ self.deepest_space_of_spatial_node+ .get(spatial.0 as usize)+ .copied()+ .unwrap_or(RasterSpaceIndex::VIEWPORT)+ }++ /// Per clip node, whether rasters of `space` leave it to be applied as they are composited, since the clip does+ /// not move with the space. Worked out once per space, as every tree the spaces serve has the same nodes.+ pub fn clips_left_to_composite(&self, space: RasterSpaceIndex, tree: &VisualContextTree) -> Rc<[bool]> {+ self.clips_left_to_composite_by_space[space.0]+ .get_or_init(|| {+ tree.clip_nodes+ .iter()+ .map(|node| {+ self.deepest_space_of_spatial_node+ .get(node.spatial.0 as usize)+ .is_none_or(|&deepest| !space_is_ancestor_or_self(&self.spaces, space, deepest))+ })+ .collect()+ })+ .clone()+ }+}++fn bounds_of_projected_rect_if_corners_in_front_of_eye(matrix: FloatMatrix4x4, rect: FloatRect) -> Option<FloatRect> {+ const SMALLEST_W_IN_FRONT_OF_EYE: f32 = 0.00001;+ let corners = [+ (rect.x, rect.y),+ (rect.right(), rect.y),+ (rect.x, rect.bottom()),+ (rect.right(), rect.bottom()),+ ]+ .map(|(x, y)| matrix.map_vector4([x, y, 0.0, 1.0]));+ if corners.iter().any(|corner| corner[3] <= SMALLEST_W_IN_FRONT_OF_EYE) {+ return None;+ }+ let xs = corners.map(|corner| corner[0] / corner[3]);+ let ys = corners.map(|corner| corner[1] / corner[3]);+ let (left, right) = (+ xs.into_iter().fold(f32::INFINITY, f32::min),+ xs.into_iter().fold(f32::NEG_INFINITY, f32::max),+ );+ let (top, bottom) = (+ ys.into_iter().fold(f32::INFINITY, f32::min),+ ys.into_iter().fold(f32::NEG_INFINITY, f32::max),+ );+ Some(FloatRect::new(left, top, right - left, bottom - top))+}++pub(crate) fn is_finite_rect(rect: FloatRect) -> bool {+ rect.x.is_finite() && rect.y.is_finite() && rect.width.is_finite() && rect.height.is_finite()+}++/// What the filters and clips of a list drawn under a tree do to where its content can show.+#[derive(Clone, Copy)]+pub struct FiltersAndClipsOfList<'a> {+ pub tree: &'a VisualContextTree,+ /// The filters of the whole effect chain of each effect: of every sample of the animations of the tree, as placing+ /// follows them, or those the tree holds, as keying the tiles of a frame follows them.+ pub filters: &'a FiltersOfEffects,+ pub effect_clips: &'a EffectClipPlan,+}++impl FiltersAndClipsOfList<'_> {+ /// The clip that bounds how far the filters that content of `context` is drawn through spread it: the clip outside+ /// every such filter, or the clip of the context where no filter spreads it.+ pub(crate) fn clip_bounding_filter_spread(&self, context: ContextRef) -> ClipNodeIndex {+ clip_bounding_spread_of_filters(self.filters, self.effect_clips, context)+ }+}++fn clip_bounding_spread_of_filters(+ filters: &FiltersOfEffects,+ effect_clips: &EffectClipPlan,+ context: ContextRef,+) -> ClipNodeIndex {+ filters+ .effect_bounding_spread_of(context.effect)+ .map_or(context.clip, |effect| effect_clips.output_clip(effect))+}++/// What `bounds_by_clip` holds for `clip`, or none for no clip.+pub(crate) fn chain_bounds_of_clip(clip: ClipNodeIndex, bounds_by_clip: &[Option<FloatRect>]) -> Option<FloatRect> {+ if clip.is_none() {+ None+ } else {+ bounds_by_clip[clip.0 as usize]+ }+}++pub(crate) fn antialiased_reach_in_device_pixels(bounds: Option<FloatRect>) -> Reach<IntRect> {+ let Some(bounds) = bounds.filter(|bounds| is_finite_rect(*bounds)) else {+ return Reach::Anywhere;+ };+ let bounds = bounds.intersected(extent_limit_rect());+ if bounds.is_empty() {+ return Reach::Nothing;+ }+ let margin = ANTIALIASING_MARGIN_IN_DEVICE_PIXELS;+ Reach::Within(enclosing_int_rect(bounds).inflated_edges(margin, margin, margin, margin))+}++/// What the geometries of every space of a tree share: the order its spatial nodes are filled in, and what it culls.+pub struct WhatEverySpaceOfTreeShares {+ spatial_dependency_order: Vec<u32>,+ culling: TreeCullingScratch,+}++impl WhatEverySpaceOfTreeShares {+ pub fn of(tree: &VisualContextTree) -> Rc<Self> {+ let mut culling = TreeCullingScratch::default();+ tree.fill_culling_scratch(&mut culling);+ Rc::new(Self {+ spatial_dependency_order: tree.spatial_dependency_order(),+ culling,+ })+ }+}++/// Where the content of one raster space lands in the space's raster coordinates under the scroll offsets of a frame:+/// the transforms of the tree's spatial nodes with the anchors of the space's chain at their origin, what the tree+/// culls, and the bounds of its clip chains.+pub struct RasterSpaceGeometry {+ pub raster_scroll_offsets: Vec<FloatPoint>,+ pub world: Rc<WorldTransforms>,+ what_every_space_of_tree_shares: Rc<WhatEverySpaceOfTreeShares>,+ /// Empty for the viewport's space, which applies every clip.+ pub clips_left_to_composite: Rc<[bool]>,+ rastered_affine_clip_chain_bounds_by_clip: Vec<Option<FloatRect>>,+ pub(crate) rastered_affine_own_clip_bounds_by_clip: Vec<Option<FloatRect>>,+}++impl RasterSpaceGeometry {+ /// `viewport_to_raster_transform` maps the device pixels of the viewport into those of the raster. It is the+ /// identity wherever there is more than one space.+ pub fn new(+ tree: &VisualContextTree,+ spaces: &RasterSpaces,+ space: RasterSpaceIndex,+ scroll_offsets: &[FloatPoint],+ viewport_to_raster_transform: FloatMatrix4x4,+ what_every_space_of_tree_shares: &Rc<WhatEverySpaceOfTreeShares>,+ ) -> Self {+ debug_assert!(viewport_to_raster_transform == FloatMatrix4x4::identity() || spaces.len() == 1);+ let raster_scroll_offsets = raster_scroll_offsets(spaces.spaces(), space, scroll_offsets);+ let mut world = WorldTransforms::default();+ world.fill(+ tree,+ &what_every_space_of_tree_shares.spatial_dependency_order,+ &raster_scroll_offsets,+ Some(viewport_to_raster_transform),+ spaces.spaces()[space.0].raster_root(),+ );+ Self::with_world(+ tree,+ spaces,+ space,+ raster_scroll_offsets,+ Rc::new(world),+ what_every_space_of_tree_shares,+ )+ }++ /// As `new`, with the world transforms that `new` fills for the space under `raster_scroll_offsets`.+ pub(crate) fn with_world(+ tree: &VisualContextTree,+ spaces: &RasterSpaces,+ space: RasterSpaceIndex,+ raster_scroll_offsets: Vec<FloatPoint>,+ world: Rc<WorldTransforms>,+ what_every_space_of_tree_shares: &Rc<WhatEverySpaceOfTreeShares>,+ ) -> Self {+ let clips_left_to_composite = if space == RasterSpaceIndex::VIEWPORT {+ Rc::default()+ } else {+ spaces.clips_left_to_composite(space, tree)+ };+ let mut rastered_affine_clip_chain_bounds_by_clip: Vec<Option<FloatRect>> = vec![None; tree.clip_nodes.len()];+ let mut rastered_affine_own_clip_bounds_by_clip: Vec<Option<FloatRect>> = vec![None; tree.clip_nodes.len()];+ tree.visit_clip_nodes_parents_first(|index| {+ let node = &tree.clip_nodes[index];+ let own_clip_rect = match &node.data {+ ClipNodeData::Rect(data) if data.mode == ClipMode::Intersect => Some(data.rect),+ ClipNodeData::Path(path) => Some(path.bounding_rect.to_float()),+ _ => None,+ };+ let left_to_composite = clips_left_to_composite.get(index).copied().unwrap_or(false);+ let own_bounds_if_rastered_affinely = own_clip_rect+ .filter(|_| !left_to_composite && world.draw_matrix(node.spatial).is_2d_affine())+ .map(|rect| world.map_rect_to_root(node.spatial, rect))+ .filter(|rect| is_finite_rect(*rect));+ rastered_affine_own_clip_bounds_by_clip[index] = own_bounds_if_rastered_affinely;+ rastered_affine_clip_chain_bounds_by_clip[index] = intersect_bounds(+ own_bounds_if_rastered_affinely,+ chain_bounds_of_clip(node.parent, &rastered_affine_clip_chain_bounds_by_clip),+ );+ });+ Self {+ raster_scroll_offsets,+ world,+ what_every_space_of_tree_shares: what_every_space_of_tree_shares.clone(),+ clips_left_to_composite,+ rastered_affine_clip_chain_bounds_by_clip,+ rastered_affine_own_clip_bounds_by_clip,+ }+ }++ pub fn clip_is_left_to_composite(&self, clip: ClipNodeIndex) -> bool {+ self.clips_left_to_composite+ .get(clip.0 as usize)+ .copied()+ .unwrap_or(false)+ }++ fn shows_nothing_of(&self, drawn_within: FloatRect, context: ContextRef) -> bool {+ drawn_within.is_empty()+ || self+ .what_every_space_of_tree_shares+ .culling+ .context_culls_everything(context)+ || self.world.backface_culled[context.spatial.0 as usize]+ }++ /// Where content of `context` can show in the space's raster coordinates, antialiased: drawn within `drawn_within`+ /// as the frame places it, spread by the filters it is drawn through, within the clips that rasters of the space+ /// apply. Placing a list asks this of the ink of its runs, and keying tiles of the records in them, so what a+ /// record reaches in a frame is within what its run reaches, as far as the space's extent shows either.+ pub fn reach_of_content(+ &self,+ list: &FiltersAndClipsOfList<'_>,+ drawn_within: FloatRect,+ context: ContextRef,+ ) -> Reach<IntRect> {+ if self.shows_nothing_of(drawn_within, context) {+ return Reach::Nothing;+ }+ let (space_of_extent, extent) = changed_extent_through_filters(+ list.tree,+ list.filters,+ context.spatial,+ drawn_within,+ context.effect,+ &self.world,+ );+ let Some(bounds) = self.bounds_where_extent_lands(space_of_extent, extent, context.spatial) else {+ return Reach::Nothing;+ };+ antialiased_reach_in_device_pixels(intersect_bounds(+ bounds,+ chain_bounds_of_clip(+ list.clip_bounding_filter_spread(context),+ &self.rastered_affine_clip_chain_bounds_by_clip,+ ),+ ))+ }++ /// As `reach_of_content`, for content a raster draws inside `composited_effect`, the innermost effect the compositor+ /// composites at or above the effect of `context`, which it leaves out with the effects around it and the clips the+ /// effect is entered within: through the filters inside the effect, within the clips inside it, and within as far+ /// past the clips it is entered within as the filters left out read, by `read_reach_of_filters_left_out` where that+ /// is known. `bounds_of_rastered_clips` gives what `rastered_bounds_of_clips_from_up_to` gives, which a caller can+ /// keep for every content of one context.+ #[allow(clippy::too_many_arguments)]+ pub fn reach_of_content_inside_composited_effect(+ &self,+ list: &FiltersAndClipsOfList<'_>,+ filters_inside_composited_effects: &FiltersOfEffects,+ drawn_within: FloatRect,+ context: ContextRef,+ composited_effect: EffectNodeIndex,+ read_reach_of_filters_left_out: Option<i32>,+ bounds_of_rastered_clips: impl FnOnce(ClipNodeIndex, ClipNodeIndex) -> Option<FloatRect>,+ ) -> Reach<IntRect> {+ if self.shows_nothing_of(drawn_within, context) {+ return Reach::Nothing;+ }+ let (space_of_extent, extent) = changed_extent_through_filters(+ list.tree,+ filters_inside_composited_effects,+ context.spatial,+ drawn_within,+ context.effect,+ &self.world,+ );+ let Some(bounds) = self.bounds_where_extent_lands(space_of_extent, extent, context.spatial) else {+ return Reach::Nothing;+ };+ let clip_bounding_filter_spread =+ clip_bounding_spread_of_filters(filters_inside_composited_effects, list.effect_clips, context);+ let clip_composited_effect_is_entered_within = list+ .effect_clips+ .output_clip_if_participating(composited_effect)+ .unwrap_or(ClipNodeIndex::NONE);+ let bounds_of_clips_inside_composited_effect =+ bounds_of_rastered_clips(clip_bounding_filter_spread, clip_composited_effect_is_entered_within);+ let clips_entered_within_widened_by_what_filters_left_out_read =+ read_reach_of_filters_left_out.and_then(|read_reach| {+ let bounds = if clip_composited_effect_is_entered_within.is_none() {+ None+ } else {+ self.rastered_affine_clip_chain_bounds_by_clip[clip_composited_effect_is_entered_within.0 as usize]+ }?;+ let twice_read_reach = 2.0 * read_reach as f32;+ Some(bounds.inflated(twice_read_reach, twice_read_reach))+ });+ antialiased_reach_in_device_pixels(intersect_bounds(+ intersect_bounds(bounds, bounds_of_clips_inside_composited_effect),+ clips_entered_within_widened_by_what_filters_left_out_read,+ ))+ }++ /// The bounds, rastered in the space, of the clips from `first_clip` up to the clip before `end_clip`, using what+ /// `bounds_by_first_and_end_clip` holds, and keeping there what it works out, so that a walk of the clips of many+ /// contents passes each clip once for each end clip.+ pub fn rastered_bounds_of_clips_from_up_to(+ &self,+ tree: &VisualContextTree,+ first_clip: ClipNodeIndex,+ end_clip: ClipNodeIndex,+ bounds_by_first_and_end_clip: &mut HashMap<(ClipNodeIndex, ClipNodeIndex), Option<FloatRect>>,+ clips_without_bounds: &mut Vec<ClipNodeIndex>,+ ) -> Option<FloatRect> {+ clips_without_bounds.clear();+ let mut clip = first_clip;+ let mut bounds = loop {+ if clip.is_none() || clip == end_clip {+ break None;+ }+ if let Some(&bounds) = bounds_by_first_and_end_clip.get(&(clip, end_clip)) {+ break bounds;+ }+ clips_without_bounds.push(clip);+ clip = tree.clip_nodes[clip.0 as usize].parent;+ };+ while let Some(clip) = clips_without_bounds.pop() {+ bounds = intersect_bounds(self.rastered_affine_own_clip_bounds_by_clip[clip.0 as usize], bounds);+ bounds_by_first_and_end_clip.insert((clip, end_clip), bounds);+ }+ bounds+ }++ // None where the extent lands nowhere, Some(None) where nothing bounds where it lands.+ fn bounds_where_extent_lands(+ &self,+ space_of_extent: SpatialNodeIndex,+ extent: Extent,+ context_spatial: SpatialNodeIndex,+ ) -> Option<Option<FloatRect>> {+ let maps_affinely = self.world.draw_matrix(space_of_extent).is_2d_affine()+ && self.world.draw_matrix(context_spatial).is_2d_affine();+ Some(match extent {+ Extent::Nothing => return None,+ Extent::Within(rect) if maps_affinely => {+ Some(self.world.map_rect_to_root(space_of_extent, rect)).filter(|rect| is_finite_rect(*rect))+ }+ Extent::Within(rect) if space_of_extent == context_spatial => {+ bounds_of_projected_rect_if_corners_in_front_of_eye(self.world.draw_matrix(space_of_extent), rect)+ .filter(|rect| is_finite_rect(*rect))+ }+ _ => None,+ })+ }+}++pub(crate) fn intersect_bounds(bounds: Option<FloatRect>, limit: Option<FloatRect>) -> Option<FloatRect> {+ match (bounds, limit) {+ (Some(bounds), Some(limit)) => Some(bounds.intersected(limit)),+ (bounds, limit) => bounds.or(limit),+ }+}++/// The index of a run group among the `RunGroups` of a list, and in `ListPlacement::run_groups`, which places them in+/// the same order.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct RunGroupIndex(pub usize);++/// Runs that are placed together, as they hold every run of the group effects and of the 3D sorting contexts that sort+/// their planes by depth among them, in paint order.+pub struct RunGroups {+ first_and_last_run_of_groups: Vec<(u32, u32)>,+ group_of_run: Vec<u32>,+ group_is_under_mask: Vec<bool>,+ roots_of_contexts_sorting_planes_by_depth: Vec<Option<SpatialNodeIndex>>,+ run_is_sorted_by_depth: Vec<bool>,+ group_is_sorted_by_depth: Vec<bool>,+}++// By the tree's structure rather than effect values, so that groups stay put while an opacity animates.+fn outermost_grouping_effects(tree: &VisualContextTree) -> Vec<EffectNodeIndex> {+ let mut outermost_grouping_effect_of_effect = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];+ tree.visit_effect_nodes_parents_first(|index| {+ let node = &tree.effect_nodes[index];+ let outermost_of_parent = if node.parent.is_none() {+ EffectNodeIndex::NONE+ } else {+ outermost_grouping_effect_of_effect[node.parent.0 as usize]+ };+ let is_grouping = node.data.pushes_layer() && tree.root_isolation_effect != Some(EffectNodeIndex(index as u32));+ outermost_grouping_effect_of_effect[index] = if !outermost_of_parent.is_none() {+ outermost_of_parent+ } else if is_grouping {+ EffectNodeIndex(index as u32)+ } else {+ EffectNodeIndex::NONE+ };+ });+ outermost_grouping_effect_of_effect+}++fn first_and_last_run_of_groups_holding_whole_grouping_effects_and_sorting_contexts(+ grouping_effect_of_run: &[EffectNodeIndex],+ sorting_context_of_run: &[Option<SpatialNodeIndex>],+) -> Vec<(u32, u32)> {+ let mut last_run_of_grouping_effect = HashMap::new();+ let mut last_run_of_sorting_context = HashMap::new();+ for (run_index, (grouping_effect, sorting_context)) in+ grouping_effect_of_run.iter().zip(sorting_context_of_run).enumerate()+ {+ if !grouping_effect.is_none() {+ last_run_of_grouping_effect.insert(grouping_effect.0, run_index);+ }+ if let Some(sorting_context) = sorting_context {+ last_run_of_sorting_context.insert(sorting_context.0, run_index);+ }+ }+ let mut first_and_last_run_of_groups = Vec::new();+ let mut run_index = 0;+ while run_index < grouping_effect_of_run.len() {+ let first = run_index;+ let mut last = run_index;+ let mut run_that_may_extend_group = run_index;+ while run_that_may_extend_group <= last {+ let grouping_effect = grouping_effect_of_run[run_that_may_extend_group];+ if !grouping_effect.is_none() {+ last = last.max(last_run_of_grouping_effect[&grouping_effect.0]);+ }+ if let Some(sorting_context) = sorting_context_of_run[run_that_may_extend_group] {+ last = last.max(last_run_of_sorting_context[&sorting_context.0]);+ }+ run_that_may_extend_group += 1;+ }+ first_and_last_run_of_groups.push((first as u32, last as u32));+ run_index = last + 1;+ }+ first_and_last_run_of_groups+}++impl RunGroups {+ /// The groups of the runs of a list, which the structure of its tree decides, with the 3D sorting contexts of the+ /// tree that sort their planes by depth, which the transforms of their planes decide.+ pub fn new<'a>(+ tree: &VisualContextTree,+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun>,+ ) -> Self {+ let roots_of_contexts_sorting_planes_by_depth = tree.roots_of_contexts_sorting_planes_by_depth();+ let mut sorting_context_of_run = Vec::new();+ let outermost_grouping_effects = outermost_grouping_effects(tree);+ let mut effect_chain_holds_mask = vec![false; tree.effect_nodes.len()];+ tree.visit_effect_nodes_parents_first(|index| {+ let node = &tree.effect_nodes[index];+ let parent_holds_mask = !node.parent.is_none() && effect_chain_holds_mask[node.parent.0 as usize];+ effect_chain_holds_mask[index] = parent_holds_mask || matches!(node.data, EffectNodeData::Mask(_));+ });+ let (grouping_effect_of_run, run_is_under_mask): (Vec<EffectNodeIndex>, Vec<bool>) = command_runs+ .into_iter()+ .map(|run| {+ sorting_context_of_run.push(+ roots_of_contexts_sorting_planes_by_depth+ .get(run.context.spatial.0 as usize)+ .copied()+ .flatten(),+ );+ if run.context.effect.is_none() {+ (EffectNodeIndex::NONE, false)+ } else {+ (+ outermost_grouping_effects[run.context.effect.0 as usize],+ effect_chain_holds_mask[run.context.effect.0 as usize],+ )+ }+ })+ .unzip();+ let first_and_last_run_of_groups =+ first_and_last_run_of_groups_holding_whole_grouping_effects_and_sorting_contexts(+ &grouping_effect_of_run,+ &sorting_context_of_run,+ );+ let mut group_of_run = vec![0u32; grouping_effect_of_run.len()];+ for (group_index, &(first, last)) in first_and_last_run_of_groups.iter().enumerate() {+ group_of_run[first as usize..=last as usize].fill(group_index as u32);+ }++ let group_is_under_mask = first_and_last_run_of_groups+ .iter()+ .map(|&(first, last)| {+ run_is_under_mask[first as usize..=last as usize]+ .iter()+ .any(|&under_mask| under_mask)+ })+ .collect();+ let run_is_sorted_by_depth: Vec<bool> = sorting_context_of_run.iter().map(Option::is_some).collect();+ let group_is_sorted_by_depth = first_and_last_run_of_groups+ .iter()+ .map(|&(first, last)| {+ run_is_sorted_by_depth[first as usize..=last as usize]+ .iter()+ .any(|&sorted| sorted)+ })+ .collect();+ Self {+ first_and_last_run_of_groups,+ group_of_run,+ group_is_under_mask,+ roots_of_contexts_sorting_planes_by_depth,+ run_is_sorted_by_depth,+ group_is_sorted_by_depth,+ }+ }++ pub fn root_of_context_sorting_planes_by_depth(&self, spatial: SpatialNodeIndex) -> Option<SpatialNodeIndex> {+ self.roots_of_contexts_sorting_planes_by_depth+ .get(spatial.0 as usize)+ .copied()+ .flatten()+ }++ /// Whether the groups are those of a tree whose 3D sorting contexts sort the same content by depth.+ pub fn match_depth_sorting_roots(+ &self,+ roots_of_contexts_sorting_planes_by_depth: &[Option<SpatialNodeIndex>],+ ) -> bool {+ self.roots_of_contexts_sorting_planes_by_depth == roots_of_contexts_sorting_planes_by_depth+ }++ /// Whether the group holds a 3D sorting context that sorts its planes by depth, whose content is replayed whole+ /// wherever any of the group shows, as sorting the planes reads all of them.+ pub fn group_is_sorted_by_depth(&self, group: RunGroupIndex) -> bool {+ self.group_is_sorted_by_depth[group.0]+ }++ pub fn run_is_sorted_by_depth(&self, run_index: usize) -> bool {+ self.run_is_sorted_by_depth[run_index]+ }++ pub fn first_and_last_run_of_groups(&self) -> &[(u32, u32)] {+ &self.first_and_last_run_of_groups+ }++ pub fn group_of_run(&self, run_index: usize) -> RunGroupIndex {+ RunGroupIndex(self.group_of_run[run_index] as usize)+ }++ /// Whether the group is under a mask, whose content is replayed whole wherever any of it shows.+ pub fn group_is_under_mask(&self, group: RunGroupIndex) -> bool {+ self.group_is_under_mask[group.0]+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/reach.rs b/Libraries/LibCompositing/Rust/src/display_list/reach.rsnew file mode 100644index 00000000000..3f51ef91e2a--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/reach.rs@@ -0,0 +1,95 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libgfx_rust::{FloatRect, IntRect};++/// The rects a `Reach` can be bounded by.+pub trait RectOfReach: Copy + Default {+ fn united(self, other: Self) -> Self;+ fn intersected(self, other: Self) -> Self;+ fn is_empty(self) -> bool;+}++impl RectOfReach for IntRect {+ fn united(self, other: Self) -> Self {+ IntRect::united(self, other)+ }++ fn intersected(self, other: Self) -> Self {+ IntRect::intersected(self, other)+ }++ fn is_empty(self) -> bool {+ IntRect::is_empty(self)+ }+}++impl RectOfReach for FloatRect {+ fn united(self, other: Self) -> Self {+ FloatRect::united(self, other)+ }++ fn intersected(self, other: Self) -> Self {+ FloatRect::intersected(self, other)+ }++ fn is_empty(self) -> bool {+ FloatRect::is_empty(self)+ }+}++/// Where content can show or a filter can read: nowhere, within a rect, or anywhere at all.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum Reach<Rect> {+ #[default]+ Nothing,+ Within(Rect),+ Anywhere,+}++impl<Rect: RectOfReach> Reach<Rect> {+ pub fn united(self, other: Self) -> Self {+ match (self, other) {+ (Self::Nothing, reach) | (reach, Self::Nothing) => reach,+ (Self::Within(rect), Self::Within(other)) => Self::Within(rect.united(other)),+ _ => Self::Anywhere,+ }+ }++ pub fn touches(self, rect: Rect) -> bool {+ match self {+ Self::Nothing => false,+ Self::Within(within) => !within.intersected(rect).is_empty(),+ Self::Anywhere => true,+ }+ }++ pub fn meets(self, other: Self) -> bool {+ match (self, other) {+ (Self::Nothing, _) | (_, Self::Nothing) => false,+ (Self::Within(rect), Self::Within(other)) => !rect.intersected(other).is_empty(),+ (Self::Within(rect), Self::Anywhere) | (Self::Anywhere, Self::Within(rect)) => !rect.is_empty(),+ (Self::Anywhere, Self::Anywhere) => true,+ }+ }++ /// The part of `area` it reaches, which is empty where it reaches none of it.+ pub fn part_of(self, area: Rect) -> Rect {+ match self {+ Self::Nothing => Rect::default(),+ Self::Within(rect) => rect.intersected(area),+ Self::Anywhere => area,+ }+ }++ pub fn limited_to(self, limit: Rect) -> Self {+ match self {+ Self::Nothing => Self::Nothing,+ Self::Within(rect) => Self::Within(rect.intersected(limit)),+ Self::Anywhere => Self::Within(limit),+ }+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rsindex e169daf1004..98749acf06e 100644--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs@@ -16,22 +16,25 @@ use crate::display_list::commands::{};use crate::display_list::depth_sorted_plan::{DepthSortedReplayStepKind, build_depth_sorted_replay_plan};use crate::display_list::effect_clip_plan::EffectClipPlan;-use crate::display_list::effect_geometry::{EffectGeometry, Extent, compute_effect_geometry};+use crate::display_list::effect_geometry::{+ EffectGeometry, Extent, compute_effect_geometry, nearest_effects_at_or_above_where,+};use crate::display_list::nested_records::{replays_nested_records_where_it_plays, span_bytes};+use crate::display_list::storage::{ChunkIndexInList, DisplayListStorage, ListSpan};use crate::host::{- CompositedContextDraw, IsolatedGroup, PresentedScrollbar, RecordSpan, ResolvedFillRect,- ResolvedFillRectWithRoundedCorners, TileRaster, VectorImagePlacement, VectorImageReplay,+ CompositedContextDraw, IsolatedGroup, PresentedScrollbar, ResolvedFillRect, ResolvedFillRectWithRoundedCorners,+ SurfaceDraw, TileRaster, VectorImagePlacement, VectorImageReplay,};use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{- ClipNodeData, ContextRef, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,+ ClipNodeData, ContextRef, EffectNodeData, RasterRoot, VisualContextTree, WorldTransforms, device_offset_for_index,resolve_leaf_to_context_matrices,};use libgfx_rust::filter::Filter;use libgfx_rust::path::Path;use libgfx_rust::{- AffineTransform, Color, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, FloatVector3, IntRect, IntSize,- MaskKind, WindingRule, enclosing_int_rect, multiply_affine,+ AffineTransform, Color, CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect,+ FloatVector3, IntRect, IntSize, MaskKind, WindingRule, enclosing_int_rect, multiply_affine,};use std::cell::RefCell;use std::collections::HashMap;@@ -46,17 +49,17 @@ pub trait ReplayPainter {fn push_clip(&mut self, clip: &ReplayClip);fn push_clip_path(&mut self, path: &Path, winding_rule: WindingRule);fn push_layer(&mut self, layer: &ReplayLayer);- // `backdrop`, when given, carries the backdrop filter the mask's layer starts with.+ /// `backdrop`, when given, carries the backdrop filter the mask's layer starts with.fn push_mask(&mut self, mask: &ReplayMask, backdrop: Option<&ReplayLayer>);- // Starts the content that masks the layer `push_mask` opened. `pop_mask` closes both.+ /// Starts the content that masks the layer `push_mask` opened. `pop_mask` closes both.fn begin_mask_content(&mut self, mask: &ReplayMask);fn pop_mask(&mut self);fn pop(&mut self);fn push_device_space_plane_clip(&mut self, vertices: &[FloatVector3]);fn push_transform(&mut self, transform: &AffineTransform);fn push_clip_path_bytes(&mut self, path_bytes: &[u8], winding_rule: WindingRule, mode: ClipMode);- // Plays one command as it was recorded. `command` holds the command struct, which can differ from the one at the- // start of `payload`; the command's spans point into `payload`.+ /// Plays one command as it was recorded. `command` holds the command struct, which can differ from the one at the+ /// start of `payload`; the command's spans point into `payload`.fn play_command(&mut self, command_type: DisplayListCommandType, command: &[u8], payload: &[u8]);fn fill_rect(&mut self, fill: &ResolvedFillRect);fn fill_rect_with_rounded_corners(&mut self, fill: &ResolvedFillRectWithRoundedCorners);@@ -66,16 +69,18 @@ pub trait ReplayPainter {fn begin_isolated_group_mask(&mut self, kind: MaskKind);fn end_isolated_group_mask(&mut self);fn end_isolated_group(&mut self);- // Answers whether the tile records are to be replayed into the raster, which `end_tile_raster` then finishes.+ /// Answers whether the tile records are to be replayed into the raster, which `end_tile_raster` then finishes.fn begin_tile_raster(&mut self, tile: &TileRaster) -> bool;fn end_tile_raster(&mut self);- // Unless the painter skips the image, the replay of its records is followed by `end_vector_image`.+ /// Unless the painter skips the image, the replay of its records is followed by `end_vector_image`.fn begin_vector_image(&mut self,placement: &VectorImagePlacement,requires_direct_replay: bool,) -> VectorImageReplay;fn end_vector_image(&mut self);+ /// Draws pixels of a surface of the compositor under the canvas's matrix and clip.+ fn draw_surface(&mut self, draw: &SurfaceDraw);fn execute_run<'t>(&mut self, _run_index: usize, records: &'t [u8], context: &RecordsContext<'_, 't>) {replay_records(records, context, self);@@ -89,11 +94,21 @@ pub struct ScrollbarShownByFrame {pub vertical: bool,pub gutter_rect: FloatRect,pub thumb_rect: FloatRect,- // How far the scrollbar has grown from its thin geometry into its expanded one.+ /// How far the scrollbar has grown from its thin geometry into its expanded one.pub expansion: f32,pub opacity: f32,}+/// The scrollbar of the frame that a scrollbar command of the display list paints, if the frame shows it.+pub fn scrollbar_shown_by_frame<'a>(+ scrollbars: &'a [ScrollbarShownByFrame],+ command: &PaintScrollBar,+) -> Option<&'a ScrollbarShownByFrame> {+ scrollbars.iter().find(|scrollbar| {+ scrollbar.scroll_node_index == command.scroll_node_index && scrollbar.vertical == command.vertical+ })+}+/// The surface that shows the frame of a context drawn into another, and the part of it the frame is in.#[derive(Clone, Copy, Debug)]pub struct ResolvedCompositedContext {@@ -103,8 +118,8 @@ pub struct ResolvedCompositedContext {/// Where a replay finds the frames of the contexts the list draws.pub trait CompositedContexts {- // The frame of the child context as it is drawn into `destination_rect` under `canvas_matrix`, none where the- // context shows nothing there.+ /// The frame of the child context as it is drawn into `destination_rect` under `canvas_matrix`, none where the+ /// context shows nothing there.fn resolve(&self,child_context_id: u64,@@ -127,7 +142,7 @@ impl CompositedContexts for NoCompositedContexts {}}-/// What a replay paints a display list with besides the list: where the frame presents the scroll containers and the+/// The frame state a replay paints a display list with: where the frame presents the scroll containers and the/// scrollbars, the time it shows a blinking caret at, and the frames of the contexts it draws.#[derive(Clone, Copy)]pub struct ReplayFrame<'a> {@@ -148,16 +163,14 @@ impl ReplayFrame<'_> {}}- // Tile records paint into a raster of their own, where nothing scrolls.- fn for_tile_records(&self) -> Self {+ fn without_scroll_offsets(&self) -> Self {Self {scroll_offsets: &[],..*self}}- // The records of an SVG image scroll nothing, and the scrollbars of the frame do not belong to its scroll nodes.- fn for_vector_image_records(&self) -> Self {+ fn without_scroll_offsets_or_scrollbars(&self) -> Self {Self {scroll_offsets: &[],scrollbars: &[],@@ -170,32 +183,33 @@ impl ReplayFrame<'_> {/// content that each of its masks declared.pub struct ListReplay<'t> {pub tree: &'t VisualContextTree,- declared_mask_contents: RefCell<HashMap<EffectNodeIndex, &'t [u8]>>,+ declared_mask_content_by_effect: RefCell<HashMap<EffectNodeIndex, &'t [u8]>>,}impl<'t> ListReplay<'t> {pub fn new(tree: &'t VisualContextTree) -> Self {Self {tree,- declared_mask_contents: RefCell::new(HashMap::new()),+ declared_mask_content_by_effect: RefCell::new(HashMap::new()),}}fn declare_mask_content(&self, effect: EffectNodeIndex, content: &'t [u8]) {- self.declared_mask_contents.borrow_mut().insert(effect, content);+ self.declared_mask_content_by_effect+ .borrow_mut()+ .insert(effect, content);}fn declared_mask_content(&self, effect: EffectNodeIndex) -> Option<&'t [u8]> {- self.declared_mask_contents.borrow().get(&effect).copied()+ self.declared_mask_content_by_effect.borrow().get(&effect).copied()}}-/// What playing a stream of records needs besides the records: the list they belong to, the frame, and the to-root-/// matrix of the space an inline clip of its own space is applied in.+/// What playing a stream of records needs besides the records.pub struct RecordsContext<'c, 't> {- pub list: &'c ListReplay<'t>,+ pub list_replay: &'c ListReplay<'t>,pub frame: &'c ReplayFrame<'c>,- pub clip_space_matrix: &'c dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+ pub to_root_matrix_of_inline_clip_space: &'c dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,}/// How far the inline clips of a command that apply in spaces of their own let it draw.@@ -207,20 +221,19 @@ pub(crate) enum OwnSpaceClipExtent {Within(FloatRect),}-/// The part of `bounds`, in the space of a command whose to-root matrix is `command_to_root`, that its inline clips-/// in spaces of their own leave the command to draw in, or None if it has no such clip. `clip_space_matrix` gives-/// the to-root matrix of a clip's space.+/// The part of `command_bounds`, in the space of a command whose to-root matrix is `command_to_root`, that its inline+/// clips in spaces of their own leave the command to draw in, or None if it has no such clip.pub(crate) fn own_space_clip_extent(header: &DisplayListCommandHeader,payload: &[u8],- bounds: FloatRect,+ command_bounds: FloatRect,command_to_root: FloatMatrix4x4,- mut clip_space_matrix: impl FnMut(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+ mut to_root_matrix_of_clip_space: impl FnMut(SpatialNodeIndex) -> Option<FloatMatrix4x4>,) -> Option<OwnSpaceClipExtent> {let mut extent = None;for clip in inline_clips_of(header, payload).filter(|clip| clip.has_own_space) {- let mapped_clip_rect = (clip.mode == ClipMode::Intersect && command_to_root.is_2d_affine())- .then(|| clip_space_matrix(clip.space))+ let clip_rect_in_command_space = (clip.mode == ClipMode::Intersect && command_to_root.is_2d_affine())+ .then(|| to_root_matrix_of_clip_space(clip.space)).flatten().filter(|clip_to_root| clip_to_root.is_2d_affine()).and_then(|clip_to_root| {@@ -228,21 +241,23 @@ pub(crate) fn own_space_clip_extent(let clip_to_command = multiply_affine(root_to_command, clip_to_root.extract_2d_affine());Some(clip_to_command.map_rect(clip.clip_rect_or_path_device_bounds))});- let Some(mapped_clip_rect) = mapped_clip_rect else {+ let Some(clip_rect_in_command_space) = clip_rect_in_command_space else {return Some(OwnSpaceClipExtent::Unbounded);};- let previous = match extent {+ let extent_so_far = match extent {Some(OwnSpaceClipExtent::Within(rect)) => rect,- _ => bounds,+ _ => command_bounds,};- extent = Some(OwnSpaceClipExtent::Within(previous.intersected(mapped_clip_rect)));+ extent = Some(OwnSpaceClipExtent::Within(+ extent_so_far.intersected(clip_rect_in_command_space),+ ));}extent}const CARET_BLINK_INTERVAL_NS: i64 = 500_000_000;-fn caret_is_visible_at_time(caret: &PaintCaret, time_ns: i64) -> bool {+pub(crate) fn caret_is_visible_at_time(caret: &PaintCaret, time_ns: i64) -> bool {if !caret.should_blink {return true;}@@ -276,19 +291,18 @@ pub fn presented_scrollbar_with_colors(thumb_outline_color: Color,track_color: Color,) -> PresentedScrollbar {- // The gutter of a thin scrollbar is not painted, so the gutter grows out of the thin track as it fades in.- let track_alpha = (f32::from(track_color.alpha()) * expansion).round();+ let track_alpha_faded_in_by_expansion = (f32::from(track_color.alpha()) * expansion).round();PresentedScrollbar {gutter_rect,thumb_rect,thumb_color,thumb_outline_color,- track_color: track_color.with_alpha(track_alpha as u8),+ track_color: track_color.with_alpha(track_alpha_faded_in_by_expansion as u8),opacity,}}-fn tile_raster_key(tile_records: &[u8], tile_size: IntSize) -> u64 {+fn tile_raster_cache_key(tile_records: &[u8], tile_size: IntSize) -> u64 {let mut hasher = crate::fast_hash::fast_hasher();hasher.write(tile_records);hasher.write_i32(tile_size.width);@@ -296,8 +310,7 @@ fn tile_raster_key(tile_records: &[u8], tile_size: IntSize) -> u64 {hasher.finish()}-// The records a pattern paint style tiles are replayed into its raster before the path command that paints with it.-fn rasterize_pattern_tile_of<'t, Painter: ReplayPainter + ?Sized>(+fn rasterize_tile_if_pattern<'t, Painter: ReplayPainter + ?Sized>(paint_kind: PathPaintKind,paint_style: &crate::display_list::commands::DisplayListPaintStyle,payload: &'t [u8],@@ -322,13 +335,13 @@ fn rasterize_pattern_tile_of<'t, Painter: ReplayPainter + ?Sized>(cacheable: false,};if painter.begin_tile_raster(&tile) {- let tile_frame = context.frame.for_tile_records();+ let tile_frame = context.frame.without_scroll_offsets();replay_records(span_bytes(payload, paint_style.pattern_tile),&RecordsContext {- list: context.list,+ list_replay: context.list_replay,frame: &tile_frame,- clip_space_matrix: &|_| None,+ to_root_matrix_of_inline_clip_space: &|_| None,},painter,);@@ -336,14 +349,13 @@ fn rasterize_pattern_tile_of<'t, Painter: ReplayPainter + ?Sized>(}}-// Plays one record, inside its inline clips and transform, resolving what the frame decides about it.-fn play_record<'t, Painter: ReplayPainter + ?Sized>(+fn play_record_resolving_frame_state<'t, Painter: ReplayPainter + ?Sized>(header: &DisplayListCommandHeader,payload: &'t [u8],context: &RecordsContext<'_, 't>,painter: &mut Painter,) {- let tree = context.list.tree;+ let tree = context.list_replay.tree;match header.command_type {DisplayListCommandType::FillRect => {let command = read_command::<FillRect>(payload);@@ -381,11 +393,7 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(}DisplayListCommandType::PaintScrollBar => {let mut command = read_command::<PaintScrollBar>(payload);- // A scrollbar command of the display list with no scrollbar of the frame is painted as the command gives- // it. The colors are the ones the display list resolved for the page, which it may have darkened.- let shown_by_frame = context.frame.scrollbars.iter().find(|scrollbar| {- scrollbar.scroll_node_index == command.scroll_node_index && scrollbar.vertical == command.vertical- });+ let shown_by_frame = scrollbar_shown_by_frame(context.frame.scrollbars, &command);let scrollbar = match shown_by_frame {Some(scrollbar) => presented_scrollbar_with_colors(scrollbar.gutter_rect,@@ -397,14 +405,14 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(command.track_color,),None => {- let device_offset =+ let scroll_offset_in_device_pixels =device_offset_for_index(context.frame.scroll_offsets, command.scroll_node_index);if command.vertical {- let shift = (-f64::from(device_offset.y) * command.scroll_size) as i32;- command.thumb_rect.y = command.thumb_rect.y.saturating_add(shift);+ let thumb_shift = (-f64::from(scroll_offset_in_device_pixels.y) * command.scroll_size) as i32;+ command.thumb_rect.y = command.thumb_rect.y.saturating_add(thumb_shift);} else {- let shift = (-f64::from(device_offset.x) * command.scroll_size) as i32;- command.thumb_rect.x = command.thumb_rect.x.saturating_add(shift);+ let thumb_shift = (-f64::from(scroll_offset_in_device_pixels.x) * command.scroll_size) as i32;+ command.thumb_rect.x = command.thumb_rect.x.saturating_add(thumb_shift);}PresentedScrollbar {gutter_rect: command.gutter_rect.to_float(),@@ -426,16 +434,15 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(DisplayListCommandType::DrawCompositedContext => {let command = read_command::<DrawCompositedContext>(payload);let mut dst_rect = command.dst_rect;- // Snap iframe origins to device pixels for browser compatibility when transforms are absent or identity.- // Preserve fractional placement under other transforms to retain the raster phase of surrounding content.- if command.snap_origin_if_untransformed- && tree.translations_snap_to_device_pixels(command.spatial_node_index)- {+ // Where it does not snap, the fractional origin keeps the raster phase of surrounding content.+ let origin_snaps_to_device_pixels = command.snap_origin_if_untransformed+ && tree.translations_snap_to_device_pixels(command.spatial_node_index);+ if origin_snaps_to_device_pixels {dst_rect.x = dst_rect.x.round();dst_rect.y = dst_rect.y.round();}let canvas_matrix = painter.canvas_matrix();- let Some(resolved) =+ let Some(resolved_context) =context.frame.composited_contexts@@ -443,12 +450,12 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(else {return;};- if resolved.surface.is_null() || resolved.content_rect.is_empty() {+ if resolved_context.surface.is_null() || resolved_context.content_rect.is_empty() {return;}painter.draw_composited_context(&CompositedContextDraw {- surface: resolved.surface,- src_rect: resolved.content_rect,+ surface: resolved_context.surface,+ src_rect: resolved_context.content_rect,dst_rect,scaling_mode: command.scaling_mode,});@@ -456,7 +463,7 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(DisplayListCommandType::DeclareMaskContent => {let command = read_command::<DeclareMaskContent>(payload);context- .list+ .list_replay.declare_mask_content(command.effect, span_bytes(payload, command.content));}DisplayListCommandType::DrawIsolatedGroup => {@@ -470,9 +477,9 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(filter_bytes_size: filter.len(),});let nested_records_context = RecordsContext {- list: context.list,+ list_replay: context.list_replay,frame: context.frame,- clip_space_matrix: &|_| None,+ to_root_matrix_of_inline_clip_space: &|_| None,};replay_records(span_bytes(payload, command.content), &nested_records_context, painter);if command.mask.size != 0 {@@ -489,18 +496,18 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(}let tile_records = span_bytes(payload, command.tile);let tile = TileRaster {- key: tile_raster_key(tile_records, command.tile_size),+ key: tile_raster_cache_key(tile_records, command.tile_size),size: command.tile_size,cacheable: true,};if painter.begin_tile_raster(&tile) {- let tile_frame = context.frame.for_tile_records();+ let tile_frame = context.frame.without_scroll_offsets();replay_records(tile_records,&RecordsContext {- list: context.list,+ list_replay: context.list_replay,frame: &tile_frame,- clip_space_matrix: &|_| None,+ to_root_matrix_of_inline_clip_space: &|_| None,},painter,);@@ -510,12 +517,12 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(}DisplayListCommandType::FillPath => {let command = read_command::<FillPath>(payload);- rasterize_pattern_tile_of(command.paint_kind, &command.paint_style, payload, context, painter);+ rasterize_tile_if_pattern(command.paint_kind, &command.paint_style, payload, context, painter);painter.play_command(header.command_type, payload, payload);}DisplayListCommandType::StrokePath => {let command = read_command::<StrokePath>(payload);- rasterize_pattern_tile_of(command.paint_kind, &command.paint_style, payload, context, painter);+ rasterize_tile_if_pattern(command.paint_kind, &command.paint_style, payload, context, painter);painter.play_command(header.command_type, payload, payload);}DisplayListCommandType::PaintVectorImage => {@@ -528,13 +535,13 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(if painter.begin_vector_image(&placement, command.requires_direct_replay) == VectorImageReplay::Skipped {return;}- let vector_image_frame = context.frame.for_vector_image_records();+ let vector_image_frame = context.frame.without_scroll_offsets_or_scrollbars();replay_records(span_bytes(payload, command.records),&RecordsContext {- list: context.list,+ list_replay: context.list_replay,frame: &vector_image_frame,- clip_space_matrix: &|_| None,+ to_root_matrix_of_inline_clip_space: &|_| None,},painter,);@@ -553,7 +560,7 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(context: &RecordsContext<'_, 't>,painter: &mut Painter,) {- let clip_space_matrix = context.clip_space_matrix;+ let to_root_matrix_of_inline_clip_space = context.to_root_matrix_of_inline_clip_space;for_each_command(records, |header, _, payload| {if header.command_type.is_compositor_metadata() {return;@@ -564,29 +571,31 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(return;}}- // The matrix of the command's space, while an inline clip in a space of its own has the canvas in another.- let mut command_space_matrix = None;+ let mut command_space_matrix_to_restore = None;if header.inline_clip_count != 0 && has_inline_clip_in_its_own_space(header, payload) {let command_to_root = painter.canvas_matrix();- // NB: The bounds of a command do not include its clips in spaces of their own, which move apart from it- // as they scroll, so the command is culled against where they are now.- if let Some(OwnSpaceClipExtent::Within(rect)) = own_space_clip_extent(+ // NB: Recorded bounds leave out clips in spaces of their own, which scroll apart from the command.+ if let Some(OwnSpaceClipExtent::Within(part_left_by_own_space_clips)) = own_space_clip_extent(header,payload,bounding_rect_computed_from_payload(header, payload).unwrap_or_default().to_float(),command_to_root,- clip_space_matrix,- ) && (rect.is_empty() || painter.would_be_fully_clipped_by_painter(enclosing_int_rect(rect)))+ to_root_matrix_of_inline_clip_space,+ ) && (part_left_by_own_space_clips.is_empty()+ || painter.would_be_fully_clipped_by_painter(enclosing_int_rect(part_left_by_own_space_clips))){return;}}for clip in inline_clips_of(header, payload) {- let own_space_matrix = clip.has_own_space.then(|| clip_space_matrix(clip.space)).flatten();+ let own_space_matrix = clip+ .has_own_space+ .then(|| to_root_matrix_of_inline_clip_space(clip.space))+ .flatten();if let Some(matrix) = &own_space_matrix {- command_space_matrix.get_or_insert_with(|| painter.canvas_matrix());+ command_space_matrix_to_restore.get_or_insert_with(|| painter.canvas_matrix());painter.set_matrix(matrix);}match clip.kind {@@ -604,7 +613,7 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(}),}if own_space_matrix.is_some()- && let Some(matrix) = &command_space_matrix+ && let Some(matrix) = &command_space_matrix_to_restore{painter.set_matrix(matrix);}@@ -613,7 +622,7 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(if let Some(transform) = &inline_transform {painter.push_transform(transform);}- play_record(header, payload, context, painter);+ play_record_resolving_frame_state(header, payload, context, painter);if inline_transform.is_some() {painter.pop();}@@ -621,7 +630,7 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(painter.pop();}// Popping a clip pushed in another space restores the matrix it was pushed with.- if let Some(matrix) = &command_space_matrix {+ if let Some(matrix) = &command_space_matrix_to_restore {painter.set_matrix(matrix);}});@@ -631,23 +640,22 @@ pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(// can push past them by up to this much, and a layer's bounds clip what is drawn into it.const LAYER_CONTENT_MARGIN_IN_DEVICE_PIXELS: f32 = 2.0;-// One entry of the canvas save stack: a clip or an effect the replay has entered.+// Spaces are entered with one absolute set_matrix, so only clips and effects go on the canvas stack.#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum Applied {+enum CanvasStackEntry {Clip(ClipNodeIndex),Effect(EffectNodeIndex),}-// Steady-state replays reuse the previous frame's capacity. Taking the storage out of the slot-// for the duration of a replay keeps re-entrant nested replays from clobbering the outer-// driver's buffers; the slot keeps whichever returned storage has the larger table.+// Steady-state replays reuse the previous frame's capacity. A replay takes the storage out of the slot, so that+// re-entrant nested replays cannot clobber the outer driver's buffers.#[derive(Default)]struct ReplayScratchStorage {world: WorldTransforms,culling: TreeCullingScratch,- applied: Vec<Applied>,- target: Vec<Applied>,- effect_geometry: Vec<EffectGeometry>,+ canvas_stack: Vec<CanvasStackEntry>,+ target_canvas_stack: Vec<CanvasStackEntry>,+ effect_geometry_by_effect_index: Vec<EffectGeometry>,}thread_local! {@@ -661,25 +669,39 @@ fn take_replay_scratch_storage() -> ReplayScratchStorage {fn return_replay_scratch_storage(mut storage: ReplayScratchStorage) {storage.world.clear();storage.culling.clear();- storage.applied.clear();- storage.target.clear();- storage.effect_geometry.clear();+ storage.canvas_stack.clear();+ storage.target_canvas_stack.clear();+ storage.effect_geometry_by_effect_index.clear();WARM_REPLAY_SCRATCH_STORAGE.with(|slot| {let mut slot = slot.borrow_mut();let slot_has_larger_table = slot.as_ref()- .is_some_and(|kept| kept.world.to_root.capacity() >= storage.world.to_root.capacity());+ .is_some_and(|cached| cached.world.to_root.capacity() >= storage.world.to_root.capacity());if !slot_has_larger_table {*slot = Some(storage);}});}+/// Which records a replay plays, and what it leaves to the compositor.#[derive(Clone, Copy, Default)]pub struct ReplaySelection<'a> {- pub record_spans: Option<&'a [RecordSpan]>,+ /// The records to replay, in paint order, or none for the whole list.+ pub record_spans: Option<&'a [ListSpan]>,pub skip_root_isolation_layer: bool,pub allows_lcd_text: bool,+ /// Per clip node, whether the compositor applies it as it composites what the replay draws.+ pub clips_left_to_composite: Option<&'a [bool]>,+ /// The effect that the compositor composites the replayed records inside. The replay leaves it out, with the+ /// effects around it and the clips it is entered within, which the compositor applies as it composites.+ pub composited_effect: Option<EffectNodeIndex>,+ /// Where the frame is, in the coordinates of the list before the target's own transform, where the target is not+ /// the frame: a blur of a backdrop mirrors at the edge of the frame there, as it does at the edge of the frame's+ /// surface in a raster of the frame.+ pub frame_edge_backdrop_blurs_mirror_at: Option<FloatRect>,+ /// The node whose subtree the replay draws in its own coordinates, for rasters of a space whose anchor the+ /// compositor animates.+ pub raster_root: Option<RasterRoot>,}#[derive(Clone, Copy, PartialEq, Eq)]@@ -690,33 +712,53 @@ enum SwitchResult {struct ReplayDriver<'a, Painter: ReplayPainter + ?Sized> {tree: &'a VisualContextTree,- tape: &'a [u8],- command_runs: &'a [DisplayListCommandRun],- list: ListReplay<'a>,+ display_list: &'a DisplayListStorage,+ list_replay: ListReplay<'a>,frame: &'a ReplayFrame<'a>,effect_clips: &'a EffectClipPlan,root_group_color: Color,selection: ReplaySelection<'a>,painter: &'a mut Painter,- // Spatial nodes never touch the canvas save stack: any node's space is entered absolutely with a single- // set_matrix(), so only clips and effects do.world: WorldTransforms,culling: TreeCullingScratch,spatial_dependency_order: Vec<u32>,- tree_has_sorting_contexts: bool,+ tree_sorts_planes_by_depth: bool,replay_base_matrix: FloatMatrix4x4,- // The draw space the canvas matrix currently equals, if known; popping a clip or a layer- // resets the matrix to its save point, so unwinding invalidates it. Recorded streams contain- // no matrix-mutating commands, so playing commands never invalidates the cache.- current_ctm_space: Option<SpatialNodeIndex>,- // The canvas save stack as clips and effects, the stack a target context needs, and the- // pair the applied stack currently serves.- applied: Vec<Applied>,- target: Vec<Applied>,- applied_context: Option<(ClipNodeIndex, EffectNodeIndex)>,- // Filled when the first layer is entered, since only replays that enter layers need it.- effect_geometry: Vec<EffectGeometry>,- effect_geometry_is_known: bool,+ // None once popping a clip or a layer has reset the canvas matrix to its save point. Played records never change+ // the matrix.+ draw_space_of_canvas_matrix: Option<SpatialNodeIndex>,+ canvas_stack: Vec<CanvasStackEntry>,+ target_canvas_stack: Vec<CanvasStackEntry>,+ clip_and_effect_of_canvas_stack: Option<(ClipNodeIndex, EffectNodeIndex)>,+ effect_geometry_by_effect_index: Vec<EffectGeometry>,+ effect_geometry_is_computed: bool,+ effects_left_to_composite_around_composited_effect: Vec<bool>,+ clips_left_to_composite_around_composited_effect: Vec<bool>,+ content_reads_layer_by_effect_index: Option<Vec<bool>>,+ first_backdrop_drawn_by_masks_by_reading_mask: std::cell::OnceCell<Vec<EffectNodeIndex>>,+}++fn effects_and_clips_left_to_composite_around(+ tree: &VisualContextTree,+ effect_clips: &EffectClipPlan,+ composited_effect: Option<EffectNodeIndex>,+) -> (Vec<bool>, Vec<bool>) {+ let Some(composited_effect) = composited_effect else {+ return (Vec::new(), Vec::new());+ };+ let mut effects_left_to_composite = vec![false; tree.effect_nodes.len()];+ let mut effect = composited_effect;+ while !effect.is_none() {+ effects_left_to_composite[effect.0 as usize] = true;+ effect = tree.effect_nodes[effect.0 as usize].parent;+ }+ let mut clips_left_to_composite = vec![false; tree.clip_nodes.len()];+ let mut clip = effect_clips.output_clip(composited_effect);+ while !clip.is_none() {+ clips_left_to_composite[clip.0 as usize] = true;+ clip = tree.clip_nodes[clip.0 as usize].parent;+ }+ (effects_left_to_composite, clips_left_to_composite)}fn replay_clip_of(clip: &crate::visual_context::ClipData) -> ReplayClip {@@ -727,8 +769,7 @@ fn replay_clip_of(clip: &crate::visual_context::ClipData) -> ReplayClip {}}-// An effect keeps its filters for as long as the tree keeps its structure, so a painter can key what it builds from-// them on the two.+// An effect keeps its filters for as long as the tree keeps its structure.fn layer_filter_cache_key(tree: &VisualContextTree, effect: EffectNodeIndex) -> u64 {let mut hasher = crate::fast_hash::fast_hasher();hasher.write_u64(tree.structural_epoch);@@ -772,7 +813,24 @@ fn replay_layer_of(}}-// Whether the backdrop of a backdrop-filter effect is drawn by its box's masks rather than by the effect's own layer.+fn plain_layer_of_bounds(content_bounds: Option<FloatRect>) -> ReplayLayer {+ ReplayLayer {+ opacity: 1.0,+ blend_mode: libgfx_rust::CompositingAndBlendingOperator::Normal,+ can_draw_directly_for_lcd_text: false,+ filter_bytes: std::ptr::null(),+ filter_bytes_size: 0,+ backdrop_filter_bytes: std::ptr::null(),+ backdrop_filter_bytes_size: 0,+ backdrop_region: IntRect::default(),+ backdrop_corner_radii: CornerRadii::default(),+ backdrop_base_color: Color::TRANSPARENT,+ backdrop_blur_edge: OptionalFloatRect::none(),+ filter_cache_key: 0,+ content_bounds: OptionalFloatRect::from(content_bounds),+ }+}+fn backdrop_is_drawn_by_masks(tree: &VisualContextTree, effect: EffectNodeIndex) -> bool {let node = &tree.effect_nodes[effect.0 as usize];matches!(&node.data, EffectNodeData::Effects(effects) if effects.backdrop_filter.is_some())@@ -780,6 +838,28 @@ fn backdrop_is_drawn_by_masks(tree: &VisualContextTree, effect: EffectNodeIndex)&& matches!(&tree.effect_nodes[node.parent.0 as usize].data, EffectNodeData::Mask(mask) if mask.masks_backdrop)}+// Per mask, the first effect whose backdrop the mask draws as the outermost of the masks of its box, if any. An effect+// that no run of the list is inside has no output clip, so the mask draws none of its backdrop.+fn first_backdrop_drawn_by_masks_by_reading_mask(+ tree: &VisualContextTree,+ effect_clips: &EffectClipPlan,+) -> Vec<EffectNodeIndex> {+ let mut first_backdrop_by_reading_mask = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];+ let node_reading_backdrop_by_effect_index = tree.nodes_reading_the_backdrops_of_effects();+ for index in 0..tree.effect_nodes.len() {+ let effect = EffectNodeIndex(index as u32);+ if !backdrop_is_drawn_by_masks(tree, effect) || effect_clips.output_clip_if_participating(effect).is_none() {+ continue;+ }+ let first_backdrop =+ &mut first_backdrop_by_reading_mask[node_reading_backdrop_by_effect_index[index].0 as usize];+ if first_backdrop.is_none() {+ *first_backdrop = effect;+ }+ }+ first_backdrop_by_reading_mask+}+fn replay_mask_of(mask: &crate::visual_context::MaskData) -> ReplayMask {ReplayMask {rect: mask.rect,@@ -787,68 +867,155 @@ fn replay_mask_of(mask: &crate::visual_context::MaskData) -> ReplayMask {}}-// The whole device pixels covering `rect`, unless they reach past what an IntRect can hold, where-// converting would clamp the edges apart from each other.-fn int_rect_enclosing(rect: FloatRect) -> Option<IntRect> {+fn enclosing_int_rect_if_representable(rect: FloatRect) -> Option<IntRect> {let (left, top, right, bottom) = (rect.x.floor(),rect.y.floor(),rect.right().ceil(),rect.bottom().ceil(),);- let fits = |value: f32| value.is_finite() && value >= i32::MIN as f32 && value < i32::MAX as f32;+ let fits_in_int_rect = |value: f32| value.is_finite() && value >= i32::MIN as f32 && value < i32::MAX as f32;[left, top, right, bottom, right - left, bottom - top].into_iter()- .all(fits)+ .all(fits_in_int_rect).then(|| enclosing_int_rect(rect))}impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {+ fn clip_is_left_to_composite(&self, clip: ClipNodeIndex) -> bool {+ self.selection+ .clips_left_to_composite+ .is_some_and(|clips| clips.get(clip.0 as usize).copied().unwrap_or(false))+ || self+ .clips_left_to_composite_around_composited_effect+ .get(clip.0 as usize)+ .copied()+ .unwrap_or(false)+ }++ // Under dynamic MSAA, Skia rasters some content, such as antialiased rounded rects, differently into a layer than+ // into the surface below it, so the tiles get the effect's content inside a layer too.+ fn push_plain_layer_standing_in_for(&mut self, effect: EffectNodeIndex) {+ let spatial = self.tree.effect_nodes[effect.0 as usize].spatial;+ self.ensure_canvas_matrix_in_draw_space_of(spatial);+ let content_bounds = self.layer_content_bounds_in_effect_space(effect, spatial);+ self.painter.push_layer(&plain_layer_of_bounds(content_bounds));+ }++ // https://drafts.fxtf.org/filter-effects-2/#BackdropRoot+ // An element with a backdrop filter is a backdrop root, so what reads the backdrop inside it reads only the+ // element's own content, not the filtered backdrop its layer starts with.+ fn effect_isolates_content_from_filtered_backdrop(&mut self, effect: EffectNodeIndex) -> bool {+ let tree = self.tree;+ if !matches!(&tree.effect_nodes[effect.0 as usize].data, EffectNodeData::Effects(effects)+ if effects.backdrop_filter.is_some())+ || backdrop_is_drawn_by_masks(tree, effect)+ {+ return false;+ }+ let display_list = self.display_list;+ self.content_reads_layer_by_effect_index.get_or_insert_with(|| {+ let mut content_reads_layer_by_effect_index = vec![false; tree.effect_nodes.len()];+ let nearest_layer_by_effect_index =+ nearest_effects_at_or_above_where(tree, |effect, _| tree.effect_pushes_layer_at_replay(effect));+ let mut mark_layer_at_or_above_as_read = |effect: EffectNodeIndex| {+ let layer = nearest_layer_by_effect_index[effect.0 as usize];+ if !layer.is_none() {+ content_reads_layer_by_effect_index[layer.0 as usize] = true;+ }+ };+ let mut node_reading_backdrop_by_effect_index = None;+ for (index, node) in tree.effect_nodes.iter().enumerate() {+ let EffectNodeData::Effects(effects) = &node.data else {+ continue;+ };+ let reading_node = if effects.backdrop_filter.is_some() {+ node_reading_backdrop_by_effect_index+ .get_or_insert_with(|| tree.nodes_reading_the_backdrops_of_effects())[index]+ } else if effects.blend_mode != libgfx_rust::CompositingAndBlendingOperator::Normal {+ EffectNodeIndex(index as u32)+ } else {+ continue;+ };+ let effect_read_from = tree.effect_nodes[reading_node.0 as usize].parent;+ if !effect_read_from.is_none() {+ mark_layer_at_or_above_as_read(effect_read_from);+ }+ }+ for record in &display_list.summary().destination_blending_records {+ let effect_read_from = display_list.run(record.run_index as usize).context.effect;+ if !effect_read_from.is_none() {+ mark_layer_at_or_above_as_read(effect_read_from);+ }+ }+ content_reads_layer_by_effect_index+ })[effect.0 as usize]+ }++ fn effect_is_left_to_composite(&self, effect: EffectNodeIndex) -> bool {+ self.effects_left_to_composite_around_composited_effect+ .get(effect.0 as usize)+ .copied()+ .unwrap_or(false)+ }+fn effect_layer_is_pushed(&self, effect: EffectNodeIndex) -> bool {self.tree.effect_pushes_layer_at_replay(effect)&& !(self.selection.skip_root_isolation_layer && self.tree.root_isolation_effect == Some(effect))}- fn ensure_ctm_space(&mut self, spatial: SpatialNodeIndex) {- let space = self.world.draw_space[spatial.0 as usize];- if self.current_ctm_space == Some(space) {+ fn ensure_canvas_matrix_in_draw_space_of(&mut self, spatial: SpatialNodeIndex) {+ let draw_space = self.world.draw_space[spatial.0 as usize];+ if self.draw_space_of_canvas_matrix == Some(draw_space) {return;}- self.painter.set_matrix(&self.world.to_root[space.0 as usize]);- self.current_ctm_space = Some(space);+ self.painter.set_matrix(&self.world.to_root[draw_space.0 as usize]);+ self.draw_space_of_canvas_matrix = Some(draw_space);}fn effect_geometry(&mut self, effect: EffectNodeIndex) -> EffectGeometry {- if !self.effect_geometry_is_known {- compute_effect_geometry(self.tree, self.command_runs, &self.world, &mut self.effect_geometry);- self.effect_geometry_is_known = true;+ if !self.effect_geometry_is_computed {+ compute_effect_geometry(+ self.tree,+ self.display_list.runs(),+ &self.world,+ &mut self.effect_geometry_by_effect_index,+ );+ self.effect_geometry_is_computed = true;}- self.effect_geometry[effect.0 as usize]+ self.effect_geometry_by_effect_index[effect.0 as usize]}- // The bounds hint for an effect's layer, in the effect's space.- fn layer_content_bounds(&mut self, effect: EffectNodeIndex, space: SpatialNodeIndex) -> Option<FloatRect> {+ fn layer_content_bounds_in_effect_space(+ &mut self,+ effect: EffectNodeIndex,+ effect_space: SpatialNodeIndex,+ ) -> Option<FloatRect> {let Extent::Within(content) = self.effect_geometry(effect).content else {return None;};- let to_root_matrix = self.world.draw_matrix(space);- if !to_root_matrix.is_2d_affine() {+ let effect_space_to_root = self.world.draw_matrix(effect_space);+ if !effect_space_to_root.is_2d_affine() {return None;}- let root_to_layer = to_root_matrix.extract_2d_affine().inverse()?;+ let root_to_layer = effect_space_to_root.extract_2d_affine().inverse()?;let margin_x = LAYER_CONTENT_MARGIN_IN_DEVICE_PIXELS * (root_to_layer.a().abs() + root_to_layer.c().abs());let margin_y = LAYER_CONTENT_MARGIN_IN_DEVICE_PIXELS * (root_to_layer.b().abs() + root_to_layer.d().abs());- let bounds = FloatRect::new(+ let content_bounds_with_margin = FloatRect::new(content.x - margin_x,content.y - margin_y,content.width + 2.0 * margin_x,content.height + 2.0 * margin_y,);- // Bounds that overflowed would clip away everything drawn into the layer.- [bounds.x, bounds.y, bounds.right(), bounds.bottom()]- .into_iter()- .all(f32::is_finite)- .then_some(bounds)+ let bounds_are_finite = [+ content_bounds_with_margin.x,+ content_bounds_with_margin.y,+ content_bounds_with_margin.right(),+ content_bounds_with_margin.bottom(),+ ]+ .into_iter()+ .all(f32::is_finite);+ bounds_are_finite.then_some(content_bounds_with_margin)}// https://drafts.fxtf.org/filter-effects-2/#backdrop-filter-operation@@ -858,36 +1025,43 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {// come after masking, so the outermost mask layer applies them too.fn backdrop_layer_of_outermost_mask(&self,- target_index: usize,+ mask_index_in_target_canvas_stack: usize,mask: &crate::visual_context::MaskData,) -> Option<ReplayLayer> {if !mask.masks_backdrop {return None;}let tree = self.tree;- let Applied::Effect(mask_effect) = self.target[target_index] else {+ let CanvasStackEntry::Effect(mask_effect) = self.target_canvas_stack[mask_index_in_target_canvas_stack] else {unreachable!("a mask is an effect");};let parent = tree.effect_nodes[mask_effect.0 as usize].parent;- if !parent.is_none()- && matches!(&tree.effect_nodes[parent.0 as usize].data, EffectNodeData::Mask(parent) if parent.masks_backdrop)- {+ let is_inside_outer_mask_of_backdrop = !parent.is_none()+ && matches!(&tree.effect_nodes[parent.0 as usize].data, EffectNodeData::Mask(data) if data.masks_backdrop);+ if is_inside_outer_mask_of_backdrop {return None;}- self.target[target_index + 1..].iter().find_map(|entry| {- let Applied::Effect(effect) = *entry else {- return None;- };- match &tree.effect_nodes[effect.0 as usize].data {- EffectNodeData::Effects(effects) if backdrop_is_drawn_by_masks(tree, effect) => {- let mut layer = replay_layer_of(effects, layer_filter_cache_key(tree, effect), None);- layer.backdrop_base_color = self.backdrop_base_color(mask_effect);- layer.backdrop_blur_edge = self.backdrop_blur_edge(effect);- Some(layer)- }+ let backdrop_effect_in_target_canvas_stack = self.target_canvas_stack[mask_index_in_target_canvas_stack + 1..]+ .iter()+ .find_map(|entry| match *entry {+ CanvasStackEntry::Effect(effect) if backdrop_is_drawn_by_masks(tree, effect) => Some(effect),_ => None,- }- })+ });+ // Compositing a mask's content enters the mask without the effect whose backdrop it draws.+ let backdrop_effect = backdrop_effect_in_target_canvas_stack.or_else(|| {+ let backdrop_effect = self+ .first_backdrop_drawn_by_masks_by_reading_mask+ .get_or_init(|| first_backdrop_drawn_by_masks_by_reading_mask(tree, self.effect_clips))+ [mask_effect.0 as usize];+ (!backdrop_effect.is_none()).then_some(backdrop_effect)+ })?;+ let EffectNodeData::Effects(effects) = &tree.effect_nodes[backdrop_effect.0 as usize].data else {+ unreachable!("a backdrop that masks draw is of an effects node");+ };+ let mut layer = replay_layer_of(effects, layer_filter_cache_key(tree, backdrop_effect), None);+ layer.backdrop_base_color = self.backdrop_base_color(mask_effect);+ layer.backdrop_blur_edge = self.backdrop_blur_edge(backdrop_effect);+ Some(layer)}// https://drafts.csswg.org/filter-effects-2/#backdrop-filter-operation@@ -908,7 +1082,17 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {else {return OptionalFloatRect::none();};- let mut edge = backdrop.region.to_float();+ let mut blur_edge = backdrop.region.to_float();+ if let Some(frame_rect) = self.selection.frame_edge_backdrop_blurs_mirror_at {+ let effect_to_target = self.world.draw_matrix(node.spatial);+ if effect_to_target.is_2d_affine()+ && self.replay_base_matrix.is_2d_affine()+ && let Some(target_to_effect) = effect_to_target.extract_2d_affine().inverse()+ {+ let frame_in_target = self.replay_base_matrix.extract_2d_affine().map_rect(frame_rect);+ blur_edge = blur_edge.intersected(target_to_effect.map_rect(frame_in_target));+ }+ }let mut clip = self.effect_clips.output_clip(effect);while !clip.is_none() {let clip_node = &tree.clip_nodes[clip.0 as usize];@@ -921,11 +1105,11 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {self.world.map_rect_between_spaces(rect, clip_node.spatial, node.spatial)}) {- edge = edge.intersected(clip_rect);+ blur_edge = blur_edge.intersected(clip_rect);}clip = clip_node.parent;}- OptionalFloatRect::from(Some(edge))+ OptionalFloatRect::from(Some(blur_edge))}// https://drafts.fxtf.org/filter-effects-2/#BackdropRoot@@ -951,11 +1135,10 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {}}- // Merge the clip and effect chains from leaf to root. Each effect goes immediately- // inside its output clip; reversing once produces the canvas stack in linear time.- fn build_target(&mut self, context: ContextRef) {+ // Each effect goes right inside its output clip.+ fn build_target_canvas_stack(&mut self, context: ContextRef) {let tree = self.tree;- self.target.clear();+ self.target_canvas_stack.clear();let mut clip = context.clip;let mut effect = context.effect;while !effect.is_none() {@@ -965,80 +1148,88 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {!clip.is_none(),"an effect's output clip lies on the context's clip chain");- self.target.push(Applied::Clip(clip));+ self.target_canvas_stack.push(CanvasStackEntry::Clip(clip));clip = tree.clip_nodes[clip.0 as usize].parent;}- self.target.push(Applied::Effect(effect));+ self.target_canvas_stack.push(CanvasStackEntry::Effect(effect));effect = node.parent;}while !clip.is_none() {- self.target.push(Applied::Clip(clip));+ self.target_canvas_stack.push(CanvasStackEntry::Clip(clip));clip = tree.clip_nodes[clip.0 as usize].parent;}- self.target.reverse();+ self.target_canvas_stack.reverse();}- // Contexts in the same effect share every layer. Their clip chains meet at or below- // that effect's output clip, so only the trailing clips can need to be replaced.- fn build_target_clip_suffix(&mut self, mut current: ClipNodeIndex, mut target: ClipNodeIndex) -> usize {- self.target.clear();- let mut current_depth = self.culling.clip_depth(current);- let mut target_depth = self.culling.clip_depth(target);+ // Contexts in one effect share every layer, and their clip chains meet at or below the effect's output clip.+ fn build_target_clip_suffix(&mut self, mut entered_clip: ClipNodeIndex, mut target_clip: ClipNodeIndex) -> usize {+ self.target_canvas_stack.clear();+ let mut entered_clip_depth = self.culling.clip_depth(entered_clip);+ let mut target_clip_depth = self.culling.clip_depth(target_clip);let mut clips_to_pop = 0;- while current != target {- if current_depth >= target_depth {- current = self.tree.clip_nodes[current.0 as usize].parent;- current_depth -= 1;+ while entered_clip != target_clip {+ if entered_clip_depth >= target_clip_depth {+ entered_clip = self.tree.clip_nodes[entered_clip.0 as usize].parent;+ entered_clip_depth -= 1;clips_to_pop += 1;} else {- self.target.push(Applied::Clip(target));- target = self.tree.clip_nodes[target.0 as usize].parent;- target_depth -= 1;+ self.target_canvas_stack.push(CanvasStackEntry::Clip(target_clip));+ target_clip = self.tree.clip_nodes[target_clip.0 as usize].parent;+ target_clip_depth -= 1;}}- self.target.reverse();- let common_prefix_length = self.applied.len() - clips_to_pop;+ self.target_canvas_stack.reverse();+ let common_prefix_length = self.canvas_stack.len() - clips_to_pop;debug_assert!(- self.applied[common_prefix_length..]+ self.canvas_stack[common_prefix_length..].iter()- .all(|entry| matches!(entry, Applied::Clip(_)))+ .all(|entry| matches!(entry, CanvasStackEntry::Clip(_))));common_prefix_length}- fn restore_to_length(&mut self, length: usize) {+ fn restore_canvas_stack_to_length(&mut self, length: usize) {let tree = self.tree;- self.applied_context = None;- while self.applied.len() > length {- match self.applied.pop().expect("applied entries are not empty") {- Applied::Clip(_) => {+ self.clip_and_effect_of_canvas_stack = None;+ while self.canvas_stack.len() > length {+ match self.canvas_stack.pop().expect("the canvas stack is not empty") {+ CanvasStackEntry::Clip(clip) if self.clip_is_left_to_composite(clip) => {}+ CanvasStackEntry::Clip(_) => {self.painter.pop();- self.current_ctm_space = None;+ self.draw_space_of_canvas_matrix = None;+ }+ CanvasStackEntry::Effect(effect) if self.effect_is_left_to_composite(effect) => {+ if self.effect_layer_is_pushed(effect) {+ self.painter.pop();+ self.draw_space_of_canvas_matrix = None;+ }}- Applied::Effect(effect) => {+ CanvasStackEntry::Effect(effect) => {let node = &tree.effect_nodes[effect.0 as usize];match &node.data {EffectNodeData::Effects(_) => {if self.effect_layer_is_pushed(effect) {+ if self.effect_isolates_content_from_filtered_backdrop(effect) {+ self.painter.pop();+ }self.painter.pop();- self.current_ctm_space = None;+ self.draw_space_of_canvas_matrix = None;}}EffectNodeData::Mask(mask) => {- self.ensure_ctm_space(node.spatial);+ self.ensure_canvas_matrix_in_draw_space_of(node.spatial);self.painter.begin_mask_content(&replay_mask_of(mask));- if let Some(content) = self.list.declared_mask_content(effect) {+ if let Some(content) = self.list_replay.declared_mask_content(effect) {let records_context = RecordsContext {- list: &self.list,+ list_replay: &self.list_replay,frame: self.frame,- clip_space_matrix: &|_| None,+ to_root_matrix_of_inline_clip_space: &|_| None,};replay_records(content, &records_context, &mut *self.painter);}self.painter.pop_mask();- self.current_ctm_space = None;+ self.draw_space_of_canvas_matrix = None;}- // A marker touches no canvas state.EffectNodeData::BackgroundColorAnimation => {}EffectNodeData::Dead => unreachable!("a run never records under a tombstoned effect"),}@@ -1047,39 +1238,39 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {}}- // OPTIMIZATION: When walking down to layer-pushing effects (opacity/blend/filter layers and masks), check- // culling before pushing each one. The clips entered so far are those outside the layer, so- // testing the layer's whole output against them is conservative and valid. This avoids- // expensive saveLayer/restore cycles for off-screen elements.+ // OPTIMIZATION: A layer whose whole output the clips entered so far cull is not pushed, which spares off-screen+ // elements a saveLayer/restore. Those clips are all outside the layer, so the test is conservative.fn switch_to_context(&mut self, context: ContextRef, may_cull_layers: bool) -> SwitchResult {- if self.applied_context == Some((context.clip, context.effect)) {+ if self.clip_and_effect_of_canvas_stack == Some((context.clip, context.effect)) {return SwitchResult::Switched;}let tree = self.tree;- let (common_prefix_length, target_begin) = if let Some((clip, effect)) = self.applied_context+ let (common_prefix_length, first_target_entry_to_enter) = if let Some((clip, effect)) =+ self.clip_and_effect_of_canvas_stack&& effect == context.effect{(self.build_target_clip_suffix(clip, context.clip), 0)} else {- self.build_target(context);+ self.build_target_canvas_stack(context);let common_prefix_length = self- .applied+ .canvas_stack.iter()- .zip(&self.target)- .take_while(|(applied, target)| applied == target)+ .zip(&self.target_canvas_stack)+ .take_while(|(entered, target)| entered == target).count();(common_prefix_length, common_prefix_length)};- self.restore_to_length(common_prefix_length);+ self.restore_canvas_stack_to_length(common_prefix_length);- for i in target_begin..self.target.len() {- let entry = self.target[i];+ for target_entry_index in first_target_entry_to_enter..self.target_canvas_stack.len() {+ let entry = self.target_canvas_stack[target_entry_index];match entry {- Applied::Clip(clip) => {+ CanvasStackEntry::Clip(clip) if self.clip_is_left_to_composite(clip) => {}+ CanvasStackEntry::Clip(clip) => {let node = &tree.clip_nodes[clip.0 as usize];- self.ensure_ctm_space(node.spatial);+ self.ensure_canvas_matrix_in_draw_space_of(node.spatial);match &node.data {ClipNodeData::Rect(clip) => self.painter.push_clip(&replay_clip_of(clip)),ClipNodeData::Path(clip_path) => {@@ -1088,33 +1279,37 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {ClipNodeData::Dead => unreachable!("a run never records under a tombstoned clip"),}}- Applied::Effect(effect) => {+ CanvasStackEntry::Effect(effect) if self.effect_is_left_to_composite(effect) => {+ if self.effect_layer_is_pushed(effect) {+ self.push_plain_layer_standing_in_for(effect);+ }+ }+ CanvasStackEntry::Effect(effect) => {let node = &tree.effect_nodes[effect.0 as usize];if node.data.pushes_layer() && may_cull_layers {- let culled_by_layer = match self.effect_geometry(effect).output {+ let layer_output_is_culled = match self.effect_geometry(effect).output {Extent::Nothing => true,- Extent::Within(output) => match int_rect_enclosing(output) {+ Extent::Within(output) => match enclosing_int_rect_if_representable(output) {Some(output) => {- self.ensure_ctm_space(node.spatial);+ self.ensure_canvas_matrix_in_draw_space_of(node.spatial);self.painter.would_be_fully_clipped_by_painter(output)}None => false,},Extent::Anywhere => false,};- if culled_by_layer {- self.restore_to_length(common_prefix_length);- // The canvas is unwound to the shared prefix; clearing the applied- // context keeps the fast path from reusing the pre-cull context while- // the applied stack still enables prefix reuse on the next switch.+ if layer_output_is_culled {+ // Unwinding forgets the context of the canvas stack, so the next switch skips the fast+ // path yet still reuses the shared prefix.+ self.restore_canvas_stack_to_length(common_prefix_length);return SwitchResult::CulledByEffect;}}match &node.data {EffectNodeData::Effects(effects) => {if self.effect_layer_is_pushed(effect) {- self.ensure_ctm_space(node.spatial);- let content_bounds = self.layer_content_bounds(effect, node.spatial);+ self.ensure_canvas_matrix_in_draw_space_of(node.spatial);+ let content_bounds = self.layer_content_bounds_in_effect_space(effect, node.spatial);let mut layer =replay_layer_of(effects, layer_filter_cache_key(tree, effect), content_bounds);if backdrop_is_drawn_by_masks(tree, effect) {@@ -1134,51 +1329,56 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {&& tree.root_isolation_effect == Some(effect)&& !effects.needs_layer();self.painter.push_layer(&layer);+ if self.effect_isolates_content_from_filtered_backdrop(effect) {+ self.painter.push_layer(&plain_layer_of_bounds(content_bounds));+ }}}EffectNodeData::Mask(mask) => {- self.ensure_ctm_space(node.spatial);- let backdrop = self.backdrop_layer_of_outermost_mask(i, mask);- self.painter.push_mask(&replay_mask_of(mask), backdrop.as_ref());+ self.ensure_canvas_matrix_in_draw_space_of(node.spatial);+ let backdrop_layer = self.backdrop_layer_of_outermost_mask(target_entry_index, mask);+ self.painter.push_mask(&replay_mask_of(mask), backdrop_layer.as_ref());}EffectNodeData::BackgroundColorAnimation => {}EffectNodeData::Dead => unreachable!("a run never records under a tombstoned effect"),}}}- self.applied.push(entry);+ self.canvas_stack.push(entry);}- self.applied_context = Some((context.clip, context.effect));+ self.clip_and_effect_of_canvas_stack = Some((context.clip, context.effect));SwitchResult::Switched}- // A run enters its context once. Skipping a run with nothing to draw before entering its- // context spares the pushes.- fn execute_run(&mut self, run_index: usize) {- let run = self.command_runs[run_index];- self.execute_run_records(run_index, run.offset, run.offset + run.size);- }-- fn execute_record_span(&mut self, span: RecordSpan) {- let first_run = self- .command_runs- .partition_point(|run| run.offset + run.size <= span.begin_offset);- for run_index in first_run..self.command_runs.len() {- let run = self.command_runs[run_index];- if run.offset >= span.end_offset {- break;+ fn execute_record_span(&mut self, span: ListSpan) {+ let display_list = self.display_list;+ for (chunk_index, begin_offset, end_offset) in display_list.parts_of_span(span) {+ let chunk = display_list.chunk(chunk_index);+ let first_run_index_in_chunk = chunk.index_of_first_run_ending_after(begin_offset);+ for (run_index_in_chunk, run) in chunk.runs().iter().enumerate().skip(first_run_index_in_chunk) {+ if run.offset >= end_offset {+ break;+ }+ self.execute_run_records(+ display_list.first_run_of_chunk(chunk_index) + run_index_in_chunk,+ chunk_index,+ *run,+ run.offset.max(begin_offset),+ (run.offset + run.size).min(end_offset),+ );}- self.execute_run_records(- run_index,- run.offset.max(span.begin_offset),- (run.offset + run.size).min(span.end_offset),- );}}- fn execute_run_records(&mut self, run_index: usize, begin_offset: u32, end_offset: u32) {- let run = self.command_runs[run_index];+ fn execute_run_records(+ &mut self,+ run_index: usize,+ chunk_index: ChunkIndexInList,+ run: DisplayListCommandRun,+ begin_offset: u32,+ end_offset: u32,+ ) {if self.world.backface_culled[run.context.spatial.0 as usize] {return;}@@ -1191,64 +1391,107 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {if self.switch_to_context(run.context, true) == SwitchResult::CulledByEffect {return;}- self.ensure_ctm_space(run.context.spatial);+ self.ensure_canvas_matrix_in_draw_space_of(run.context.spatial);if self.painter.would_be_fully_clipped_by_painter(run.ink_bounds) {return;}- let records = &self.tape[begin_offset as usize..end_offset as usize];+ let display_list = self.display_list;+ let records = &display_list.chunk(chunk_index).records()[begin_offset as usize..end_offset as usize];let world = &self.world;- let clip_space_matrix = |space: SpatialNodeIndex| world.draw_matrix_if_known(space);+ let to_root_matrix_of_inline_clip_space = |space: SpatialNodeIndex| world.draw_matrix_if_known(space);let records_context = RecordsContext {- list: &self.list,+ list_replay: &self.list_replay,frame: self.frame,- clip_space_matrix: &clip_space_matrix,+ to_root_matrix_of_inline_clip_space: &to_root_matrix_of_inline_clip_space,};self.painter.execute_run(run_index, records, &records_context);}+ fn execute_selected_records_of_run(&mut self, run_index: usize) {+ let run_span = self.display_list.span_of_run(run_index);+ let Some(record_spans) = self.selection.record_spans else {+ self.execute_record_span(run_span);+ return;+ };+ let first_span_index = record_spans.partition_point(|span| span.end <= run_span.begin);+ for span in &record_spans[first_span_index..] {+ if span.begin >= run_span.end {+ break;+ }+ self.execute_record_span(ListSpan {+ begin: span.begin.max(run_span.begin),+ end: span.end.min(run_span.end),+ });+ }+ }++ fn spans_hold_records_sorted_by_depth(&self, record_spans: &[ListSpan]) -> bool {+ let display_list = self.display_list;+ let run_groups = display_list.run_groups(self.tree);+ record_spans.iter().any(|span| {+ display_list+ .parts_of_span(*span)+ .any(|(chunk_index, begin_offset, end_offset)| {+ let chunk = display_list.chunk(chunk_index);+ let first_run_index_in_chunk = chunk.index_of_first_run_ending_after(begin_offset);+ chunk+ .runs()+ .iter()+ .enumerate()+ .skip(first_run_index_in_chunk)+ .take_while(|(_, run)| run.offset < end_offset)+ .any(|(run_index_in_chunk, _)| {+ run_groups.run_is_sorted_by_depth(+ display_list.first_run_of_chunk(chunk_index) + run_index_in_chunk,+ )+ })+ })+ })+ }+fn execute(&mut self) {let tree = self.tree;- if let Some(record_spans) = self.selection.record_spans {- debug_assert!(!self.tree_has_sorting_contexts);+ if let Some(record_spans) = self.selection.record_spans+ && !(self.tree_sorts_planes_by_depth && self.spans_hold_records_sorted_by_depth(record_spans))+ {for span in record_spans {self.execute_record_span(*span);}- } else if !self.tree_has_sorting_contexts {- for run_index in 0..self.command_runs.len() {- self.execute_run(run_index);- }+ } else if !self.tree_sorts_planes_by_depth {+ self.execute_record_span(self.display_list.whole_span());} else {let root_isolation_effect = tree.root_isolation_effect;- let plane_clip_base_length = usize::from(root_isolation_effect.is_some());- let contexts = tree.resolve_sorting_contexts_in_order(&self.spatial_dependency_order);- let parent_by_node: Vec<SpatialNodeIndex> = tree.spatial_nodes.iter().map(|node| node.parent).collect();+ let canvas_stack_length_below_plane_clips = usize::from(root_isolation_effect.is_some());+ let sorting_contexts = tree.resolve_sorting_contexts_in_order(&self.spatial_dependency_order);+ let parent_by_spatial_node: Vec<SpatialNodeIndex> =+ tree.spatial_nodes.iter().map(|node| node.parent).collect();let leaf_to_context_palette = resolve_leaf_to_context_matrices(- &contexts,+ &sorting_contexts,&self.spatial_dependency_order,- &parent_by_node,+ &parent_by_spatial_node,&self.world.local,&self.world.flattens_inherited_transform,);- let plan = build_depth_sorted_replay_plan(- self.command_runs,- &contexts,+ let depth_sorted_plan = build_depth_sorted_replay_plan(+ self.display_list.runs(),+ &sorting_contexts,&self.world.to_root,&leaf_to_context_palette,&self.world.draw_space,&self.world.backface_culled,&self.culling,);- for step in &plan.steps {+ for step in &depth_sorted_plan.steps {match step.kind {DepthSortedReplayStepKind::RunSpan => {- let first_run = step.first_run as usize;- for run_index in first_run..first_run + step.run_count as usize {- self.execute_run(run_index);+ let first_run_index = step.first_run as usize;+ for run_index in first_run_index..first_run_index + step.run_count as usize {+ self.execute_selected_records_of_run(run_index);}}DepthSortedReplayStepKind::PushPlaneClip => {- // The root effect is a layer at the root of the effect tree under no- // clip, so the plane clip sits right above it.+ // The root isolation effect is the root of the effect tree under no clip, so the plane clip+ // sits right above it.if let Some(root_isolation_effect) = root_isolation_effect {self.switch_to_context(ContextRef {@@ -1259,82 +1502,276 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {false,);}- self.restore_to_length(plane_clip_base_length);+ self.restore_canvas_stack_to_length(canvas_stack_length_below_plane_clips);let vertex_offset = step.vertex_offset as usize;self.painter.push_device_space_plane_clip(- &plan.vertices[vertex_offset..vertex_offset + step.vertex_count as usize],+ &depth_sorted_plan.vertices[vertex_offset..vertex_offset + step.vertex_count as usize],);- self.current_ctm_space = None;+ self.draw_space_of_canvas_matrix = None;}DepthSortedReplayStepKind::PopPlaneClip => {- self.restore_to_length(plane_clip_base_length);+ self.restore_canvas_stack_to_length(canvas_stack_length_below_plane_clips);self.painter.pop();- self.current_ctm_space = None;+ self.draw_space_of_canvas_matrix = None;}}}}- self.restore_to_length(0);- // Node spaces were entered by setting the canvas matrix absolutely, outside any save, so the- // matrix the replay entered with must be handed back explicitly.+ self.restore_canvas_stack_to_length(0);+ // Spaces were entered by setting the canvas matrix outside any save, so no restore hands it back.let replay_base_matrix = self.replay_base_matrix;self.painter.set_matrix(&replay_base_matrix);}}-#[allow(clippy::too_many_arguments)]pub fn replay_display_list<Painter: ReplayPainter + ?Sized>(tree: &VisualContextTree,- tape: &[u8],- command_runs: &[DisplayListCommandRun],- effect_clips: &EffectClipPlan,+ display_list: &DisplayListStorage,root_group_color: Color,frame: &ReplayFrame<'_>,selection: ReplaySelection<'_>,painter: &mut Painter,) {- let replay_base_matrix = painter.canvas_matrix();- let mut scratch = take_replay_scratch_storage();- tree.fill_culling_scratch(&mut scratch.culling);- let mut driver = ReplayDriver {+ let mut driver = ReplayDriver::new(tree, display_list, root_group_color, frame, selection, painter);+ driver.execute();+ driver.return_scratch_storage();+}++impl<'a, Painter: ReplayPainter + ?Sized> ReplayDriver<'a, Painter> {+ fn new(+ tree: &'a VisualContextTree,+ display_list: &'a DisplayListStorage,+ root_group_color: Color,+ frame: &'a ReplayFrame<'a>,+ selection: ReplaySelection<'a>,+ painter: &'a mut Painter,+ ) -> Self {+ let replay_base_matrix = painter.canvas_matrix();+ let effect_clips = display_list.effect_clip_plan(tree);+ let mut scratch = take_replay_scratch_storage();+ tree.fill_culling_scratch(&mut scratch.culling);+ let (effects_left_to_composite, clips_left_to_composite) =+ effects_and_clips_left_to_composite_around(tree, effect_clips, selection.composited_effect);+ let mut driver = ReplayDriver {+ tree,+ display_list,+ list_replay: ListReplay::new(tree),+ frame,+ effect_clips,+ root_group_color,+ selection,+ painter,+ world: scratch.world,+ culling: scratch.culling,+ spatial_dependency_order: tree.spatial_dependency_order(),+ tree_sorts_planes_by_depth: tree.sorts_planes_by_depth(),+ replay_base_matrix,+ draw_space_of_canvas_matrix: None,+ canvas_stack: scratch.canvas_stack,+ target_canvas_stack: scratch.target_canvas_stack,+ clip_and_effect_of_canvas_stack: None,+ effect_geometry_by_effect_index: scratch.effect_geometry_by_effect_index,+ effect_geometry_is_computed: false,+ effects_left_to_composite_around_composited_effect: effects_left_to_composite,+ clips_left_to_composite_around_composited_effect: clips_left_to_composite,+ content_reads_layer_by_effect_index: None,+ first_backdrop_drawn_by_masks_by_reading_mask: std::cell::OnceCell::new(),+ };+ driver.world.fill(+ tree,+ &driver.spatial_dependency_order,+ frame.scroll_offsets,+ Some(replay_base_matrix),+ driver.selection.raster_root,+ );+ driver+ }++ fn return_scratch_storage(&mut self) {+ return_replay_scratch_storage(ReplayScratchStorage {+ world: std::mem::take(&mut self.world),+ culling: std::mem::take(&mut self.culling),+ canvas_stack: std::mem::take(&mut self.canvas_stack),+ target_canvas_stack: std::mem::take(&mut self.target_canvas_stack),+ effect_geometry_by_effect_index: std::mem::take(&mut self.effect_geometry_by_effect_index),+ });+ }++ // Compositing enters masks without replaying the declarations of their content ahead of them.+ fn declare_every_mask_content_of_list(&mut self) {+ let display_list = self.display_list;+ for declaration in &display_list.summary().mask_declarations {+ let (_, payload) = display_list.record_at(declaration.record.position);+ let command = read_command::<DeclareMaskContent>(payload);+ self.list_replay+ .declare_mask_content(command.effect, span_bytes(payload, command.content));+ }+ }+}++/// The compositing of rasters of a frame inside the effects the compositor applies to them as it composites them,+/// which it enters and leaves through the same context switches a replay of the list makes, so that every effect+/// composites as a replay of the list composites it.+pub struct CompositingInsideEffects<'d, 'a, Painter: ReplayPainter + ?Sized> {+ driver: &'d mut ReplayDriver<'a, Painter>,+ canvas_matrix_of_raster_pixels: FloatMatrix4x4,+ canvas_stack_lengths_inside_entered_effects: Vec<usize>,+}++impl<Painter: ReplayPainter + ?Sized> CompositingInsideEffects<'_, '_, Painter> {+ /// Enters `effect` from the innermost effect entered so far, which is one of the effects around it.+ pub fn enter_effect(&mut self, effect: EffectNodeIndex) {+ let node = &self.driver.tree.effect_nodes[effect.0 as usize];+ let context = ContextRef {+ spatial: node.spatial,+ clip: self.driver.effect_clips.output_clip(effect),+ effect,+ };+ self.driver.switch_to_context(context, false);+ self.canvas_stack_lengths_inside_entered_effects+ .push(self.driver.canvas_stack.len());+ }++ /// Leaves the innermost effect entered, which composites what was drawn inside it.+ pub fn leave_effect(&mut self) {+ self.canvas_stack_lengths_inside_entered_effects.pop();+ self.return_to_innermost_entered_effect();+ }++ fn return_to_innermost_entered_effect(&mut self) {+ let canvas_stack_length_inside_innermost_effect = self+ .canvas_stack_lengths_inside_entered_effects+ .last()+ .copied()+ .unwrap_or(0);+ self.driver+ .restore_canvas_stack_to_length(canvas_stack_length_inside_innermost_effect);+ }++ /// Draws the pixels of `source_rect` of a raster over `target_rect` of the surface, within `clips` of the surface,+ /// inside the innermost effect entered.+ pub fn draw_raster(+ &mut self,+ surface: *mut std::ffi::c_void,+ source_rect: IntRect,+ target_rect: IntRect,+ clips: CompositeClipsOfRaster<'_>,+ target_to_surface: Option<AffineTransform>,+ ) {+ self.draw_at_raster_pixels_inside_innermost_effect(clips, target_to_surface, |painter| {+ painter.draw_surface(&SurfaceDraw {+ surface,+ source_rect,+ target_rect,+ filtered: target_to_surface.is_some(),+ });+ });+ }++ /// Fills `rect` of the surface with `color` over what is below, within `clips` of the surface, inside the+ /// innermost effect entered, as a raster all of that color would draw.+ pub fn fill_rect(+ &mut self,+ rect: IntRect,+ color: Color,+ clips: CompositeClipsOfRaster<'_>,+ rect_to_surface: Option<AffineTransform>,+ ) {+ self.draw_at_raster_pixels_inside_innermost_effect(clips, rect_to_surface, |painter| {+ painter.fill_rect(&ResolvedFillRect {+ rect,+ color,+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ });+ });+ }++ /// Draws through `drawn_to_raster_pixels`, which maps what `draw` draws to the surface's pixels, where it does not+ /// draw at them, within `clips`, which are at them.+ fn draw_at_raster_pixels_inside_innermost_effect(+ &mut self,+ clips: CompositeClipsOfRaster<'_>,+ drawn_to_raster_pixels: Option<AffineTransform>,+ draw: impl FnOnce(&mut Painter),+ ) {+ self.return_to_innermost_entered_effect();+ self.driver.painter.set_matrix(&self.canvas_matrix_of_raster_pixels);+ self.driver.draw_space_of_canvas_matrix = None;+ let clips_to_push = clips+ .rect+ .map(|rect| (rect, CornerRadii::default()))+ .into_iter()+ .chain(clips.rounded_rects.iter().copied());+ let mut pushed_clip_count = 0;+ for (rect, corner_radii) in clips_to_push {+ self.driver.painter.push_clip(&ReplayClip {+ rect: rect.to_float(),+ corner_radii,+ mode: ClipMode::Intersect,+ });+ pushed_clip_count += 1;+ }+ if let Some(drawn_to_raster_pixels) = drawn_to_raster_pixels {+ let matrix = self+ .canvas_matrix_of_raster_pixels+ .multiplied(libgfx_rust::affine_to_matrix(drawn_to_raster_pixels));+ self.driver.painter.set_matrix(&matrix);+ }+ draw(self.driver.painter);+ for _ in 0..pushed_clip_count {+ self.driver.painter.pop();+ }+ }++ /// Replays the records within `span` inside the innermost effect entered, which they are recorded within.+ pub fn replay_records(&mut self, span: ListSpan) {+ self.return_to_innermost_entered_effect();+ self.driver.execute_record_span(span);+ }+}++/// The clips a raster is composited within, in the pixels of the surface it is composited into: a rect, and rounded+/// rects within it.+#[derive(Clone, Copy, Default)]+pub struct CompositeClipsOfRaster<'a> {+ pub rect: Option<IntRect>,+ pub rounded_rects: &'a [(IntRect, CornerRadii)],+}++/// Composites rasters of the frame into the painter's surface through `composite`, which draws them at the painter's+/// matrix and enters effects as a replay of the list under that matrix would, outside the root isolation layer, which+/// the surface stands for.+pub fn composite_inside_effects<Painter: ReplayPainter + ?Sized>(+ tree: &VisualContextTree,+ display_list: &DisplayListStorage,+ root_group_color: Color,+ frame: &ReplayFrame<'_>,+ painter: &mut Painter,+ composite: impl FnOnce(&mut CompositingInsideEffects<'_, '_, Painter>),+) {+ let canvas_matrix_of_raster_pixels = painter.canvas_matrix();+ let mut driver = ReplayDriver::new(tree,- tape,- command_runs,- list: ListReplay::new(tree),- frame,- effect_clips,+ display_list,root_group_color,- selection,+ frame,+ ReplaySelection {+ skip_root_isolation_layer: true,+ ..ReplaySelection::default()+ },painter,- world: scratch.world,- culling: scratch.culling,- spatial_dependency_order: tree.spatial_dependency_order(),- tree_has_sorting_contexts: tree.spatial_nodes.iter().any(|node| {- matches!(&node.data, SpatialData::Transform(transform) if transform.sorting_context_root_index.is_some())- }),- replay_base_matrix,- current_ctm_space: None,- applied: scratch.applied,- target: scratch.target,- applied_context: None,- effect_geometry: scratch.effect_geometry,- effect_geometry_is_known: false,- };- driver.world.fill(- tree,- &driver.spatial_dependency_order,- frame.scroll_offsets,- Some(replay_base_matrix),);- driver.execute();- return_replay_scratch_storage(ReplayScratchStorage {- world: std::mem::take(&mut driver.world),- culling: std::mem::take(&mut driver.culling),- applied: std::mem::take(&mut driver.applied),- target: std::mem::take(&mut driver.target),- effect_geometry: std::mem::take(&mut driver.effect_geometry),- });+ driver.declare_every_mask_content_of_list();+ let mut compositing = CompositingInsideEffects {+ driver: &mut driver,+ canvas_matrix_of_raster_pixels,+ canvas_stack_lengths_inside_entered_effects: Vec::new(),+ };+ composite(&mut compositing);+ driver.restore_canvas_stack_to_length(0);+ driver.painter.set_matrix(&canvas_matrix_of_raster_pixels);+ driver.return_scratch_storage();}#[cfg(test)]@@ -1342,6 +1779,7 @@ mod tests {use super::*;use crate::display_list::commands::ContextRef;use crate::display_list::commands::VISUAL_VIEWPORT_NODE_INDEX;+ use crate::display_list::storage::ListPosition;use crate::node_slot_id::NodeSlotId;use crate::visual_context::{BackdropFilterData, BackfaceVisibilityData, ClipData, ClipMode, EffectsData, MaskData, MaskLayerOrigin,@@ -1458,6 +1896,7 @@ mod tests {layer_content_bounds: Vec<Option<FloatRect>>,layers_that_can_draw_directly_for_lcd_text: Vec<bool>,backdrop_base_colors: Vec<Color>,+ masks_drawing_backdrop: Vec<bool>,run_record_sizes: Vec<usize>,filled_rects: Vec<IntRect>,begun_isolated_groups: usize,@@ -1472,6 +1911,7 @@ mod tests {layer_content_bounds: Vec::new(),layers_that_can_draw_directly_for_lcd_text: Vec::new(),backdrop_base_colors: Vec::new(),+ masks_drawing_backdrop: Vec::new(),run_record_sizes: Vec::new(),filled_rects: Vec::new(),begun_isolated_groups: 0,@@ -1504,8 +1944,9 @@ mod tests {self.backdrop_base_colors.push(layer.backdrop_base_color);}}- fn push_mask(&mut self, mask: &ReplayMask, _backdrop: Option<&ReplayLayer>) {+ fn push_mask(&mut self, mask: &ReplayMask, backdrop: Option<&ReplayLayer>) {self.events.push(PainterEvent::PushMask(mask.rect));+ self.masks_drawing_backdrop.push(backdrop.is_some());}fn begin_mask_content(&mut self, _mask: &ReplayMask) {}fn pop_mask(&mut self) {@@ -1546,6 +1987,7 @@ mod tests {VectorImageReplay::Skipped}fn end_vector_image(&mut self) {}+ fn draw_surface(&mut self, _draw: &SurfaceDraw) {}fn execute_run<'t>(&mut self, run_index: usize, records: &'t [u8], _context: &RecordsContext<'_, 't>) {self.events.push(PainterEvent::Run(run_index));@@ -1641,7 +2083,7 @@ mod tests {fn replay_test_records(records: &[u8],- clip_space_matrix: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+ to_root_matrix_of_inline_clip_space: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,painter: &mut RecordingPainter,) {let tree = identity_tree();@@ -1650,20 +2092,42 @@ mod tests {replay_records(records,&RecordsContext {- list: &list,+ list_replay: &list,frame: &frame,- clip_space_matrix,+ to_root_matrix_of_inline_clip_space,},painter,);}+ fn list_of_one_chunk(record_bytes: &[u8], runs: &[DisplayListCommandRun]) -> std::sync::Arc<DisplayListStorage> {+ DisplayListStorage::of_chunks(vec![std::sync::Arc::new(+ crate::display_list::storage::ListChunk::copied(record_bytes, runs, 0),+ )])+ .unwrap()+ }++ // Lays the runs over a record each, as a recorded list holds no run without a record.+ fn list_of_runs(runs: &[DisplayListCommandRun]) -> std::sync::Arc<DisplayListStorage> {+ let mut builder = crate::display_list::builder::DisplayListBuilder::new();+ builder.append(&fill_rect_command(visible_bounds()), &[], ContextRef::default());+ let record = builder.bytes();+ let runs: Vec<DisplayListCommandRun> = runs+ .iter()+ .enumerate()+ .map(|(index, run)| DisplayListCommandRun {+ offset: (index * record.len()) as u32,+ size: record.len() as u32,+ ..*run+ })+ .collect();+ list_of_one_chunk(&record.repeat(runs.len()), &runs)+ }+fn replay(tree: &VisualContextTree, runs: &[DisplayListCommandRun], painter: &mut RecordingPainter) {replay_display_list(tree,- &[],- runs,- &EffectClipPlan::new(tree, runs).unwrap(),+ &list_of_runs(runs),Color::TRANSPARENT,&ReplayFrame::unscrolled(0),ReplaySelection::default(),@@ -1681,13 +2145,11 @@ mod tests {run.offset = index as u32 * run_size;run.size = run_size;}- let tape = vec![0u8; runs.len() * run_size as usize];+ let record_bytes = vec![0u8; runs.len() * run_size as usize];let mut painter = RecordingPainter::new();replay_display_list(tree,- &tape,- runs,- &EffectClipPlan::new(tree, runs).unwrap(),+ &list_of_one_chunk(&record_bytes, runs),Color::TRANSPARENT,&ReplayFrame::unscrolled(0),selection,@@ -1715,16 +2177,11 @@ mod tests {};let mut runs =[clipped, in_layer, clipped].map(|context| run(VISUAL_VIEWPORT_NODE_INDEX, context, visible_bounds()));- let spans = [- RecordSpan {- begin_offset: 0,- end_offset: 8,- },- RecordSpan {- begin_offset: 16,- end_offset: 24,- },- ];+ let span = |begin, end| ListSpan {+ begin: ListPosition::new(ChunkIndexInList(0), begin),+ end: ListPosition::new(ChunkIndexInList(0), end),+ };+ let spans = [span(0, 8), span(16, 24)];let painter = replay_selection(&tree,&mut runs,@@ -1745,6 +2202,96 @@ mod tests {);}+ #[test]+ fn a_replay_enters_and_leaves_contexts_across_chunks_as_it_does_across_runs() {+ let mut tree = identity_tree();+ let rect = FloatRect::new(0.0, 0.0, 100.0, 100.0);+ let clip = root_clip(&mut tree, rect);+ let layer = effect_under(&mut tree, effects(0.5), EffectNodeIndex::NONE, ClipNodeIndex::NONE);+ let clipped = ContextRef {+ clip,+ ..ContextRef::default()+ };+ let in_layer = ContextRef {+ effect: layer,+ ..ContextRef::default()+ };+ let mut runs = [clipped, in_layer, in_layer, clipped]+ .map(|context| run(VISUAL_VIEWPORT_NODE_INDEX, context, visible_bounds()));+ for (index, run) in runs.iter_mut().enumerate() {+ run.offset = index as u32 * 16;+ run.size = 16;+ }+ let record_bytes = vec![0u8; 64];+ let one_chunk = list_of_one_chunk(&record_bytes, &runs);+ let two_chunks = DisplayListStorage::of_chunks(vec![+ std::sync::Arc::new(crate::display_list::storage::ListChunk::copied(+ &record_bytes[..32],+ &runs[..2],+ 0,+ )),+ std::sync::Arc::new(crate::display_list::storage::ListChunk::copied(+ &record_bytes[32..],+ &runs[2..],+ 32,+ )),+ ])+ .unwrap();+ let events_of = |list: &DisplayListStorage, spans: Option<&[ListSpan]>| {+ let mut painter = RecordingPainter::new();+ replay_display_list(+ &tree,+ list,+ Color::TRANSPARENT,+ &ReplayFrame::unscrolled(0),+ ReplaySelection {+ record_spans: spans,+ ..Default::default()+ },+ &mut painter,+ );+ painter+ .events+ .retain(|event| !matches!(event, PainterEvent::SetMatrix(_)));+ (painter.events, painter.run_record_sizes)+ };+ let whole_list = events_of(&one_chunk, None);+ assert_eq!(+ whole_list.0,+ vec![+ PainterEvent::PushClip(rect),+ PainterEvent::Run(0),+ PainterEvent::Pop,+ PainterEvent::PushLayer(0.5),+ PainterEvent::Run(1),+ PainterEvent::Run(2),+ PainterEvent::Pop,+ PainterEvent::PushClip(rect),+ PainterEvent::Run(3),+ PainterEvent::Pop,+ ]+ );+ assert_eq!(events_of(&two_chunks, None), whole_list);+ // A span that starts and ends inside runs plays the same records whichever chunks hold them.+ let span = |begin: ListPosition, end: ListPosition| [ListSpan { begin, end }];+ assert_eq!(+ events_of(+ &two_chunks,+ Some(&span(+ ListPosition::new(ChunkIndexInList(0), 24),+ ListPosition::new(ChunkIndexInList(1), 8)+ ))+ ),+ events_of(+ &one_chunk,+ Some(&span(+ ListPosition::new(ChunkIndexInList(0), 24),+ ListPosition::new(ChunkIndexInList(0), 40)+ ))+ )+ );+ }+#[test]fn a_span_replay_plays_the_records_of_a_run_inside_the_span() {let mut runs = [ClipNodeIndex::NONE, ClipNodeIndex::NONE]@@ -1752,9 +2299,9 @@ mod tests {runs[1].context.effect = EffectNodeIndex(0);let mut tree = identity_tree();effect_under(&mut tree, effects(1.0), EffectNodeIndex::NONE, ClipNodeIndex::NONE);- let spans = [RecordSpan {- begin_offset: 8,- end_offset: 24,+ let spans = [ListSpan {+ begin: ListPosition::new(ChunkIndexInList(0), 8),+ end: ListPosition::new(ChunkIndexInList(0), 24),}];let painter = replay_selection(&tree,@@ -1821,7 +2368,6 @@ mod tests {visible_bounds(),)});- let effect_clips = EffectClipPlan::new(&tree, &runs).unwrap();let white = Color::from_rgb(255, 255, 255);for (color, allows_lcd_text, expected) in [@@ -1832,9 +2378,7 @@ mod tests {let mut painter = RecordingPainter::new();replay_display_list(&tree,- &[],- &runs,- &effect_clips,+ &list_of_runs(&runs),color,&ReplayFrame::unscrolled(0),ReplaySelection {@@ -1868,19 +2412,19 @@ mod tests {],);// The clip lands on the command, at (3, 5) in its space.- let clip_space_matrix = translation_matrix(102.0, 203.0, 0.0);+ let to_root_matrix_of_inline_clip_space = translation_matrix(102.0, 203.0, 0.0);let mut painter = RecordingPainter::new();let command_space_matrix = painter.base_matrix;replay_test_records(builder.bytes(),- &|space| (space == clip_space).then_some(clip_space_matrix),+ &|space| (space == clip_space).then_some(to_root_matrix_of_inline_clip_space),&mut painter,);assert_eq!(painter.events,vec![PainterEvent::PushClip(clip_rect),- PainterEvent::SetMatrix(clip_space_matrix),+ PainterEvent::SetMatrix(to_root_matrix_of_inline_clip_space),PainterEvent::PushClip(clip_rect),PainterEvent::SetMatrix(command_space_matrix),PainterEvent::Pop,@@ -1963,11 +2507,11 @@ mod tests {.in_space(clip_space),],);- let clip_space_matrix = translation_matrix(0.0, -50.0, 0.0);+ let to_root_matrix_of_inline_clip_space = translation_matrix(0.0, -50.0, 0.0);let mut painter = RecordingPainter::new();replay_test_records(builder.bytes(),- &|space| (space == clip_space).then_some(clip_space_matrix),+ &|space| (space == clip_space).then_some(to_root_matrix_of_inline_clip_space),&mut painter,);assert_eq!(painter.events, vec![]);@@ -2110,8 +2654,6 @@ mod tests {);}- // A layer spanning content far apart must not be culled through a clamped conversion of its- // bounds, whose edges would no longer enclose the visible part.#[test]fn a_layer_too_wide_for_device_pixel_bounds_is_not_culled() {let mut tree = identity_tree();@@ -2168,8 +2710,7 @@ mod tests {painter.fully_clipped_x = 999;let base = painter.base_matrix;replay(&tree, &runs, &mut painter);- // Inside the layer the painter still culls the run by its own ink; a real canvas clip has- // grown by the blur there.+ // Inside the layer this painter still culls the run by its ink, where a real canvas clip grows by the blur.assert_eq!(painter.events,vec![@@ -2191,8 +2732,7 @@ mod tests {}}- // A layer's bounds are its content plus the margin it keeps for antialiasing, in its own units.- fn with_margin(rect: FloatRect, margin: f32) -> FloatRect {+ fn inflated_by_margin(rect: FloatRect, margin: f32) -> FloatRect {FloatRect::new(rect.x - margin,rect.y - margin,@@ -2236,8 +2776,8 @@ mod tests {assert_eq!(painter.layer_content_bounds,[- Some(with_margin(FloatRect::new(-3.0, -3.0, 33.0, 18.0), 2.0)),- Some(with_margin(FloatRect::new(0.0, 0.0, 10.0, 10.0), 2.0)),+ Some(inflated_by_margin(FloatRect::new(-3.0, -3.0, 33.0, 18.0), 2.0)),+ Some(inflated_by_margin(FloatRect::new(0.0, 0.0, 10.0, 10.0), 2.0)),]);}@@ -2253,7 +2793,7 @@ mod tests {replay(&tree, &runs, &mut painter);assert_eq!(painter.layer_content_bounds,- [Some(with_margin(FloatRect::new(0.0, 0.0, 40.0, 40.0), 4.0))]+ [Some(inflated_by_margin(FloatRect::new(0.0, 0.0, 40.0, 40.0), 4.0))]);}@@ -2302,9 +2842,6 @@ mod tests {);}- // An absolute child that skips its parent's overflow clip records under the parent's effect- // and the effect's output clip: the layer is entered once and the overflow clip moves in and- // out of it around the child's run.#[test]fn an_escaping_absolute_child_under_an_opacity_layer_pushes_the_layer_once() {let mut tree = identity_tree();@@ -2347,8 +2884,6 @@ mod tests {);}- // A box appends an effect with the widest clip a chain could take; tightening moves it back- // down to the clips its contexts share, so the layer is entered inside them.#[test]fn a_layer_nothing_escapes_is_entered_inside_the_clips_its_contexts_share() {let mut tree = identity_tree();@@ -2398,7 +2933,6 @@ mod tests {);}- // Two chains that differ only in their clip copies swap clips inside the shared layer.#[test]fn a_clip_inside_a_layer_is_re_pushed_when_switching_chains_without_popping_the_layer() {let mut tree = identity_tree();@@ -2535,8 +3069,6 @@ mod tests {);}- // A mask nested in a layer is entered inside its own output clip, which may sit above a clip- // pushed inside the layer; that clip is re-pushed inside the mask and the mask exits once.#[test]fn a_mask_nested_in_a_layer_pops_once_with_its_effect_index() {let mut tree = identity_tree();@@ -2594,6 +3126,71 @@ mod tests {);}+ #[test]+ fn a_mask_draws_only_the_backdrop_of_an_effect_its_list_draws_into() {+ let mut tree = identity_tree();+ let root = effect_under(&mut tree, effects(1.0), EffectNodeIndex::NONE, ClipNodeIndex::NONE);+ tree.root_isolation_effect = Some(root);+ let mask_drawing_backdrop = effect_under(+ &mut tree,+ EffectNodeData::Mask(MaskData {+ rect: visible_bounds(),+ kind: MaskKind::Alpha,+ origin: MaskLayerOrigin::CssMaskLayers,+ masks_backdrop: true,+ }),+ root,+ ClipNodeIndex::NONE,+ );+ let box_with_blurred_backdrop = effect_under(+ &mut tree,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: Some(BackdropFilterData {+ filter: std::sync::Arc::new(libgfx_rust::filter::Filter::blur(2.0, 2.0, None).serialize()),+ region: visible_bounds(),+ corner_radii: CornerRadii::default(),+ }),+ }),+ mask_drawing_backdrop,+ ClipNodeIndex::NONE,+ );+ let run_in = |effect| {+ run(+ VISUAL_VIEWPORT_NODE_INDEX,+ ContextRef {+ effect,+ ..ContextRef::default()+ },+ visible_bounds(),+ )+ };++ // A list from another process can draw under the mask and nothing inside the box.+ let mut painter = RecordingPainter::new();+ replay(&tree, &[run_in(mask_drawing_backdrop)], &mut painter);+ assert!(painter.events.contains(&PainterEvent::Run(0)));+ assert_eq!(painter.masks_drawing_backdrop, vec![false]);++ let runs = [run_in(box_with_blurred_backdrop)];+ let mut painter = RecordingPainter::new();+ composite_inside_effects(+ &tree,+ &list_of_runs(&runs),+ Color::TRANSPARENT,+ &ReplayFrame::unscrolled(0),+ &mut painter,+ |compositing| {+ compositing.enter_effect(mask_drawing_backdrop);+ compositing.leave_effect();+ },+ );+ assert_eq!(painter.masks_drawing_backdrop, vec![true]);+ }+#[test]fn a_layer_carries_its_backdrop_filter() {let filter = std::sync::Arc::new(vec![1, 2, 3]);@@ -2632,8 +3229,7 @@ mod tests {let mut tree = identity_tree();let root = effect_under(&mut tree, effects(1.0), EffectNodeIndex::NONE, ClipNodeIndex::NONE);tree.root_isolation_effect = Some(root);- // will-change: opacity keeps an effects node that pushes no layer, which is a backdrop root nonetheless.- let will_change = effect_under(&mut tree, effects(1.0), root, ClipNodeIndex::NONE);+ let will_change_without_layer = effect_under(&mut tree, effects(1.0), root, ClipNodeIndex::NONE);let backdrop = || {EffectNodeData::Effects(EffectsData {isolation: false,@@ -2648,7 +3244,7 @@ mod tests {})};let in_root = effect_under(&mut tree, backdrop(), root, ClipNodeIndex::NONE);- let in_will_change = effect_under(&mut tree, backdrop(), will_change, ClipNodeIndex::NONE);+ let in_will_change = effect_under(&mut tree, backdrop(), will_change_without_layer, ClipNodeIndex::NONE);let runs = [in_root, in_will_change].map(|effect| {run(VISUAL_VIEWPORT_NODE_INDEX,@@ -2663,9 +3259,7 @@ mod tests {let mut painter = RecordingPainter::new();replay_display_list(&tree,- &[],- &runs,- &EffectClipPlan::new(&tree, &runs).unwrap(),+ &list_of_runs(&runs),white,&ReplayFrame::unscrolled(0),ReplaySelection::default(),@@ -2674,10 +3268,64 @@ mod tests {assert_eq!(painter.backdrop_base_colors, vec![white, Color::TRANSPARENT]);}- // A background-color animation marker is an effect without canvas state: entering or leaving- // it neither pushes nor invalidates the matrix.#[test]- fn a_background_color_animation_marker_pushes_nothing() {+ fn a_replay_inside_a_composited_effect_leaves_out_the_effect_and_those_around_it() {+ let mut tree = identity_tree();+ let root = effect_under(&mut tree, effects(1.0), EffectNodeIndex::NONE, ClipNodeIndex::NONE);+ tree.root_isolation_effect = Some(root);+ let backdrop = || {+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: Some(BackdropFilterData {+ filter: std::sync::Arc::new(vec![1]),+ region: visible_bounds(),+ corner_radii: CornerRadii::default(),+ }),+ })+ };+ let composited_box = effect_under(&mut tree, backdrop(), root, ClipNodeIndex::NONE);+ let other_box = effect_under(&mut tree, backdrop(), root, ClipNodeIndex::NONE);+ let runs = [composited_box, other_box].map(|effect| {+ run(+ VISUAL_VIEWPORT_NODE_INDEX,+ ContextRef {+ effect,+ ..ContextRef::default()+ },+ visible_bounds(),+ )+ });+ let white = Color::from_rgb(255, 255, 255);+ let mut painter = RecordingPainter::new();+ replay_display_list(+ &tree,+ &list_of_runs(&runs),+ white,+ &ReplayFrame::unscrolled(0),+ ReplaySelection {+ composited_effect: Some(composited_box),+ ..ReplaySelection::default()+ },+ &mut painter,+ );+ // The composited box and the root isolation layer get plain layers standing in for theirs, and only the other+ // box reads a backdrop.+ assert_eq!(+ painter+ .events+ .iter()+ .filter(|event| matches!(event, PainterEvent::PushLayer(_)))+ .count(),+ 3+ );+ assert_eq!(painter.backdrop_base_colors, vec![white]);+ }++ #[test]+ fn a_background_color_animation_marker_pushes_nothing_and_keeps_the_matrix() {let mut tree = identity_tree();let layer = effect_under(&mut tree, effects(0.5), EffectNodeIndex::NONE, ClipNodeIndex::NONE);let marker = effect_under(@@ -2718,8 +3366,6 @@ mod tests {);}- // Culling the second of two new layers unwinds to the shared prefix, so the next run rebuilds- // from there.#[test]fn culling_the_second_of_two_new_layers_unwinds_to_the_shared_prefix() {let mut tree = identity_tree();@@ -2790,9 +3436,7 @@ mod tests {let base = painter.base_matrix;replay_display_list(&tree,- &[],- &runs,- &EffectClipPlan::new(&tree, &runs).unwrap(),+ &list_of_runs(&runs),Color::TRANSPARENT,&ReplayFrame {scroll_offsets: &scroll_offsets,@@ -2846,8 +3490,6 @@ mod tests {assert_eq!(painter.events.last(), Some(&PainterEvent::SetMatrix(base)));}- // Plane clips are pushed right above the root isolation layer: everything under it unwinds- // around each plane boundary, and the layer itself is entered once.#[test]fn plane_clips_unwind_to_the_root_isolation_layer() {let mut tree = identity_tree();diff --git a/Libraries/LibCompositing/Rust/src/display_list/storage.rs b/Libraries/LibCompositing/Rust/src/display_list/storage.rsindex 150a8a61aad..96d17bd801c 100644--- a/Libraries/LibCompositing/Rust/src/display_list/storage.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/storage.rs@@ -4,23 +4,28 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The tape of one display list: a recording this process made, with the visual context tree it was recorded against,-//! or a tape that came from another process and passed validation.+//! A display list as the chunks it is cut into, in paint order: chunks another process sent that passed validation, or+//! the chunks of a recording this process made, with the visual context tree it was recorded against.-use super::builder::RecordedDisplayList;+use super::builder::{COMMAND_ALIGNMENT, HEADER_SIZE, RecordedDisplayList, for_each_command, read_header};use super::chunks::{- Chunk, ChunkId, TapeChunks, TopLevelRecordReachingOutsideItsChunk, chunk_id,- top_level_records_reaching_outside_their_chunk,+ Chunk, ChunkId, DisplayListChunk, TopLevelRecordReachingOutsideRunContext, chunk_id, chunks_of,+ top_level_records_reaching_outside_run_context,};-use super::commands::{ContextRef, DisplayListCommandRun};+use super::commands::{ContextRef, DisplayListCommandHeader, DisplayListCommandRun, DisplayListCommandType};use super::effect_clip_plan::EffectClipPlan;-use super::summary::{DisplayListSummary, summarize};+use super::placement::RunGroups;+use super::summary::{DisplayListSummary, IndexedRecord, summarize, summary_of_pieces};+use super::tile_keys::{ChunkPlacedInRasterSpace, ContentHash, RecordTable};use super::validate::validate_tape;use crate::visual_context::VisualContextTree;use libipc_rust::wire::{Decode, Encode};-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, Mutex, OnceLock, PoisonError};-// Tape bytes in memory aligned for every command struct, which a Vec<u8> does not promise.+// Room for the spaces a chunk shows in and those of a moment before, which a scroll that comes back needs again.+const PLACEMENTS_CACHED_PER_CHUNK: usize = 4;++// Backed by u64 words, as a Vec<u8> does not promise the alignment command structs need.struct AlignedBytes {words: Vec<u64>,size: usize,@@ -34,6 +39,12 @@ impl AlignedBytes {Some(Self { words, size })}+ fn copied(bytes: &[u8]) -> Self {+ let mut copy = Self::try_zeroed(bytes.len()).expect("a recorded chunk fits in memory");+ copy.as_mut_slice().copy_from_slice(bytes);+ copy+ }+fn as_slice(&self) -> &[u8] {// SAFETY: The words hold at least `size` initialized bytes.unsafe { ak::slice_from_raw_parts(self.words.as_ptr().cast(), self.size) }@@ -45,98 +56,495 @@ impl AlignedBytes {}}-enum Tape {- Empty,- Recorded(Arc<RecordedDisplayList>),- Received {- bytes: AlignedBytes,- command_runs: Vec<DisplayListCommandRun>,+/// The index of a chunk among the chunks of a list, in paint order.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct ChunkIndexInList(pub u32);++/// The index of a run among the runs of a list, in paint order.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct RunIndexInList(pub u32);++/// The index of a run among the runs of the chunk that holds it.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct RunIndexInChunk(pub u32);++/// Where a record is in a display list: the chunk that holds it and its offset in that chunk. Records are painted in+/// the order of their positions.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct ListPosition {+ pub chunk_index: ChunkIndexInList,+ pub offset: u32,+}++impl ListPosition {+ pub const fn new(chunk_index: ChunkIndexInList, offset: u32) -> Self {+ Self { chunk_index, offset }+ }+}++/// The records of a display list from `begin` up to `end`, which can lie in a later chunk than `begin`. Every record of+/// the chunks between the two is in the span.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct ListSpan {+ pub begin: ListPosition,+ pub end: ListPosition,+}++impl ListSpan {+ pub fn contains(&self, position: ListPosition) -> bool {+ self.begin <= position && position < self.end+ }+}++enum RecordsAndRuns {+ Copied {+ records: AlignedBytes,+ runs: Vec<DisplayListCommandRun>,},+ // Only where the records start on a boundary that every command struct may start on.+ SharedWith(Arc<Chunk>),+}++/// A chunk that display lists hold, named by what it holds: its records in memory aligned for every command struct,+/// and its runs, which name the records by their offsets from where the chunk starts. Every list that names a chunk+/// shares it, and what is known of the chunk alone is worked out once, for all of them.+pub struct ListChunk {+ pub id: ChunkId,+ records_and_runs: RecordsAndRuns,+ records_reaching_outside_run_context: OnceLock<Vec<TopLevelRecordReachingOutsideRunContext>>,+ summary: OnceLock<DisplayListSummary>,+ record_table: OnceLock<RecordTable>,+ cached_placements_least_recently_used_first: Mutex<Vec<Arc<ChunkPlacedInRasterSpace>>>,+}++impl ListChunk {+ fn new(id: ChunkId, records_and_runs: RecordsAndRuns) -> Self {+ Self {+ id,+ records_and_runs,+ records_reaching_outside_run_context: OnceLock::new(),+ summary: OnceLock::new(),+ record_table: OnceLock::new(),+ cached_placements_least_recently_used_first: Mutex::new(Vec::new()),+ }+ }++ fn named_copy(records: AlignedBytes, runs: Vec<DisplayListCommandRun>) -> Self {+ Self::new(+ chunk_id(records.as_slice(), &runs, 0),+ RecordsAndRuns::Copied { records, runs },+ )+ }++ /// The chunk of a copy of `records`, which `runs` name by their offsets from `chunk_start`.+ pub fn copied(records: &[u8], runs: &[DisplayListCommandRun], chunk_start: u32) -> Self {+ Self::named_copy(+ AlignedBytes::copied(records),+ runs.iter()+ .map(|run| DisplayListCommandRun {+ offset: run.offset - chunk_start,+ ..*run+ })+ .collect(),+ )+ }++ /// The chunk of `chunk`, which this process made, with its id. It shares the records and runs of `chunk`, or holds+ /// a copy of them where the records do not start on a boundary that every command struct may start on.+ pub fn of_chunk_made_in_this_process(chunk: &Arc<Chunk>) -> Self {+ if !chunk.records.as_ptr().addr().is_multiple_of(COMMAND_ALIGNMENT) {+ return Self::new(+ chunk.id,+ RecordsAndRuns::Copied {+ records: AlignedBytes::copied(&chunk.records),+ runs: chunk.runs.clone(),+ },+ );+ }+ Self::new(chunk.id, RecordsAndRuns::SharedWith(chunk.clone()))+ }++ pub fn records(&self) -> &[u8] {+ match &self.records_and_runs {+ RecordsAndRuns::Copied { records, .. } => records.as_slice(),+ RecordsAndRuns::SharedWith(chunk) => &chunk.records,+ }+ }++ pub fn runs(&self) -> &[DisplayListCommandRun] {+ match &self.records_and_runs {+ RecordsAndRuns::Copied { runs, .. } => runs,+ RecordsAndRuns::SharedWith(chunk) => &chunk.runs,+ }+ }++ pub fn run_starting_at(&self, offset: u32) -> Option<&DisplayListCommandRun> {+ let runs = self.runs();+ runs.get(runs.partition_point(|run| run.offset < offset))+ .filter(|run| run.offset == offset)+ }++ /// The index of the first run whose records end past `offset`, which is the run that holds the record at `offset`+ /// where a run holds it.+ pub fn index_of_first_run_ending_after(&self, offset: u32) -> usize {+ self.runs()+ .partition_point(|run| run.offset.saturating_add(run.size) <= offset)+ }++ pub fn records_reaching_outside_run_context(&self) -> &[TopLevelRecordReachingOutsideRunContext] {+ self.records_reaching_outside_run_context+ .get_or_init(|| top_level_records_reaching_outside_run_context(self.records(), self.runs()))+ }++ pub fn summary(&self) -> &DisplayListSummary {+ self.summary.get_or_init(|| summarize(self.records(), self.runs()))+ }++ pub fn record_table(&self) -> &RecordTable {+ self.record_table+ .get_or_init(|| RecordTable::new(self.records(), self.runs()))+ }++ /// The cached placement of the chunk's records whose inputs hash to `placement_inputs_hash`, or else the one+ /// `place` makes, and whether it was made now.+ pub(crate) fn find_or_make_placement(+ &self,+ placement_inputs_hash: ContentHash,+ place: impl FnOnce() -> ChunkPlacedInRasterSpace,+ ) -> (Arc<ChunkPlacedInRasterSpace>, bool) {+ let mut placements = self+ .cached_placements_least_recently_used_first+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ if let Some(index) = placements+ .iter()+ .position(|placement| placement.placement_inputs_hash() == placement_inputs_hash)+ {+ let placement = placements.remove(index);+ placements.push(placement.clone());+ return (placement, false);+ }+ let placement = Arc::new(place());+ if placements.len() == PLACEMENTS_CACHED_PER_CHUNK {+ placements.remove(0);+ }+ placements.push(placement.clone());+ (placement, true)+ }++ /// The header and the payload of the record at `offset`.+ pub fn record_at(&self, offset: u32) -> (DisplayListCommandHeader, &[u8]) {+ let records = self.records();+ let offset = offset as usize;+ let header = read_header(&records[offset..]);+ let payload_start = offset + HEADER_SIZE;+ (+ header,+ &records[payload_start..payload_start + header.payload_size as usize],+ )+ }}pub struct DisplayListStorage {- tape: Tape,- // The tree a list this process recorded was recorded against, which it replays against and goes- // to the compositor with. A tape from another process comes without one.- visual_context_tree: Option<Arc<VisualContextTree>>,- // The placement of the runs' clips and effects. The list is replayed against trees of one structural epoch only, so- // one plan serves every replay.+ chunks_in_paint_order: Vec<Arc<ListChunk>>,+ first_run_index_of_each_chunk_then_run_count: Vec<u32>,+ tree_if_recorded_in_this_process: Option<Arc<VisualContextTree>>,+ // Lists replay against trees of one structural epoch only, so one plan serves every replay.effect_clip_plan: OnceLock<EffectClipPlan>,+ // One epoch fixes the tree structure run groups follow, but transforms decide which 3D sorting contexts sort their+ // planes by depth. The samples of a tree sort the same contexts unless a transform animation animates a plane of+ // one, so the groups are kept with the copy of the tree without the samples of the compositor's animations that+ // they were found to hold for, and found to hold again only for the samples of such an animation.+ cached_run_groups: Mutex<Option<(u64, Arc<RunGroups>)>>,summary: OnceLock<DisplayListSummary>,- chunks: OnceLock<TapeChunks>,}impl DisplayListStorage {- fn new(tape: Tape, visual_context_tree: Option<Arc<VisualContextTree>>, chunks: OnceLock<TapeChunks>) -> Arc<Self> {+ fn new(+ chunks_in_paint_order: Vec<Arc<ListChunk>>,+ tree_if_recorded_in_this_process: Option<Arc<VisualContextTree>>,+ ) -> Arc<Self> {+ let mut first_run_index_of_each_chunk_then_run_count = Vec::with_capacity(chunks_in_paint_order.len() + 1);+ let mut run_count = 0u32;+ for chunk in &chunks_in_paint_order {+ first_run_index_of_each_chunk_then_run_count.push(run_count);+ run_count += chunk.runs().len() as u32;+ }+ first_run_index_of_each_chunk_then_run_count.push(run_count);Arc::new(Self {- tape,- visual_context_tree,+ chunks_in_paint_order,+ first_run_index_of_each_chunk_then_run_count,+ tree_if_recorded_in_this_process,effect_clip_plan: OnceLock::new(),+ cached_run_groups: Mutex::new(None),summary: OnceLock::new(),- chunks,})}- pub fn bytes(&self) -> &[u8] {- match &self.tape {- Tape::Empty => &[],- Tape::Recorded(recorded) => &recorded.bytes,- Tape::Received { bytes, .. } => bytes.as_slice(),+ /// The list of `chunks`, which another process sent, in paint order. A list may name one chunk many times, and+ /// what is worked out of a list, such as its summary, holds what is worked out of each chunk once per time the list+ /// names it, so the records of the chunks, counted so, are limited as a list was limited when it was one tape.+ pub fn of_chunks(chunks: Vec<Arc<ListChunk>>) -> Result<Arc<Self>, &'static str> {+ let run_count = chunks.iter().map(|chunk| chunk.runs().len()).sum::<usize>();+ if u32::try_from(chunks.len()).is_err() || u32::try_from(run_count).is_err() {+ return Err("Display list has more chunks or runs than a list can hold");+ }+ let record_byte_count = chunks.iter().fold(0u64, |byte_count, chunk| {+ byte_count.saturating_add(chunk.records().len() as u64)+ });+ if record_byte_count > u64::from(u32::MAX) {+ return Err("Display list holds more bytes of records than a list can hold");}+ Ok(Self::new(chunks, None))}- pub fn command_runs(&self) -> &[DisplayListCommandRun] {- match &self.tape {- Tape::Empty => &[],- Tape::Recorded(recorded) => &recorded.command_runs,- Tape::Received { command_runs, .. } => command_runs,- }+ /// A list this process recorded against `visual_context_tree`.+ pub fn recorded(recorded: &RecordedDisplayList, visual_context_tree: Arc<VisualContextTree>) -> Arc<Self> {+ Self::new(+ chunks_of_recording(&recorded.bytes, &recorded.command_runs, &recorded.chunks),+ Some(visual_context_tree),+ )+ }++ /// An empty list, recorded against a tree with no node but the visual viewport.+ pub fn empty() -> Arc<Self> {+ Self::new(Vec::new(), Some(Arc::new(VisualContextTree::create_identity())))+ }++ /// The list of what `builder` recorded so far, cut into the chunks it ended, as tests build lists.+ #[cfg(test)]+ pub(crate) fn of_builder(builder: &super::builder::DisplayListBuilder) -> Arc<Self> {+ Self::new(+ chunks_of_recording(builder.bytes(), builder.command_runs(), builder.chunks()),+ None,+ )}+ pub fn chunks(&self) -> &[Arc<ListChunk>] {+ &self.chunks_in_paint_order+ }++ pub fn chunk(&self, index: ChunkIndexInList) -> &ListChunk {+ &self.chunks_in_paint_order[index.0 as usize]+ }++ /// Whether `other` holds chunks of the same ids in the same order.+ pub fn holds_same_chunks_in_same_order_as(&self, other: &Self) -> bool {+ self.chunks_in_paint_order.len() == other.chunks_in_paint_order.len()+ && self+ .chunks_in_paint_order+ .iter()+ .zip(&other.chunks_in_paint_order)+ .all(|(chunk, other_chunk)| chunk.id == other_chunk.id)+ }++ /// The tree a list this process recorded was recorded against, which it replays against and goes to the compositor+ /// with. A list from another process comes without one.pub fn visual_context_tree(&self) -> Option<&Arc<VisualContextTree>> {- self.visual_context_tree.as_ref()+ self.tree_if_recorded_in_this_process.as_ref()+ }++ pub fn byte_size(&self) -> usize {+ self.chunks_in_paint_order+ .iter()+ .map(|chunk| chunk.records().len())+ .sum()+ }++ pub fn run_count(&self) -> usize {+ *self+ .first_run_index_of_each_chunk_then_run_count+ .last()+ .expect("the run counts end with the total") as usize+ }++ /// The runs of the list in paint order.+ pub fn runs(&self) -> impl Iterator<Item = &DisplayListCommandRun> + Clone {+ self.chunks_in_paint_order.iter().flat_map(|chunk| chunk.runs().iter())+ }++ /// The index among the runs of the list of the first run of the chunk at `chunk_index`.+ pub fn first_run_of_chunk(&self, chunk_index: ChunkIndexInList) -> usize {+ self.first_run_index_of_each_chunk_then_run_count[chunk_index.0 as usize] as usize+ }++ /// The chunk that holds the run at `run_index` among the runs of the list, and the run's index in the chunk.+ pub fn chunk_of_run(&self, run_index: usize) -> (ChunkIndexInList, usize) {+ let chunk_index = self+ .first_run_index_of_each_chunk_then_run_count+ .partition_point(|&first_run_index| first_run_index as usize <= run_index)+ - 1;+ (+ ChunkIndexInList(chunk_index as u32),+ run_index - self.first_run_index_of_each_chunk_then_run_count[chunk_index] as usize,+ )+ }++ pub fn run(&self, run_index: usize) -> &DisplayListCommandRun {+ let (chunk_index, run_index_in_chunk) = self.chunk_of_run(run_index);+ &self.chunk(chunk_index).runs()[run_index_in_chunk]+ }++ /// The records of the run at `run_index`.+ pub fn span_of_run(&self, run_index: usize) -> ListSpan {+ let (chunk_index, run_index_in_chunk) = self.chunk_of_run(run_index);+ let run = &self.chunk(chunk_index).runs()[run_index_in_chunk];+ ListSpan {+ begin: ListPosition::new(chunk_index, run.offset),+ end: ListPosition::new(chunk_index, run.offset + run.size),+ }+ }++ /// The span of every record of the list.+ pub fn whole_span(&self) -> ListSpan {+ let end = match self.chunks_in_paint_order.last() {+ Some(last) => ListPosition::new(+ ChunkIndexInList(self.chunks_in_paint_order.len() as u32 - 1),+ last.records().len() as u32,+ ),+ None => ListPosition::default(),+ };+ ListSpan {+ begin: ListPosition::default(),+ end,+ }+ }++ /// The chunks that `span` reaches into, each with the offsets of the part of it in the span.+ pub fn parts_of_span(&self, span: ListSpan) -> impl Iterator<Item = (ChunkIndexInList, u32, u32)> + '_ {+ let first_chunk_index = span.begin.chunk_index.0;+ let end_chunk_index = (span.end.chunk_index.0 as usize + 1).min(self.chunks_in_paint_order.len()) as u32;+ (first_chunk_index..end_chunk_index.max(first_chunk_index)).filter_map(move |chunk_index| {+ let chunk_index = ChunkIndexInList(chunk_index);+ let begin = if chunk_index == span.begin.chunk_index {+ span.begin.offset+ } else {+ 0+ };+ let end = if chunk_index == span.end.chunk_index {+ span.end.offset+ } else {+ self.chunk(chunk_index).records().len() as u32+ };+ (begin < end).then_some((chunk_index, begin, end))+ })+ }++ /// The header and the payload of the record at `position`.+ pub fn record_at(&self, position: ListPosition) -> (DisplayListCommandHeader, &[u8]) {+ self.chunk(position.chunk_index).record_at(position.offset)}pub fn summary(&self) -> &DisplayListSummary {- self.summary- .get_or_init(|| summarize(self.bytes(), self.command_runs()))+ self.summary.get_or_init(|| {+ summary_of_pieces(self.chunks_in_paint_order.iter().enumerate().map(|(index, chunk)| {+ (+ chunk.summary(),+ self.first_run_index_of_each_chunk_then_run_count[index],+ ChunkIndexInList(index as u32),+ )+ }))+ })}pub fn effect_clip_plan(&self, tree: &VisualContextTree) -> &EffectClipPlan {self.effect_clip_plan.get_or_init(|| {- EffectClipPlan::new(tree, self.command_runs()).expect("a display list's runs name live nodes of its tree")+ EffectClipPlan::new(tree, self.runs()).expect("a display list's runs name live nodes of its tree")})}- pub fn chunks(&self) -> &TapeChunks {- self.chunks.get_or_init(|| {- let recorded_chunks = match &self.tape {- Tape::Recorded(recorded) => &recorded.chunks[..],- Tape::Empty | Tape::Received { .. } => &[],- };- TapeChunks::of_tape(self.bytes(), self.command_runs(), recorded_chunks)- })+ /// Whether `tree` can take the place of the tree the list was paired with: the plan of the clips of its effects+ /// that the list keeps, if it keeps one yet, is the plan of the list under `tree` too. A tree from another process+ /// can claim the structural epoch of the list and still nest its effects otherwise.+ pub fn effect_clip_plan_holds_under(&self, tree: &VisualContextTree) -> bool {+ let Some(kept_plan) = self.effect_clip_plan.get() else {+ return true;+ };+ EffectClipPlan::new(tree, self.runs()).is_some_and(|plan| plan.places_effects_as(kept_plan))}-}-impl DisplayListStorage {- /// A list this process recorded against `visual_context_tree`.- pub fn recorded(recorded: Arc<RecordedDisplayList>, visual_context_tree: Arc<VisualContextTree>) -> Arc<Self> {- Self::new(Tape::Recorded(recorded), Some(visual_context_tree), OnceLock::new())+ pub fn run_groups(&self, tree: &VisualContextTree) -> Arc<RunGroups> {+ let mut cached_run_groups = self.cached_run_groups.lock().unwrap_or_else(PoisonError::into_inner);+ let tree_copy_without_animation_samples = tree.copy_without_animation_samples();+ if let Some((tree_copy, run_groups)) = cached_run_groups.as_mut()+ && ((*tree_copy == tree_copy_without_animation_samples+ && !tree.transform_animation_animates_plane_of_sorting_context())+ || run_groups.match_depth_sorting_roots(&tree.roots_of_contexts_sorting_planes_by_depth()))+ {+ *tree_copy = tree_copy_without_animation_samples;+ return run_groups.clone();+ }+ cached_run_groups+ .insert((+ tree_copy_without_animation_samples,+ Arc::new(RunGroups::new(tree, self.runs())),+ ))+ .1+ .clone()}- /// An empty list, recorded against a tree with no node but the visual viewport.- pub fn empty() -> Arc<Self> {- Self::new(- Tape::Empty,- Some(Arc::new(VisualContextTree::create_identity())),- OnceLock::new(),- )+ /// Visits the compositor metadata commands of the runs that hold any, with the context of their run and their+ /// payload, in paint order.+ pub fn for_each_compositor_metadata(&self, mut visit: impl FnMut(ContextRef, DisplayListCommandType, &[u8])) {+ for chunk in &self.chunks_in_paint_order {+ let records = chunk.records();+ for run in chunk.runs().iter().filter(|run| run.has_compositor_metadata) {+ for_each_command(+ &records[run.offset as usize..(run.offset + run.size) as usize],+ |header, _, payload| {+ if header.command_type.is_compositor_metadata() {+ visit(run.context, header.command_type, payload);+ }+ },+ );+ }+ }+ }++ /// Visits indexed top-level records with their run's context, their header and their payload.+ pub fn for_each_indexed_record(+ &self,+ records: &[IndexedRecord],+ mut visit: impl FnMut(ContextRef, &DisplayListCommandHeader, &[u8]),+ ) {+ for record in records {+ let (header, payload) = self.record_at(record.position);+ visit(self.run(record.run_index as usize).context, &header, payload);+ }}}-// Writes a run field by field, so its padding is written too.-pub(super) fn write_run(run: &DisplayListCommandRun, out: &mut [u8]) {+/// The chunks of a recorded tape, which `chunks` cuts it into, each a copy. What the tape holds past its last chunk is a+/// chunk of its own.+pub fn chunks_of_recording(+ bytes: &[u8],+ runs: &[DisplayListCommandRun],+ chunks: &[DisplayListChunk],+) -> Vec<Arc<ListChunk>> {+ let mut list_chunks = Vec::with_capacity(chunks.len() + 1);+ let (mut covered_bytes, mut covered_runs) = (0usize, 0usize);+ for (chunk, chunk_bytes, chunk_runs) in chunks_of(bytes, runs, chunks) {+ if !chunk_runs.is_empty() {+ list_chunks.push(Arc::new(ListChunk::copied(+ chunk_bytes,+ chunk_runs,+ covered_bytes as u32,+ )));+ }+ covered_bytes = chunk.byte_end as usize;+ covered_runs = chunk.run_end as usize;+ }+ if covered_runs < runs.len() {+ list_chunks.push(Arc::new(ListChunk::copied(+ &bytes[covered_bytes..],+ &runs[covered_runs..],+ covered_bytes as u32,+ )));+ }+ list_chunks+}++pub(super) fn write_run_with_zeroed_padding(run: &DisplayListCommandRun, out: &mut [u8]) {use std::mem::offset_of;out.fill(0);let mut put = |offset: usize, bytes: &[u8]| out[offset..offset + bytes.len()].copy_from_slice(bytes);@@ -193,7 +601,7 @@ impl PackedChunkSize {}}- fn in_bytes(self) -> Option<(usize, usize)> {+ fn record_and_run_byte_counts(self) -> Option<(usize, usize)> {let record_bytes = usize::try_from(self.record_bytes).ok()?;let run_bytes = usize::try_from(self.run_count).ok()?@@ -222,35 +630,12 @@ pub fn write_packed_chunks(chunks: &[&Chunk], destination: &mut [u8]) {after_records.split_at_mut(chunk.runs.len() * std::mem::size_of::<DisplayListCommandRun>());let (run_destinations, _) = runs.as_chunks_mut::<{ std::mem::size_of::<DisplayListCommandRun>() }>();for (run, out) in chunk.runs.iter().zip(run_destinations) {- write_run(run, out);+ write_run_with_zeroed_padding(run, out);}rest = after_runs;}}-/// A chunk another process sent that passed validation, named by what it holds: its records in memory aligned for-/// every command struct, and its runs.-pub struct ReceivedChunk {- pub id: ChunkId,- records: AlignedBytes,- runs: Vec<DisplayListCommandRun>,- records_reaching_outside: Vec<TopLevelRecordReachingOutsideItsChunk>,-}--impl ReceivedChunk {- pub fn records(&self) -> &[u8] {- self.records.as_slice()- }-- pub fn runs(&self) -> &[DisplayListCommandRun] {- &self.runs- }-- pub fn records_reaching_outside(&self) -> &[TopLevelRecordReachingOutsideItsChunk] {- &self.records_reaching_outside- }-}-/// Copies the chunks packed one after another in the `packed_size_in_bytes` bytes at `packed`, whose sizes `sizes` lists/// in order, out of memory that another process can still write to, checks each copy and names it by what it holds.///@@ -260,14 +645,16 @@ pub unsafe fn receive_packed_chunks_from_shared_memory(packed: *const u8,packed_size_in_bytes: usize,sizes: &[PackedChunkSize],-) -> Result<Vec<ReceivedChunk>, &'static str> {+) -> Result<Vec<ListChunk>, &'static str> {let mut chunks = Vec::new();chunks.try_reserve_exact(sizes.len()).map_err(|_| "Display list has too many chunks to receive")?;let mut offset = 0usize;for size in sizes {- let (record_bytes, run_bytes) = size.in_bytes().ok_or("Display list chunk sizes overflow")?;+ let (record_bytes, run_bytes) = size+ .record_and_run_byte_counts()+ .ok_or("Display list chunk sizes overflow")?;let end = offset.checked_add(record_bytes).and_then(|end| end.checked_add(run_bytes))@@ -275,8 +662,9 @@ pub unsafe fn receive_packed_chunks_from_shared_memory(if end > packed_size_in_bytes {return Err("Display list chunks exceed the buffer that holds them");}- // Every run holds at least one record, so more runs than headers cannot describe the chunk.- if run_bytes / std::mem::size_of::<DisplayListCommandRun>() > record_bytes / super::builder::HEADER_SIZE {+ let run_count = run_bytes / std::mem::size_of::<DisplayListCommandRun>();+ let largest_run_count_records_allow = record_bytes / super::builder::HEADER_SIZE;+ if run_count > largest_run_count_records_allow {return Err("Display list chunk has more runs than its records allow");}let mut records = AlignedBytes::try_zeroed(record_bytes).ok_or("Display list chunk is too large to receive")?;@@ -294,12 +682,7 @@ pub unsafe fn receive_packed_chunks_from_shared_memory(}}let runs = validate_tape(records.as_slice(), &packed_runs)?;- chunks.push(ReceivedChunk {- id: chunk_id(records.as_slice(), &runs, 0),- records_reaching_outside: top_level_records_reaching_outside_their_chunk(records.as_slice(), &runs),- records,- runs,- });+ chunks.push(ListChunk::named_copy(records, runs));offset = end;}if offset != packed_size_in_bytes {@@ -310,79 +693,75 @@ pub unsafe fn receive_packed_chunks_from_shared_memory(/// Copies the chunks packed one after another in `packed`, whose sizes `sizes` lists in order, out, checks each copy and/// names it by what it holds.-pub fn receive_packed_chunks(packed: &[u8], sizes: &[PackedChunkSize]) -> Result<Vec<ReceivedChunk>, &'static str> {+pub fn receive_packed_chunks(packed: &[u8], sizes: &[PackedChunkSize]) -> Result<Vec<ListChunk>, &'static str> {// SAFETY: The slice addresses its bytes.unsafe { receive_packed_chunks_from_shared_memory(packed.as_ptr(), packed.len(), sizes) }}-impl DisplayListStorage {- /// The tape of `chunks`, which another process sent, one after another.- pub fn of_received_chunks(chunks: &[Arc<ReceivedChunk>]) -> Result<Arc<Self>, &'static str> {- let tape_size = chunks.iter().map(|chunk| chunk.records().len()).sum::<usize>();- if u32::try_from(tape_size).is_err() {- return Err("Display list exceeds the size of a tape");- }- let mut bytes = AlignedBytes::try_zeroed(tape_size).ok_or("Display list is too large to receive")?;- let mut command_runs = Vec::new();- command_runs- .try_reserve_exact(chunks.iter().map(|chunk| chunk.runs().len()).sum())- .map_err(|_| "Display list is too large to receive")?;- let mut tape_chunks = TapeChunks::default();- tape_chunks.try_reserve(- chunks.len(),- chunks.iter().map(|chunk| chunk.records_reaching_outside().len()).sum(),- )?;- let mut chunk_start = 0;- for chunk in chunks {- let records = chunk.records();- bytes.as_mut_slice()[chunk_start..chunk_start + records.len()].copy_from_slice(records);- tape_chunks.push_chunk(- chunk.id,- command_runs.len() as u32,- chunk.runs().len(),- chunk_start as u32,- chunk.records_reaching_outside(),- );- command_runs.extend(chunk.runs().iter().map(|run| DisplayListCommandRun {- offset: run.offset + chunk_start as u32,- ..*run- }));- chunk_start += records.len();- }- Ok(DisplayListStorage::new(- Tape::Received { bytes, command_runs },- None,- OnceLock::from(tape_chunks),- ))- }-}-#[cfg(test)]mod tests {use super::*;+ use crate::display_list::builder::DisplayListBuilder;+ use crate::display_list::commands::{EffectNodeIndex, FillRect};+ use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};++ fn fill_rect(y: i32) -> FillRect {+ FillRect {+ rect: IntRect::new(0, y, 10, 10),+ color: Color::default(),+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ }+ }++ #[test]+ fn a_list_naming_chunks_whose_records_add_up_past_the_limit_is_refused() {+ let mut builder = DisplayListBuilder::new();+ let mut y = 0;+ while builder.byte_size() < 1 << 20 {+ builder.append(&fill_rect(y), &[], ContextRef::default());+ y += 1;+ }+ let chunk = Arc::new(ListChunk::copied(builder.bytes(), builder.command_runs(), 0));+ let occurrences_within_limit = (u32::MAX as usize) / chunk.records().len();+ assert!(DisplayListStorage::of_chunks(vec![chunk.clone(); occurrences_within_limit]).is_ok());+ assert!(DisplayListStorage::of_chunks(vec![chunk; occurrences_within_limit + 1]).is_err());+ }#[test]- fn chunks_packed_for_transport_come_back_as_the_tape_they_make() {- use super::super::builder::DisplayListBuilder;- use super::super::chunks::ReachOutsideChunk;- use super::super::commands::{ClipNodeIndex, EffectNodeIndex, FillRect, PaintScrollBar, SpatialNodeIndex};- use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};+ fn chunks_packed_for_transport_come_back_as_the_chunks_of_the_list_they_make() {+ use crate::display_list::chunks::ReachOutsideRunContext;+ use crate::display_list::commands::{CanvasId, ClipNodeIndex, DrawCanvas, PaintScrollBar, SpatialNodeIndex};+ use libgfx_rust::ScalingMode;let context = |spatial| ContextRef {spatial: SpatialNodeIndex(spatial),clip: ClipNodeIndex::NONE,effect: EffectNodeIndex::NONE,};- let fill_rect = |y| FillRect {- rect: IntRect::new(0, y, 10, 10),- color: Color::default(),- compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,- background_color_animation_effect: EffectNodeIndex::NONE,- };let mut builder = DisplayListBuilder::new();builder.append(&fill_rect(0), &[], context(1));+ builder.append(+ &DrawCanvas {+ dst_rect: IntRect::new(0, 0, 30, 30),+ canvas_id: CanvasId(4),+ scaling_mode: ScalingMode::NearestNeighbor,+ },+ &[],+ context(1),+ );let first = builder.take_chunk();builder.append(&fill_rect(10), &[], context(1));builder.append(&fill_rect(20), &[], context(2));+ let canvas_offset_in_second_chunk = builder.byte_size() as u32;+ builder.append(+ &DrawCanvas {+ dst_rect: IntRect::new(40, 0, 30, 30),+ canvas_id: CanvasId(3),+ scaling_mode: ScalingMode::NearestNeighbor,+ },+ &[],+ context(2),+ );let scrollbar_offset_in_second_chunk = builder.byte_size() as u32;builder.append(&PaintScrollBar {@@ -412,30 +791,42 @@ mod tests {assert_eq!(received.records(), &sent.records[..]);assert_eq!(received.runs(), &sent.runs[..]);}- let received: Vec<Arc<ReceivedChunk>> = received.into_iter().map(Arc::new).collect();- let storage = DisplayListStorage::of_received_chunks(&received).unwrap();+ let received: Vec<Arc<ListChunk>> = received.into_iter().map(Arc::new).collect();+ let list = DisplayListStorage::of_chunks(received).unwrap();+ // The chunks of a recording of the same chunks are the same, and so is what is known of them.let tape = RecordedDisplayList::of_chunks(chunks);- assert_eq!(storage.bytes(), &tape.bytes[..]);- assert_eq!(storage.command_runs(), &tape.command_runs[..]);-- let tape_chunks = storage.chunks();+ let recorded = DisplayListStorage::recorded(&tape, Arc::new(VisualContextTree::create_identity()));+ assert_eq!(list.summary(), recorded.summary());+ let ids = |list: &DisplayListStorage| list.chunks().iter().map(|chunk| chunk.id).collect::<Vec<_>>();+ assert_eq!(ids(&list), [first.id, second.id]);+ assert_eq!(ids(&recorded), [first.id, second.id]);+ // A canvas and a scroll bar are each alone in a run.+ assert_eq!(list.run_count(), 6);+ assert_eq!(list.chunk_of_run(0), (ChunkIndexInList(0), 0));+ assert_eq!(list.chunk_of_run(3), (ChunkIndexInList(1), 1));assert_eq!(- tape_chunks,- &TapeChunks::of_tape(&tape.bytes, &tape.command_runs, &tape.chunks)+ list.span_of_run(3).begin,+ ListPosition::new(ChunkIndexInList(1), second.runs[1].offset));+ // What the list knows of its records is where they are in their chunks.assert_eq!(- (tape_chunks.len(), tape_chunks.id(0), tape_chunks.id(1)),- (2, first.id, second.id)+ list.summary().live_content_records[1].record.position,+ ListPosition::new(ChunkIndexInList(1), canvas_offset_in_second_chunk)+ );+ assert_eq!(list.summary().live_content_records[1].record.run_index, 4);+ assert!(+ list.chunk(ChunkIndexInList(0))+ .records_reaching_outside_run_context()+ .is_empty());- // The scroll bar is alone in a run.- assert_eq!((tape_chunks.runs_of(0), tape_chunks.runs_of(1)), (0..1, 1..4));- assert!(tape_chunks.records_reaching_outside(0).is_empty());assert_eq!(- tape_chunks.records_reaching_outside(1),- [TopLevelRecordReachingOutsideItsChunk {- record_offset: first.records.len() as u32 + scrollbar_offset_in_second_chunk,+ list.chunk(ChunkIndexInList(1)).records_reaching_outside_run_context(),+ [TopLevelRecordReachingOutsideRunContext {+ record_offset: scrollbar_offset_in_second_chunk,run_index: 3,- reach: ReachOutsideChunk::ScrollbarThumbFollowsScrollOffsetOf(SpatialNodeIndex(3)),+ reach_outside_run_context: ReachOutsideRunContext::ScrollbarThumbFollowsScrollOffsetOf(+ SpatialNodeIndex(3)+ ),}]);@@ -445,23 +836,97 @@ mod tests {}#[test]- fn published_bytes_survive_the_recorder_and_can_be_released_on_another_thread() {+ fn a_chunk_made_in_this_process_keeps_its_id_and_its_records_stay_aligned() {+ let mut builder = DisplayListBuilder::new();+ builder.append(&fill_rect(0), &[], ContextRef::default());+ builder.append(&fill_rect(10), &[], ContextRef::default());+ let chunk = Arc::new(builder.take_chunk());+ let list_chunk = ListChunk::of_chunk_made_in_this_process(&chunk);+ let copy = ListChunk::copied(&chunk.records, &chunk.runs, 0);+ assert_eq!(list_chunk.id, copy.id);+ assert_eq!(list_chunk.records(), copy.records());+ assert_eq!(list_chunk.runs(), copy.runs());+ assert_eq!(list_chunk.summary(), copy.summary());+ assert!(list_chunk.records().as_ptr().addr().is_multiple_of(COMMAND_ALIGNMENT));+ // Records that start where every command struct may are shared, not copied.+ if chunk.records.as_ptr().addr().is_multiple_of(COMMAND_ALIGNMENT) {+ assert_eq!(list_chunk.records().as_ptr(), chunk.records.as_ptr());+ }+ }++ #[test]+ fn a_recorded_list_survives_the_recorder_and_can_be_released_on_another_thread() {fn assert_send_sync<T: Send + Sync>() {}assert_send_sync::<RecordedDisplayList>();assert_send_sync::<DisplayListStorage>();- let mut recorded = Arc::new(RecordedDisplayList {- bytes: vec![1, 2, 3],- ..Default::default()- });- let storage = DisplayListStorage::recorded(recorded.clone(), Arc::new(VisualContextTree::create_identity()));+ let mut builder = DisplayListBuilder::new();+ builder.append(&fill_rect(0), &[], ContextRef::default());+ let mut recorded = Arc::new(builder.finish());+ let records = recorded.bytes.clone();+ let storage = DisplayListStorage::recorded(&recorded, Arc::new(VisualContextTree::create_identity()));Arc::make_mut(&mut recorded).bytes[0] = 9;- assert_eq!(storage.bytes(), &[1, 2, 3]);+ assert_eq!(storage.chunk(ChunkIndexInList(0)).records(), &records[..]);drop(recorded);std::thread::spawn(move || {- assert_eq!(storage.bytes(), &[1, 2, 3]);+ assert_eq!(storage.chunk(ChunkIndexInList(0)).records(), &records[..]);drop(storage);}).join().unwrap();}++ #[test]+ fn a_plane_the_tree_turns_out_of_its_context_is_sorted_by_depth_in_a_sample_its_planar_animation_leaves_alone() {+ use crate::animation_timing::TimeValue;+ use crate::display_list::test_fixtures::{+ GREEN, ListOfOneChunk, fill, transform, transform_animation_of, tree_with_root_isolation_effect,+ };+ use crate::host::FfiVisualAnimationTransformOperationKind;+ use crate::visual_context::{SpatialData, TransformData};++ let element = IntRect::new(50, 50, 100, 100);+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let context_root = tree.append_spatial(+ SpatialData::Transform(TransformData {+ establishes_sorting_context: true,+ ..transform(element.to_float())+ }),+ viewport.spatial,+ );+ let turned_plane = tree.append_spatial(+ SpatialData::Transform(TransformData {+ matrix: libgfx_rust::rotation_matrix([0.0, 1.0, 0.0], 30f32.to_radians()),+ sorting_context_root_index: Some(context_root),+ ..transform(element.to_float())+ }),+ context_root,+ );+ let mut slide_in_the_plane = transform_animation_of(+ turned_plane,+ FfiVisualAnimationTransformOperationKind::TranslateX,+ 0.0,+ 100.0,+ );+ slide_in_the_plane.timing.start_delay = TimeValue::milliseconds(200.0);+ slide_in_the_plane.timing.iteration_count = 1.0;+ tree.set_visual_animations(vec![slide_in_the_plane]);+ let storage = ListOfOneChunk::default()+ .with(fill(IntRect::new(0, 0, 200, 200), GREEN), viewport)+ .with(+ fill(element, GREEN),+ ContextRef {+ spatial: turned_plane,+ ..viewport+ },+ )+ .storage();++ let sliding = tree.with_visual_animation_samples(450_000_000);+ assert!(!sliding.sorts_planes_by_depth());+ assert!(!storage.run_groups(&sliding).run_is_sorted_by_depth(1));++ let before_the_slide = tree.with_visual_animation_samples(0);+ assert!(before_the_slide.sorts_planes_by_depth());+ assert!(storage.run_groups(&before_the_slide).run_is_sorted_by_depth(1));+ }}diff --git a/Libraries/LibCompositing/Rust/src/display_list/summary.rs b/Libraries/LibCompositing/Rust/src/display_list/summary.rsindex e5b4e5ae6ed..f458b6fbd89 100644--- a/Libraries/LibCompositing/Rust/src/display_list/summary.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/summary.rs@@ -4,25 +4,37 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! What C++ and damage ask about a display list's tape: the resources its commands reference, whether reusing a-//! raster of it can differ from replaying it, its compositor metadata, its carets, and where it draws live content.+//! What is asked about the records of a display list: the resources its commands reference, whether reusing a raster+//! of it can differ from replaying it, its carets, where it draws live content, and where it declares the content of+//! masks.-use super::builder::{HEADER_SIZE, for_each_command, read_command};+use super::builder::{for_each_command, read_command};use super::commands::*;use super::nested_records::{for_each_nested_record_span, span_bytes};+use super::storage::{ChunkIndexInList, ListPosition};use libgfx_rust::CompositingAndBlendingOperator;use libgfx_rust::filter::Filter;use std::collections::HashSet;-// A top-level record, found by the run it belongs to and its offset in the tape.-#[derive(Clone, Copy, Debug)]+/// A top-level record, by the index of its run among the runs of its list and its position in the list. In the summary+/// of a chunk alone, the run index counts the runs of that chunk only, and the position is in that chunk.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct IndexedRecord {pub run_index: u32,- pub record_offset: u32,+ pub position: ListPosition,}-// Content that changes under the list's immutable commands.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+impl IndexedRecord {+ fn shifted_into_list(self, first_run_index_of_chunk: u32, chunk_index: ChunkIndexInList) -> Self {+ Self {+ run_index: self.run_index + first_run_index_of_chunk,+ position: ListPosition::new(chunk_index, self.position.offset),+ }+ }+}++/// Content that changes under the list's immutable commands.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub enum LiveContent {Canvas(CanvasId),VideoFrame(VideoSinkHandle),@@ -30,14 +42,21 @@ pub enum LiveContent {CompositedContext(CompositorContextId),}-// A top-level record that draws live content, itself or in a record nested in it.-#[derive(Clone, Copy, Debug)]+/// A top-level record that draws live content, itself or in a record nested in it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct LiveContentRecord {pub record: IndexedRecord,pub content: LiveContent,}-#[derive(Default)]+/// A top-level record that declares the content of a mask, with the effect of the mask.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct MaskDeclarationRecord {+ pub record: IndexedRecord,+ pub mask_effect: EffectNodeIndex,+}++#[derive(Debug, Default, PartialEq, Eq)]pub struct DisplayListSummary {pub font_ids: Vec<u64>,pub image_frame_ids: Vec<u64>,@@ -48,7 +67,7 @@ pub struct DisplayListSummary {pub carets: Vec<IndexedRecord>,pub live_content_records: Vec<LiveContentRecord>,pub destination_blending_records: Vec<IndexedRecord>,- pub mask_declarations: Vec<IndexedRecord>,+ pub mask_declarations: Vec<MaskDeclarationRecord>,}#[derive(Default)]@@ -61,7 +80,7 @@ struct ReferencedIds {composited_contexts: HashSet<u64>,}-fn live_content_of(command_type: DisplayListCommandType, payload: &[u8]) -> Option<LiveContent> {+pub(crate) fn live_content_of(command_type: DisplayListCommandType, payload: &[u8]) -> Option<LiveContent> {use DisplayListCommandType as T;match command_type {T::DrawCanvas => Some(LiveContent::Canvas(read_command::<DrawCanvas>(payload).canvas_id)),@@ -173,7 +192,6 @@ fn note_referenced_ids(command_type: DisplayListCommandType, payload: &[u8], ids}}-// Visits every record of `records` and of the records nested in them, depth first.fn for_each_record_including_nested(records: &[u8], visit: &mut impl FnMut(DisplayListCommandType, &[u8])) {for_each_command(records, |header, _, payload| {visit(header.command_type, payload);@@ -195,27 +213,30 @@ pub fn summarize(tape: &[u8], command_runs: &[DisplayListCommandRun]) -> Displayfor (run_index, run) in command_runs.iter().enumerate() {let run_start = run.offset as usize;let records = &tape[run_start..run_start + run.size as usize];- for_each_command(records, |header, offset, payload| {- let indexed = IndexedRecord {+ for_each_command(records, |header, offset_in_run, payload| {+ let indexed_record = IndexedRecord {run_index: run_index as u32,- record_offset: (run_start + offset) as u32,+ position: ListPosition::new(ChunkIndexInList(0), (run_start + offset_in_run) as u32),};match header.command_type {- DisplayListCommandType::PaintCaret => summary.carets.push(indexed),- DisplayListCommandType::DeclareMaskContent => summary.mask_declarations.push(indexed),+ DisplayListCommandType::PaintCaret => summary.carets.push(indexed_record),+ DisplayListCommandType::DeclareMaskContent => summary.mask_declarations.push(MaskDeclarationRecord {+ record: indexed_record,+ mask_effect: read_command::<DeclareMaskContent>(payload).effect,+ }),_ => {}}if let Some((blend, blends_with_isolated_backdrop_color)) = command_blend(header.command_type, payload)&& blend != CompositingAndBlendingOperator::Normal&& !blends_with_isolated_backdrop_color{- summary.destination_blending_records.push(indexed);+ summary.destination_blending_records.push(indexed_record);}note_referenced_ids(header.command_type, payload, &mut ids);let mut note_live_content = |command_type, payload: &[u8]| {if let Some(content) = live_content_of(command_type, payload) {summary.live_content_records.push(LiveContentRecord {- record: indexed,+ record: indexed_record,content,});}@@ -238,9 +259,72 @@ pub fn summarize(tape: &[u8], command_runs: &[DisplayListCommandRun]) -> Displaysummary}-// The blend a command composites with, and whether it blends with a backdrop color of its own instead of the-// destination.-fn command_blend(+/// The summary of a list made of chunks, each summarized alone: the summary of a chunk, the index of its first run+/// among the runs of the list, and its place among the chunks of the list.+pub fn summary_of_pieces<'a>(+ pieces: impl IntoIterator<Item = (&'a DisplayListSummary, u32, ChunkIndexInList)>,+) -> DisplayListSummary {+ let mut summary = DisplayListSummary::default();+ for (chunk_summary, first_run_index_of_chunk, chunk_index) in pieces {+ let shift_into_list = |record: &IndexedRecord| record.shifted_into_list(first_run_index_of_chunk, chunk_index);+ summary.carets.extend(chunk_summary.carets.iter().map(shift_into_list));+ summary+ .live_content_records+ .extend(+ chunk_summary+ .live_content_records+ .iter()+ .map(|live_content_record| LiveContentRecord {+ record: shift_into_list(&live_content_record.record),+ content: live_content_record.content,+ }),+ );+ summary+ .destination_blending_records+ .extend(chunk_summary.destination_blending_records.iter().map(shift_into_list));+ summary+ .mask_declarations+ .extend(+ chunk_summary+ .mask_declarations+ .iter()+ .map(|declaration| MaskDeclarationRecord {+ record: shift_into_list(&declaration.record),+ mask_effect: declaration.mask_effect,+ }),+ );+ summary.font_ids.extend_from_slice(&chunk_summary.font_ids);+ summary+ .image_frame_ids+ .extend_from_slice(&chunk_summary.image_frame_ids);+ summary+ .video_sink_handles+ .extend_from_slice(&chunk_summary.video_sink_handles);+ summary+ .vector_image_ids+ .extend_from_slice(&chunk_summary.vector_image_ids);+ summary.canvas_ids.extend_from_slice(&chunk_summary.canvas_ids);+ summary+ .composited_context_ids+ .extend_from_slice(&chunk_summary.composited_context_ids);+ }+ for ids in [+ &mut summary.font_ids,+ &mut summary.image_frame_ids,+ &mut summary.video_sink_handles,+ &mut summary.vector_image_ids,+ &mut summary.canvas_ids,+ &mut summary.composited_context_ids,+ ] {+ ids.sort_unstable();+ ids.dedup();+ }+ summary+}++/// The blend a command composites with, and whether it blends with a backdrop color of its own instead of the+/// destination.+pub(crate) fn command_blend(command_type: DisplayListCommandType,payload: &[u8],) -> Option<(CompositingAndBlendingOperator, bool)> {@@ -371,38 +455,3 @@ pub fn vector_image_records_require_direct_replay(records: &[u8]) -> bool {});requires_direct_replay}--/// Visits the compositor metadata commands of the runs that hold any, in tape order.-pub fn for_each_compositor_metadata(- tape: &[u8],- command_runs: &[DisplayListCommandRun],- mut visit: impl FnMut(ContextRef, DisplayListCommandType, &[u8]),-) {- for run in command_runs.iter().filter(|run| run.has_compositor_metadata) {- let records = &tape[run.offset as usize..(run.offset + run.size) as usize];- for_each_command(records, |header, _, payload| {- if header.command_type.is_compositor_metadata() {- visit(run.context, header.command_type, payload);- }- });- }-}--/// Visits indexed top-level records with their run's context, their header and their payload.-pub fn for_each_indexed_record(- tape: &[u8],- command_runs: &[DisplayListCommandRun],- records: &[IndexedRecord],- mut visit: impl FnMut(ContextRef, &DisplayListCommandHeader, &[u8]),-) {- for record in records {- let offset = record.record_offset as usize;- let header = super::builder::read_header(&tape[offset..]);- let payload_start = offset + HEADER_SIZE;- visit(- command_runs[record.run_index as usize].context,- &header,- &tape[payload_start..payload_start + header.payload_size as usize],- );- }-}diff --git a/Libraries/LibCompositing/Rust/src/display_list/test_fixtures.rs b/Libraries/LibCompositing/Rust/src/display_list/test_fixtures.rsnew file mode 100644index 00000000000..d370094fd75--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/test_fixtures.rs@@ -0,0 +1,313 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the unit tests of the layer planner, of the wire form of its plans and of tile keying build their pages from.++use crate::display_list::builder::DisplayListBuilder;+use crate::display_list::commands::{+ CanvasId, ClipNodeIndex, CompositorContextId, ContextRef, DisplayListCommand, DrawCanvas, EffectNodeIndex,+ FillRect, ImageFrameResourceId, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX, VideoSinkHandle,+};+use crate::display_list::layers::LayerStack;+use crate::display_list::layers::planning::{LayerStackInputs, PlannedLayers, plan_layer_stack};+use crate::display_list::storage::{DisplayListStorage, ListChunk};+use crate::display_list::tile_keys::{ContentHash, FrameStateReadByReplay, LayerRasterSettings, LiveContentVersions};+use crate::host::{FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};+use crate::node_slot_id::NodeSlotId;+use crate::visual_animation::{+ VisualAnimation, VisualAnimationKeyframe, VisualAnimationTransformOperation, VisualAnimationValue,+};+use crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT;+use crate::visual_context::{+ BackdropFilterData, CompositorScrollNodeRecord, CompositorScrollTable, EffectNodeData, EffectsData, ScrollData,+ SpatialData, TransformData, TransformDataRole, VisualContextTree,+};+use libgfx_rust::{+ Color, CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, IntRect, ScalingMode,+};+use std::sync::Arc;++pub const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);+pub const GREEN: Color = Color::from_rgb(0, 128, 0);++pub struct LiveContentThatNeverChanges;++impl LiveContentVersions for LiveContentThatNeverChanges {+ fn canvas_content_generation(&self, _: CanvasId) -> u64 {+ 0+ }+ fn video_frame_id(&self, _: VideoSinkHandle) -> Option<u64> {+ None+ }+ fn image_frame_pixel_generation(&self, _: ImageFrameResourceId) -> Option<u64> {+ None+ }+ fn nested_context_frame_generation(&self, _: CompositorContextId) -> Option<u64> {+ None+ }+}++pub const NO_FRAME_STATE: FrameStateReadByReplay<'static> = FrameStateReadByReplay {+ scrollbars: &[],+ time_ns: 0,+ live_content: &LiveContentThatNeverChanges,+};++pub fn raster_settings_hash_by_layer(stack: &LayerStack) -> Vec<ContentHash> {+ let raster_settings = LayerRasterSettings {+ raster_space_identity: 0,+ clear_color: Color::TRANSPARENT,+ root_group_color: Color::TRANSPARENT,+ viewport_to_raster_transform: FloatMatrix4x4::identity(),+ allows_lcd_text: false,+ };+ vec![raster_settings.content_hash(); stack.layers.len()]+}++pub fn effects(opacity: f32, blend_mode: CompositingAndBlendingOperator) -> EffectNodeData {+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity,+ blend_mode,+ filter: None,+ backdrop_filter: None,+ })+}++pub fn transform(bounds: FloatRect) -> TransformData {+ TransformData {+ matrix: FloatMatrix4x4::identity(),+ origin: FloatPoint {+ x: bounds.x + bounds.width / 2.0,+ y: bounds.y + bounds.height / 2.0,+ },+ sorting_context_root_index: None,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: false,+ bounds,+ }+}++/// A tree whose root isolation effect has `root_opacity`, and the context of the viewport inside that effect.+pub fn tree_with_root_isolation_effect(root_opacity: f32) -> (VisualContextTree, ContextRef) {+ let mut tree = VisualContextTree::create_identity();+ let root = tree.append_effect(+ effects(root_opacity, CompositingAndBlendingOperator::Normal),+ EffectNodeIndex::NONE,+ VISUAL_VIEWPORT_NODE_INDEX,+ ClipNodeIndex::NONE,+ );+ tree.root_isolation_effect = Some(root);+ let viewport = ContextRef {+ effect: root,+ ..ContextRef::default()+ };+ (tree, viewport)+}++pub fn scroll_node(tree: &mut VisualContextTree, parent: SpatialNodeIndex) -> SpatialNodeIndex {+ tree.append_spatial(+ SpatialData::Scroll(ScrollData {+ state_slot: NO_SCROLL_STATE_SLOT,+ owner_paintable: NodeSlotId::INVALID,+ }),+ parent,+ )+}++/// The record of a scroller that a wheel scrolls down by up to `max_scroll_offset_y`.+pub fn scroll_record(+ node: SpatialNodeIndex,+ parent: SpatialNodeIndex,+ scrollport_rect: IntRect,+ max_scroll_offset_y: f32,+ is_viewport: bool,+) -> CompositorScrollNodeRecord {+ CompositorScrollNodeRecord {+ scroll_node_index: node,+ parent_scroll_node_index: parent,+ scrollport_rect,+ max_scroll_offset: FloatPoint {+ x: 0.0,+ y: max_scroll_offset_y,+ },+ is_viewport,+ can_be_wheel_scrolled_vertically: true,+ ..CompositorScrollNodeRecord::default()+ }+}++/// A tree whose document scrolls by up to 2000 px down the viewport, with the context of the viewport, and those of the+/// document and of a scroller in it per rect of `nested_scrollers`, which scrolls by up to 500 px.+pub fn tree_with_document_scroller(nested_scrollers: &[IntRect]) -> (VisualContextTree, ContextRef, Vec<ContextRef>) {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let document_node = scroll_node(&mut tree, VISUAL_VIEWPORT_NODE_INDEX);+ let mut records = vec![scroll_record(+ document_node,+ VISUAL_VIEWPORT_NODE_INDEX,+ VIEWPORT,+ 2000.0,+ true,+ )];+ let mut contexts = vec![ContextRef {+ spatial: document_node,+ ..viewport+ }];+ for &scrollport_rect in nested_scrollers {+ let nested_node = scroll_node(&mut tree, document_node);+ records.push(scroll_record(nested_node, document_node, scrollport_rect, 500.0, false));+ contexts.push(ContextRef {+ spatial: nested_node,+ ..viewport+ });+ }+ assert!(tree.set_compositor_scroll_table(CompositorScrollTable {+ nodes: records.into(),+ ..CompositorScrollTable::default()+ }));+ (tree, viewport, contexts)+}++/// A tree whose document scrolls by up to 2000 px down the viewport, with the contexts of the viewport and of the+/// document.+pub fn tree_with_document_scroll() -> (VisualContextTree, ContextRef, ContextRef) {+ let (tree, viewport, contexts) = tree_with_document_scroller(&[]);+ (tree, viewport, contexts[0])+}++pub fn fill(rect: IntRect, color: Color) -> FillRect {+ FillRect {+ rect,+ color,+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ }+}++pub fn canvas(rect: IntRect, id: u64) -> DrawCanvas {+ DrawCanvas {+ dst_rect: rect,+ canvas_id: CanvasId(id),+ scaling_mode: ScalingMode::NearestNeighbor,+ }+}++pub fn frosted_glass(tree: &mut VisualContextTree, parent: ContextRef, region: IntRect) -> ContextRef {+ tree.append_effect_node_under(+ parent,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: Some(BackdropFilterData {+ filter: Arc::new(libgfx_rust::filter::Filter::blur(4.0, 4.0, None).serialize()),+ region,+ corner_radii: CornerRadii::default(),+ }),+ }),+ )+}++#[derive(Default)]+pub struct ListOfOneChunk {+ pub builder: DisplayListBuilder,+}++impl ListOfOneChunk {+ pub fn with<C: DisplayListCommand>(mut self, command: C, context: ContextRef) -> Self {+ self.builder.append(&command, &[], context);+ self+ }++ pub fn storage(&self) -> Arc<DisplayListStorage> {+ DisplayListStorage::of_builder(&self.builder)+ }++ pub fn planned(&self, tree: &VisualContextTree, scroll_offsets: &[FloatPoint]) -> PlannedLayers {+ plan_layer_stack(&LayerStackInputs {+ list: &self.storage(),+ tree,+ scroll_offsets,+ viewport_rect: VIEWPORT,+ })+ }++ pub fn stack(&self, tree: &VisualContextTree, scroll_offsets: &[FloatPoint]) -> LayerStack {+ self.planned(tree, scroll_offsets).stack+ }+}++pub fn chunk_of<C: DisplayListCommand>(command: C, context: ContextRef) -> Arc<ListChunk> {+ let mut builder = DisplayListBuilder::new();+ builder.append(&command, &[], context);+ Arc::new(ListChunk::copied(builder.bytes(), builder.command_runs(), 0))+}++/// An animation of `node_index` that takes one second.+pub fn animation_of(+ target_kind: FfiVisualAnimationTargetKind,+ node_index: u32,+ keyframes: Vec<VisualAnimationKeyframe>,+) -> VisualAnimation {+ VisualAnimation {+ target_kind,+ node_indices: vec![node_index],+ timing: crate::animation_timing::AnimationEffectTiming {+ iteration_duration: crate::animation_timing::TimeValue::milliseconds(1000.0),+ ..VisualAnimation::default().timing+ },+ keyframes,+ ..VisualAnimation::default()+ }+}++fn transform_animation_keyframe(+ offset: f64,+ kind: FfiVisualAnimationTransformOperationKind,+ value: f32,+) -> VisualAnimationKeyframe {+ VisualAnimationKeyframe {+ offset,+ easing: crate::easing::Easing::default(),+ value: VisualAnimationValue::Transform(vec![VisualAnimationTransformOperation::new(kind, &[value]).unwrap()]),+ }+}++pub fn transform_animation_of(+ node: SpatialNodeIndex,+ kind: FfiVisualAnimationTransformOperationKind,+ from: f32,+ to: f32,+) -> VisualAnimation {+ animation_of(+ FfiVisualAnimationTargetKind::Transform,+ node.0,+ vec![+ transform_animation_keyframe(0.0, kind, from),+ transform_animation_keyframe(1.0, kind, to),+ ],+ )+}++pub fn spinning(node: SpatialNodeIndex) -> VisualAnimation {+ transform_animation_of(node, FfiVisualAnimationTransformOperationKind::Rotate, 0.0, 360.0)+}++pub fn opacity_animation_of(effect: EffectNodeIndex, from: f32, to: f32) -> VisualAnimation {+ let keyframe = |offset: f64, opacity: f32| VisualAnimationKeyframe {+ offset,+ easing: crate::easing::Easing::default(),+ value: VisualAnimationValue::Opacity(opacity),+ };+ animation_of(+ FfiVisualAnimationTargetKind::Opacity,+ effect.0,+ vec![keyframe(0.0, from), keyframe(1.0, to)],+ )+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/tile_keys.rs b/Libraries/LibCompositing/Rust/src/display_list/tile_keys.rsnew file mode 100644index 00000000000..af2468b026a--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/tile_keys.rs@@ -0,0 +1,3580 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The content hashes of the tiles of the layers of one band, which alone decide whether a tile is rastered again.+//!+//! A tile's content hash covers what it holds: the records of the band that can show in it, as the geometry of the+//! band's raster space places their visual contexts, and the frame state those records read. A chunk is placed once for+//! each placement of the contexts of its runs, and the placement is cached on the chunk for every list that names it. A+//! band bound to another list or geometry bins its tiles again, and a tile that holds what it held before gets the+//! content hash it had before.++use super::builder::{inline_clips_of, read_command};+use super::commands::{+ ClipNodeIndex, ContextRef, DisplayListCommandRun, DrawCompositedContext, EffectNodeIndex, PaintCaret,+ PaintScrollBar, SpatialNodeIndex,+};+use super::effect_clip_plan::EffectClipPlan;+use super::effect_geometry::{+ FiltersOfEffects, LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS, backdrop_filter_read_reach,+ filter_read_reach_in_device_pixels, nearest_effects_at_or_above_where, spreading_filter_of,+};+use super::layers::{BandIndex, BarrierCutsOfCell, CutsOfCell, LayerIndex, LayerStack, PlacementNodeBand};+use super::nested_records::for_each_command_including_nested;+use super::placement::{+ ANTIALIASING_MARGIN_IN_DEVICE_PIXELS, FiltersAndClipsOfList, RasterSpaceGeometry, RunGroupIndex, RunGroups,+ enclosing_int_rect_within_extent_limit, is_finite_rect,+};+use super::reach::Reach;+use super::replay::{ScrollbarShownByFrame, caret_is_visible_at_time, scrollbar_shown_by_frame};+use super::storage::{ChunkIndexInList, DisplayListStorage, ListChunk, ListPosition, ListSpan, RunIndexInChunk};+use super::summary::{LiveContent, live_content_of};+use super::tiles::{CellRange, TileCoord, entries_within, for_each_entry_within};+use super::window_server_placement::RoundedRect;+use crate::display_list::commands::{CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkHandle};+use crate::visual_context::{+ ClipData, ClipNodeData, EffectNodeData, VisualContextTree, WorldTransforms, device_offset_for_index,+};+use foldhash::fast::{FixedState, FoldHasher};+use libgfx_rust::{Color, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, IntRect};+use std::cell::{Cell, OnceCell, RefCell};+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::hash::{BuildHasher, Hasher};+use std::sync::Arc;++mod chunk_placement;+mod coverage;++pub(crate) use chunk_placement::ChunkRecord;+pub use chunk_placement::{ChunkPlacedInRasterSpace, PlacedRecordRangeIndex, RecordIndexInChunk, RecordTable};+use chunk_placement::{+ FRAME_STATE_CARET_BLINK_PHASE, FRAME_STATE_LIVE_CONTENT, FRAME_STATE_SAMPLED_BACKGROUND_COLOR,+ FRAME_STATE_SCROLL_BAR, FRAME_STATE_SPACES_OF_INLINE_CLIPS, PlacedRecordRange,+ background_color_animation_effect_of,+};+pub use coverage::TileCoverage;++pub type ContentHash = u128;++const LOW_HALF_SEED: u64 = 0x243f_6a88_85a3_08d3;+const HIGH_HALF_SEED: u64 = 0x1319_8a2e_0370_7344;+// The farthest past its cell that a tile is rastered, in device pixels. A tile whose backdrop filters read farther takes+// how far as not known, which keeps the rects that rastering inflates by it within the limits of an `IntRect`.+const LARGEST_RASTER_MARGIN_IN_DEVICE_PIXELS: i32 = 4 * LARGEST_FILTER_READ_REACH_IN_DEVICE_PIXELS as i32;++struct ContentHasher {+ low: FoldHasher<'static>,+ high: FoldHasher<'static>,+}++impl ContentHasher {+ fn new() -> Self {+ Self {+ low: FixedState::with_seed(LOW_HALF_SEED).build_hasher(),+ high: FixedState::with_seed(HIGH_HALF_SEED).build_hasher(),+ }+ }++ fn write_bytes(&mut self, bytes: &[u8]) {+ self.write_u64(bytes.len() as u64);+ self.low.write(bytes);+ self.high.write(bytes);+ }++ fn write_u64(&mut self, value: u64) {+ self.low.write_u64(value);+ self.high.write_u64(value);+ }++ fn write_u32(&mut self, value: u32) {+ self.low.write_u32(value);+ self.high.write_u32(value);+ }++ fn write_i32(&mut self, value: i32) {+ self.write_u32(value as u32);+ }++ fn write_bool(&mut self, value: bool) {+ self.write_u32(u32::from(value));+ }++ fn write_f32(&mut self, value: f32) {+ self.write_u32(value.to_bits());+ }++ fn write_content_hash(&mut self, content_hash: ContentHash) {+ self.write_u64(content_hash as u64);+ self.write_u64((content_hash >> 64) as u64);+ }++ fn write_int_rect(&mut self, rect: IntRect) {+ self.write_i32(rect.x);+ self.write_i32(rect.y);+ self.write_i32(rect.width);+ self.write_i32(rect.height);+ }++ fn write_float_rect(&mut self, rect: FloatRect) {+ self.write_f32(rect.x);+ self.write_f32(rect.y);+ self.write_f32(rect.width);+ self.write_f32(rect.height);+ }++ fn write_float_point(&mut self, point: FloatPoint) {+ self.write_f32(point.x);+ self.write_f32(point.y);+ }++ fn write_matrix(&mut self, matrix: &FloatMatrix4x4) {+ for row in &matrix.elements {+ for value in row {+ self.write_f32(*value);+ }+ }+ }++ fn write_corner_radii(&mut self, corner_radii: &libgfx_rust::CornerRadii) {+ for corner in [+ corner_radii.top_left,+ corner_radii.top_right,+ corner_radii.bottom_right,+ corner_radii.bottom_left,+ ] {+ self.write_i32(corner.horizontal_radius);+ self.write_i32(corner.vertical_radius);+ }+ }++ fn finish(&self) -> ContentHash {+ (u128::from(self.high.finish()) << 64) | u128::from(self.low.finish())+ }+}++pub trait LiveContentVersions {+ fn canvas_content_generation(&self, canvas: CanvasId) -> u64;+ fn video_frame_id(&self, video_sink: VideoSinkHandle) -> Option<u64>;+ fn image_frame_pixel_generation(&self, image_frame: ImageFrameResourceId) -> Option<u64>;+ fn nested_context_frame_generation(&self, nested_context: CompositorContextId) -> Option<u64>;+}++#[derive(Clone, Copy)]+pub struct FrameStateReadByReplay<'a> {+ pub scrollbars: &'a [ScrollbarShownByFrame],+ pub time_ns: i64,+ pub live_content: &'a dyn LiveContentVersions,+}++#[derive(Clone, Copy)]+pub struct LayerRasterSettings {+ pub raster_space_identity: u64,+ pub clear_color: Color,+ pub root_group_color: Color,+ pub viewport_to_raster_transform: FloatMatrix4x4,+ pub allows_lcd_text: bool,+}++impl LayerRasterSettings {+ pub fn content_hash(&self) -> ContentHash {+ let mut hasher = ContentHasher::new();+ hasher.write_u64(self.raster_space_identity);+ hasher.write_u32(self.clear_color.0);+ hasher.write_u32(self.root_group_color.0);+ hasher.write_matrix(&self.viewport_to_raster_transform);+ hasher.write_bool(self.allows_lcd_text);+ hasher.finish()+ }+}++pub struct TileKeyingOfList<'a> {+ display_list: &'a DisplayListStorage,+ effect_clips: &'a EffectClipPlan,+ tree: &'a VisualContextTree,+ frame_state: FrameStateReadByReplay<'a>,+ // Worked out on first use, as most frames bind no band and key no tile.+ run_groups: OnceCell<Arc<RunGroups>>,+ filters_of_effects: OnceCell<FiltersOfEffects>,+ filters_inside_composited_effects: OnceCell<FiltersOfEffects>,+ replays_every_record_into_every_tile: bool,+ tree_sorts_planes_by_depth: bool,+ frame_state_hash: ContentHash,+ innermost_composited_effect_by_effect_index: Vec<EffectNodeIndex>,+ /// Per effect, the nearest effect at or around it that the compositor composites or that is not a plain group,+ /// once the coverage of a tile asks.+ nearest_composited_or_not_plain_effect_by_effect_index: OnceCell<Vec<EffectNodeIndex>>,+ /// Per effect, the nearest effect at or around it that the compositor composites or whose blend mode can lower the+ /// alpha of what is below it, once the coverage of a tile asks.+ nearest_composited_or_alpha_lowering_effect_by_effect_index: OnceCell<Vec<EffectNodeIndex>>,+}++impl<'a> TileKeyingOfList<'a> {+ /// Prepares keying the tiles of a frame's list, of which `stack` was worked out.+ pub fn new(+ display_list: &'a DisplayListStorage,+ tree: &'a VisualContextTree,+ stack: &LayerStack,+ frame_state: FrameStateReadByReplay<'a>,+ ) -> Self {+ let layering_obstacles = stack.layering_obstacles;+ let mut is_composited_by_effect_index = vec![false; tree.effect_nodes.len()];+ for composited in &stack.composited_effects {+ is_composited_by_effect_index[composited.effect.0 as usize] = true;+ }+ let innermost_composited_effect_by_effect_index =+ nearest_effects_at_or_above_where(tree, |effect, _| is_composited_by_effect_index[effect.0 as usize]);+ Self {+ display_list,+ effect_clips: display_list.effect_clip_plan(tree),+ tree,+ frame_state,+ run_groups: OnceCell::new(),+ filters_of_effects: OnceCell::new(),+ filters_inside_composited_effects: OnceCell::new(),+ replays_every_record_into_every_tile: layering_obstacles.every_tile_replays_every_record()+ || stack.one_layer_list_cannot_tell_which_records_show_in_tile(),+ tree_sorts_planes_by_depth: layering_obstacles.sorts_planes_by_depth,+ frame_state_hash: frame_state_hash_of(display_list, &frame_state),+ innermost_composited_effect_by_effect_index,+ nearest_composited_or_not_plain_effect_by_effect_index: OnceCell::new(),+ nearest_composited_or_alpha_lowering_effect_by_effect_index: OnceCell::new(),+ }+ }++ fn run_groups(&self) -> &RunGroups {+ self.run_groups.get_or_init(|| self.display_list.run_groups(self.tree))+ }++ fn filters_of_effects(&self) -> &FiltersOfEffects {+ self.filters_of_effects+ .get_or_init(|| FiltersOfEffects::of(self.tree, None, false))+ }++ fn filters_inside_composited_effects(&self) -> &FiltersOfEffects {+ self.filters_inside_composited_effects.get_or_init(|| {+ FiltersOfEffects::of(+ self.tree,+ Some(&self.innermost_composited_effect_by_effect_index),+ false,+ )+ })+ }++ fn compositor_composites(&self, effect: EffectNodeIndex) -> bool {+ self.innermost_composited_effect_by_effect_index[effect.0 as usize] == effect+ }+}++fn version_of_live_content(live_content: &dyn LiveContentVersions, content: LiveContent) -> u64 {+ match content {+ LiveContent::Canvas(canvas) => live_content.canvas_content_generation(canvas),+ LiveContent::VideoFrame(video_sink) => live_content.video_frame_id(video_sink).unwrap_or(u64::MAX),+ LiveContent::ImageFrame(image_frame) => live_content+ .image_frame_pixel_generation(image_frame)+ .unwrap_or(u64::MAX),+ LiveContent::CompositedContext(nested_context) => live_content+ .nested_context_frame_generation(nested_context)+ .unwrap_or(u64::MAX),+ }+}++fn write_scrollbar_shown_by_frame(hasher: &mut ContentHasher, scrollbar: &ScrollbarShownByFrame) {+ hasher.write_float_rect(scrollbar.gutter_rect);+ hasher.write_float_rect(scrollbar.thumb_rect);+ hasher.write_f32(scrollbar.expansion);+ hasher.write_f32(scrollbar.opacity);+}++fn frame_state_hash_of(display_list: &DisplayListStorage, frame_state: &FrameStateReadByReplay<'_>) -> ContentHash {+ let summary = display_list.summary();+ let mut hasher = ContentHasher::new();+ for caret in &summary.carets {+ let (_, payload) = display_list.record_at(caret.position);+ hasher.write_bool(caret_is_visible_at_time(+ &read_command::<PaintCaret>(payload),+ frame_state.time_ns,+ ));+ }+ for scrollbar in frame_state.scrollbars {+ hasher.write_u32(scrollbar.scroll_node_index.0);+ hasher.write_bool(scrollbar.vertical);+ write_scrollbar_shown_by_frame(&mut hasher, scrollbar);+ }+ for live_content_record in &summary.live_content_records {+ hasher.write_u64(version_of_live_content(+ frame_state.live_content,+ live_content_record.content,+ ));+ }+ hasher.finish()+}++struct BackdropReadInLayer {+ first_record_position: ListPosition,+ region_reach: Reach<IntRect>,+ backdrop_read_reach: Reach<IntRect>,+ read_reach_in_device_pixels: Option<i32>,+ spread_past_region_in_device_pixels: i32,+ // A mirroring blur stops at the frame's edge where its region reaches past the frame, as a raster of the frame+ // does.+ mirroring_blur_region: Option<Reach<IntRect>>,+}++impl BackdropReadInLayer {+ fn blur_mirrors_at_edge_of_frame(&self, frame: IntRect) -> bool {+ match self.mirroring_blur_region {+ None | Some(Reach::Nothing) => false,+ Some(Reach::Within(region)) => !frame.contains_rect(region),+ Some(Reach::Anywhere) => true,+ }+ }+}++// The most backdrop reads that a band follows one by one, and the most passes over them that follow the reach of+// content through reads that read one another. Past either, content that a backdrop read can reach reaches the regions+// of every backdrop read of the band, and the cells those regions touch take what their tiles read as not known.+const MAXIMUM_BACKDROP_READS_A_BAND_FOLLOWS_ONE_BY_ONE: usize = 64;+const MAXIMUM_PASSES_OVER_BACKDROP_READS: usize = 8;++/// The backdrop reads of the layers of a band, in the paint order of their first records.+struct BackdropReadsOfBand {+ reads_in_paint_order: Vec<BackdropReadInLayer>,+ region_reach_of_every_read: Reach<IntRect>,+}++impl BackdropReadsOfBand {+ fn new(reads_in_paint_order: Vec<BackdropReadInLayer>) -> Self {+ debug_assert!(+ reads_in_paint_order+ .windows(2)+ .all(|pair| pair[0].first_record_position <= pair[1].first_record_position)+ );+ let region_reach_of_every_read = reads_in_paint_order+ .iter()+ .fold(Reach::Nothing, |united, read| united.united(read.region_reach));+ Self {+ reads_in_paint_order,+ region_reach_of_every_read,+ }+ }++ fn is_empty(&self) -> bool {+ self.reads_in_paint_order.is_empty()+ }++ fn are_followed_one_by_one(&self) -> bool {+ self.reads_in_paint_order.len() <= MAXIMUM_BACKDROP_READS_A_BAND_FOLLOWS_ONE_BY_ONE+ }++ // A tile that shows part of a backdrop filter's region must also hold what the filter reads past that part.+ fn reach_extended_through_reads(&self, mut reach: Reach<IntRect>, paint_position: ListPosition) -> Reach<IntRect> {+ let first_read_painted_after = self+ .reads_in_paint_order+ .partition_point(|read| read.first_record_position <= paint_position);+ let reads_painted_after = &self.reads_in_paint_order[first_read_painted_after..];+ if reads_painted_after.is_empty() {+ return reach;+ }+ if !self.are_followed_one_by_one() {+ return reach.united(self.region_reach_of_every_read);+ }+ let pass_count = self.reads_in_paint_order.len() + 1;+ for _ in 0..pass_count.min(MAXIMUM_PASSES_OVER_BACKDROP_READS) {+ let mut reach_grew = false;+ for backdrop_read in reads_painted_after {+ let Reach::Within(rect) = reach else {+ continue;+ };+ if !backdrop_read.backdrop_read_reach.touches(rect) {+ continue;+ }+ let reach_through_backdrop_read =+ match (backdrop_read.region_reach, backdrop_read.read_reach_in_device_pixels) {+ (Reach::Within(region), Some(read_reach_in_device_pixels)) => {+ let distance =+ read_reach_in_device_pixels + backdrop_read.spread_past_region_in_device_pixels;+ Reach::Within(+ rect.inflated_edges(distance, distance, distance, distance)+ .intersected(region),+ )+ }+ (region_reach, _) => region_reach,+ };+ let extended = reach.united(reach_through_backdrop_read);+ if extended != reach {+ reach = extended;+ reach_grew = true;+ }+ }+ if !reach_grew {+ return reach;+ }+ }+ if pass_count > MAXIMUM_PASSES_OVER_BACKDROP_READS {+ return reach.united(self.region_reach_of_every_read);+ }+ reach+ }++ /// How far past `cell` its tiles are rastered, in device pixels: as far as the backdrop filters whose regions touch+ /// the cell read and spread what they read, or none where that is not known or is farther than+ /// `LARGEST_RASTER_MARGIN_IN_DEVICE_PIXELS`.+ fn raster_margin_of_cell(&self, cell: IntRect) -> Option<i32> {+ if !self.are_followed_one_by_one() {+ return (!self.region_reach_of_every_read.touches(cell)).then_some(0);+ }+ self.reads_in_paint_order+ .iter()+ .filter(|backdrop_read| backdrop_read.region_reach.touches(cell))+ .try_fold(0i32, |margin, backdrop_read| {+ Some(+ margin+ .saturating_add(backdrop_read.read_reach_in_device_pixels?)+ .saturating_add(backdrop_read.spread_past_region_in_device_pixels),+ )+ })+ .filter(|&margin| margin <= LARGEST_RASTER_MARGIN_IN_DEVICE_PIXELS)+ }++ /// The frame where the blurs of some backdrop read of the band mirror at its edge, in any cell.+ fn frame_edge_blurs_mirror_at(&self, frame: Option<IntRect>) -> Option<IntRect> {+ frame.filter(|frame| {+ if !self.are_followed_one_by_one() {+ return self.region_reach_of_every_read != Reach::Nothing;+ }+ self.reads_in_paint_order+ .iter()+ .any(|backdrop_read| backdrop_read.blur_mirrors_at_edge_of_frame(*frame))+ })+ }++ fn frame_edge_blurs_of_cell_mirror_at(&self, cell: IntRect, frame: Option<IntRect>) -> Option<IntRect> {+ frame.filter(|frame| {+ if !self.are_followed_one_by_one() {+ return self.region_reach_of_every_read.touches(cell);+ }+ self.reads_in_paint_order.iter().any(|backdrop_read| {+ backdrop_read.region_reach.touches(cell) && backdrop_read.blur_mirrors_at_edge_of_frame(*frame)+ })+ })+ }+}++impl RoundedRect {+ /// The rect in device pixels, where its space maps onto them by a scale and a translation.+ fn device_aligned_of(+ world: &WorldTransforms,+ spatial: SpatialNodeIndex,+ rect: FloatRect,+ corner_radii: &CornerRadii,+ ) -> Option<Self> {+ let matrix = world.draw_matrix(spatial);+ if !matrix.is_2d_affine() {+ return None;+ }+ let affine = matrix.extract_2d_affine();+ if affine.b() != 0.0 || affine.c() != 0.0 || affine.a() <= 0.0 || affine.d() <= 0.0 {+ return None;+ }+ let rect = world.map_rect_to_root(spatial, rect);+ if !is_finite_rect(rect) {+ return None;+ }+ let radius_in_device_pixels = |radius: &libgfx_rust::CornerRadius| {+ (+ radius.horizontal_radius as f32 * affine.a(),+ radius.vertical_radius as f32 * affine.d(),+ )+ };+ Some(Self {+ rect,+ horizontal_and_vertical_radii_clockwise_from_top_left: [+ radius_in_device_pixels(&corner_radii.top_left),+ radius_in_device_pixels(&corner_radii.top_right),+ radius_in_device_pixels(&corner_radii.bottom_right),+ radius_in_device_pixels(&corner_radii.bottom_left),+ ],+ })+ }++ fn write_part_within_or_whole_if_corner_reaches_in(&self, hasher: &mut ContentHasher, area: FloatRect) {+ for (horizontal, vertical) in self.horizontal_and_vertical_radii_clockwise_from_top_left {+ hasher.write_f32(horizontal);+ hasher.write_f32(vertical);+ }+ let rect = self.rect;+ if self.rounded_corner_reaches_into(area) {+ hasher.write_u32(1);+ hasher.write_float_rect(rect);+ return;+ }+ let part = rect.intersected(area);+ if part.is_empty() {+ hasher.write_u32(2);+ return;+ }+ hasher.write_u32(3);+ hasher.write_float_rect(part);+ }+}++struct ContentHashesNearArea {+ area: FloatRect,+ content_hash_by_clip: HashMap<u32, ContentHash>,+ content_hash_by_effect: HashMap<u32, ContentHash>,+}++impl ContentHashesNearArea {+ /// The area that the tiles of the cell at `coord` raster within, where their raster margin is known.+ fn of_cell(coord: TileCoord, raster_margin_in_device_pixels: Option<i32>) -> Option<Self> {+ raster_margin_in_device_pixels.map(|backdrop_read_margin| {+ let margin = 2.0 * (ANTIALIASING_MARGIN_IN_DEVICE_PIXELS + backdrop_read_margin) as f32;+ Self {+ area: coord.cell_rect().to_float().inflated(margin, margin),+ content_hash_by_clip: HashMap::new(),+ content_hash_by_effect: HashMap::new(),+ }+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+enum TileReplayItem {+ PlacedRecordRange {+ chunk_index: ChunkIndexInList,+ range_index: PlacedRecordRangeIndex,+ },+ // The records of a span of a chunk: one that every tile replays, or a record that no placed record range of the band+ // holds, replayed for the mask content it declares.+ RecordSpan {+ chunk_index: ChunkIndexInList,+ begin_offset: u32,+ end_offset: u32,+ },+}++impl TileReplayItem {+ fn chunk_index(&self) -> ChunkIndexInList {+ match *self {+ TileReplayItem::PlacedRecordRange { chunk_index, .. } | TileReplayItem::RecordSpan { chunk_index, .. } => {+ chunk_index+ }+ }+ }+}++/// A tile of a layer of a band, with the hash of what it holds, the replay items of the band replayed into it, and how+/// far past its cell content is read to raster it.+pub struct KeyedTile {+ pub layer_index: LayerIndex,+ pub coord: TileCoord,+ pub content_hash: ContentHash,+ pub raster_margin_in_device_pixels: Option<i32>,+ /// Which barriers cut the tile: tiles of a layer that are cut alike hold every replay item that reaches them alike,+ /// so one replay can raster them together.+ pub cuts: BarrierCutsOfCell,+ /// The part of the tile's cell that what it holds can reach.+ pub content_bounds: IntRect,+ replay_items_in_paint_order: Vec<TileReplayItem>,+}++/// A chunk that the spans of a band hold runs of. The spans hold whole runs.+struct ChunkHeldByBand {+ chunk_index: ChunkIndexInList,+ placement: Arc<ChunkPlacedInRasterSpace>,+ held_run_indices: Vec<RunIndexInChunk>,+ reach_of_held_records: Reach<IntRect>,+}++struct RunReplayedWholeWhereverRunGroupShows {+ reach: Reach<IntRect>,+ /// The innermost mask around the run with declared content, whose declarations, and those of the declared masks+ /// around it, replay with the run, or `EffectNodeIndex::NONE`.+ innermost_declared_mask_around: EffectNodeIndex,+}++/// A mask with declared content around a run that a band replays whole.+struct DeclaredMaskAroundRunReplayedWhole {+ /// The items that replay its declarations, each with where it is painted and how far it reaches.+ declarations: Vec<(ListPosition, TileReplayItem, Reach<IntRect>)>,+ next_declared_mask_around: EffectNodeIndex,+}++type RunsReplayedWhole = HashMap<(ChunkIndexInList, RunIndexInChunk), RunReplayedWholeWhereverRunGroupShows>;++/// The masks with declared content, for a band that replays runs whole: where the list declares the content of each, and+/// per effect the nearest such mask at or around it.+struct MasksWithDeclaredContent {+ declaration_positions_by_mask: HashMap<EffectNodeIndex, Vec<ListPosition>>,+ nearest_declared_mask_by_effect_index: Vec<EffectNodeIndex>,+}++impl MasksWithDeclaredContent {+ fn nearest_declared_mask_at_or_above(&self, effect: EffectNodeIndex) -> EffectNodeIndex {+ self.nearest_declared_mask_by_effect_index+ .get(effect.0 as usize)+ .copied()+ .unwrap_or(EffectNodeIndex::NONE)+ }+}++struct BandBoundToListAndGeometry {+ /// In the order of their chunks, as the spans of a band are in paint order.+ held_chunks: Vec<ChunkHeldByBand>,+ runs_replayed_whole: RunsReplayedWhole,+ declared_masks_around_runs_replayed_whole: HashMap<EffectNodeIndex, DeclaredMaskAroundRunReplayedWhole>,+ backdrop_reads: BackdropReadsOfBand,+ items_replayed_in_every_tile: Option<Vec<(ListPosition, TileReplayItem)>>,+ replays_records_reading_frame_state_hashed_for_the_list: bool,+}++impl BandBoundToListAndGeometry {+ fn held_chunk_if_held(&self, chunk_index: ChunkIndexInList) -> Option<&ChunkHeldByBand> {+ self.held_chunks+ .binary_search_by_key(&chunk_index, |held_chunk| held_chunk.chunk_index)+ .ok()+ .map(|held_chunk_index| &self.held_chunks[held_chunk_index])+ }++ fn held_chunk(&self, chunk_index: ChunkIndexInList) -> &ChunkHeldByBand {+ self.held_chunk_if_held(chunk_index)+ .expect("an item of a band names a chunk the band holds")+ }++ fn placed_record_range(+ &self,+ chunk_index: ChunkIndexInList,+ range_index: PlacedRecordRangeIndex,+ ) -> &PlacedRecordRange {+ &self.held_chunk(chunk_index).placement.record_ranges[range_index.0 as usize]+ }++ fn reach_of_item(&self, item: TileReplayItem) -> Reach<IntRect> {+ let TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index,+ } = item+ else {+ return Reach::Nothing;+ };+ let held_chunk = self.held_chunk(chunk_index);+ let range = &held_chunk.placement.record_ranges[range_index.0 as usize];+ if let Some(run_replayed_whole) = self.runs_replayed_whole.get(&(chunk_index, range.run_index))+ && held_chunk.placement.ranges_of_each_run[range.run_index.0 as usize].whole_run_range_index == range_index+ {+ return run_replayed_whole.reach;+ }+ self.backdrop_reads+ .reach_extended_through_reads(range.reach, ListPosition::new(chunk_index, range.begin_offset))+ }++ fn span_of(&self, item: TileReplayItem) -> ListSpan {+ let (chunk_index, begin_offset, end_offset) = match item {+ TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index,+ } => {+ let range = self.placed_record_range(chunk_index, range_index);+ (chunk_index, range.begin_offset, range.end_offset)+ }+ TileReplayItem::RecordSpan {+ chunk_index,+ begin_offset,+ end_offset,+ } => (chunk_index, begin_offset, end_offset),+ };+ ListSpan {+ begin: ListPosition::new(chunk_index, begin_offset),+ end: ListPosition::new(chunk_index, end_offset),+ }+ }++ fn item_replaying_record(+ &self,+ display_list: &DisplayListStorage,+ chunk_index: ChunkIndexInList,+ record_index: RecordIndexInChunk,+ ) -> TileReplayItem {+ let table = display_list.chunk(chunk_index).record_table();+ let record = table.record(record_index);+ let record_alone = TileReplayItem::RecordSpan {+ chunk_index,+ begin_offset: record.offset,+ end_offset: record.end_offset,+ };+ let Some(held_chunk) = self.held_chunk_if_held(chunk_index) else {+ return record_alone;+ };+ let run_index = record.run_index;+ if held_chunk.held_run_indices.binary_search(&run_index).is_err() {+ return record_alone;+ }+ let ranges_of_run = &held_chunk.placement.ranges_of_each_run[run_index.0 as usize];+ if self.runs_replayed_whole.contains_key(&(chunk_index, run_index)) {+ return TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index: ranges_of_run.whole_run_range_index,+ };+ }+ // The binned ranges of a run are in the order of their records and apart.+ let first_binned_range_index = ranges_of_run.first_binned_range_index;+ let binned_ranges = &held_chunk.placement.record_ranges+ [first_binned_range_index.0 as usize..ranges_of_run.whole_run_range_index.0 as usize];+ let position_among_binned_ranges =+ binned_ranges.partition_point(|range| range.end_record_index <= record_index);+ match binned_ranges.get(position_among_binned_ranges) {+ Some(range) if range.first_record_index <= record_index => TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index: PlacedRecordRangeIndex(first_binned_range_index.0 + position_among_binned_ranges as u32),+ },+ _ => record_alone,+ }+ }++ fn for_each_held_item(+ &self,+ held_chunk: &ChunkHeldByBand,+ mut visit: impl FnMut(ListPosition, TileReplayItem, Reach<IntRect>, EffectNodeIndex),+ ) {+ for &run_index in &held_chunk.held_run_indices {+ let ranges_of_run = &held_chunk.placement.ranges_of_each_run[run_index.0 as usize];+ if let Some(run_replayed_whole) = self.runs_replayed_whole.get(&(held_chunk.chunk_index, run_index)) {+ let whole_run_range =+ &held_chunk.placement.record_ranges[ranges_of_run.whole_run_range_index.0 as usize];+ visit(+ ListPosition::new(held_chunk.chunk_index, whole_run_range.begin_offset),+ TileReplayItem::PlacedRecordRange {+ chunk_index: held_chunk.chunk_index,+ range_index: ranges_of_run.whole_run_range_index,+ },+ run_replayed_whole.reach,+ run_replayed_whole.innermost_declared_mask_around,+ );+ continue;+ }+ for range_index in (ranges_of_run.first_binned_range_index.0..ranges_of_run.whole_run_range_index.0)+ .map(PlacedRecordRangeIndex)+ {+ let range = &held_chunk.placement.record_ranges[range_index.0 as usize];+ let paint_position = ListPosition::new(held_chunk.chunk_index, range.begin_offset);+ visit(+ paint_position,+ TileReplayItem::PlacedRecordRange {+ chunk_index: held_chunk.chunk_index,+ range_index,+ },+ self.backdrop_reads+ .reach_extended_through_reads(range.reach, paint_position),+ EffectNodeIndex::NONE,+ );+ }+ }+ }++ fn work_out_reach_of_held_records(&mut self, display_list: &DisplayListStorage) {+ for held_chunk_index in 0..self.held_chunks.len() {+ let held_chunk = &self.held_chunks[held_chunk_index];+ let mut reach_of_runs_replayed_whole = Reach::Nothing;+ let mut reach_of_runs_binned_range_by_range = Reach::Nothing;+ for &run_index in &held_chunk.held_run_indices {+ match self.runs_replayed_whole.get(&(held_chunk.chunk_index, run_index)) {+ Some(run_replayed_whole) => {+ reach_of_runs_replayed_whole = reach_of_runs_replayed_whole.united(run_replayed_whole.reach);+ }+ None => {+ reach_of_runs_binned_range_by_range = reach_of_runs_binned_range_by_range.united(+ held_chunk.placement.ranges_of_each_run[run_index.0 as usize].reach_of_binned_ranges,+ );+ }+ }+ }+ // A backdrop filter can extend content painted before it past the cells that content reaches.+ if !self.backdrop_reads.is_empty() {+ let first_held_offset = held_chunk.held_run_indices.first().map_or(0, |run_index| {+ display_list.chunk(held_chunk.chunk_index).runs()[run_index.0 as usize].offset+ });+ reach_of_runs_binned_range_by_range = self.backdrop_reads.reach_extended_through_reads(+ reach_of_runs_binned_range_by_range,+ ListPosition::new(held_chunk.chunk_index, first_held_offset),+ );+ }+ self.held_chunks[held_chunk_index].reach_of_held_records =+ reach_of_runs_replayed_whole.united(reach_of_runs_binned_range_by_range);+ }+ }+}++/// What the tiles of the layers of one band hold, kept from frame to frame while the band is bound to one list and one+/// geometry: the tiles keyed so far, binned against the list, the geometry and the band of the stack they are bound to.+/// Every tile is keyed again where a value of the frame that some tile of the band can read changed.+pub struct BandTileKeys {+ cells: BTreeMap<TileCoord, Vec<KeyedTile>>,+ /// The cells where the band holds tiles at every cell it can hold something in, as the latest frame keyed them.+ /// Only the cells where the band can hold something have an entry in `cells`, so a frame that shows no cell outside+ /// these looks for no cell to key.+ cells_looked_at: CellRange,+ bound_band: BandBoundToListAndGeometry,+ values_of_frame_tiles_were_keyed_with: Option<ValuesOfFrameThatTilesOfBandRead>,+}++/// What the tiles of a band read of a frame besides the records they replay. A frame keys every tile of the band again+/// where any of these differs from the frame before.+#[derive(Clone, Copy, PartialEq, Eq)]+struct ValuesOfFrameThatTilesOfBandRead {+ frame_state_hash: Option<ContentHash>,+ tree_copy_number: u64,+ raster_settings_hash_of_layers_of_band: ContentHash,+ frame_edge_backdrop_blurs_mirror_at: Option<IntRect>,+}++/// What keying the shown tiles of a band did.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct TileKeyingCounts {+ pub tiles_keyed: usize,+ /// The cells binned anew where the band holds something.+ pub cells_binned: usize,+}++impl BandTileKeys {+ pub fn tile(&self, coord: TileCoord, layer: LayerIndex) -> Option<&KeyedTile> {+ self.cells.get(&coord)?.iter().find(|tile| tile.layer_index == layer)+ }++ /// The keyed tiles within `rect`, by row and then by layer. A rect of any size costs no more than the cells the+ /// band holds.+ pub fn tiles_within(&self, rect: IntRect) -> impl Iterator<Item = &KeyedTile> {+ entries_within(&self.cells, CellRange::touched_by(rect)).flat_map(|(_, tiles)| tiles)+ }++ pub fn record_spans_of_tiles<'a>(&self, tiles: impl IntoIterator<Item = &'a KeyedTile>) -> Vec<ListSpan> {+ let bound_band = &self.bound_band;+ let mut spans: Vec<ListSpan> = tiles+ .into_iter()+ .flat_map(|tile| {+ tile.replay_items_in_paint_order+ .iter()+ .map(|item| bound_band.span_of(*item))+ })+ .collect();+ spans.sort_unstable_by_key(|span| (span.begin, span.end));+ spans.dedup();+ let mut merged: Vec<ListSpan> = Vec::with_capacity(spans.len());+ for span in spans {+ match merged.last_mut() {+ Some(last) if last.end >= span.begin => last.end = last.end.max(span.end),+ _ => merged.push(span),+ }+ }+ merged+ }+}++/// The most cells that one band keys in a frame. A frame keys only the cells where the band can hold something and+/// that the frame shows. A viewport of a real size shows content at a sane scale in far fewer cells. A transform that+/// the compositor animates can show large content at a small part of the scale it is rastered at, and then the frame+/// shows many more cells of it. This bounds the work and the tiles of the band in such a frame: it keys only the cells+/// nearest to the middle of the shown rect, and shows nothing in the others.+pub const MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME: usize = 4096;++/// Per chunk that `record_spans` hold records of, in the order of the chunks, the offset ranges they hold there, joined+/// where they touch.+fn held_offset_ranges_by_chunk(+ display_list: &DisplayListStorage,+ record_spans: &[ListSpan],+) -> Vec<(ChunkIndexInList, Vec<(u32, u32)>)> {+ let mut held_offset_ranges_by_chunk: Vec<(ChunkIndexInList, Vec<(u32, u32)>)> = Vec::new();+ for span in record_spans {+ for (chunk_index, begin, end) in display_list.parts_of_span(*span) {+ match held_offset_ranges_by_chunk.last_mut() {+ Some((last_chunk_index, held_offset_ranges)) if *last_chunk_index == chunk_index => {+ match held_offset_ranges.last_mut() {+ Some(last) if last.1 == begin => last.1 = end,+ _ => held_offset_ranges.push((begin, end)),+ }+ }+ _ => held_offset_ranges_by_chunk.push((chunk_index, vec![(begin, end)])),+ }+ }+ }+ held_offset_ranges_by_chunk+}++/// The runs of a chunk that `held_offset_ranges`, which are in order and of whole runs, hold.+fn runs_within_held_offset_ranges(+ runs: &[DisplayListCommandRun],+ held_offset_ranges: &[(u32, u32)],+) -> Vec<RunIndexInChunk> {+ let mut held_runs = Vec::new();+ for &(begin, end) in held_offset_ranges {+ let first_run_index = runs.partition_point(|run| run.offset < begin);+ let end_run_index = runs.partition_point(|run| run.offset < end);+ debug_assert!(+ first_run_index < end_run_index+ && runs[first_run_index].offset == begin+ && runs[end_run_index - 1].offset + runs[end_run_index - 1].size == end,+ "the checks of a plan take only bands whose spans are of whole runs"+ );+ held_runs.extend((first_run_index..end_run_index).map(|run_index| RunIndexInChunk(run_index as u32)));+ }+ held_runs+}++/// Whether `held_offset_ranges`, which are in order and apart, hold the record at `offset`.+fn offset_is_held(held_offset_ranges: &[(u32, u32)], offset: u32) -> bool {+ let index = held_offset_ranges.partition_point(|&(_, end)| end <= offset);+ held_offset_ranges.get(index).is_some_and(|&(begin, _)| begin <= offset)+}++/// The cells of `shown_rect` that a band keys in a frame: those where it can hold something and holds no tiles yet.+/// The band can hold the base layer and items replayed into every tile at every cell, and the records of a held chunk+/// where the chunk reaches. Where those are more than `MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME` cells, the band keys+/// only those nearest to the middle of `shown_rect`, and forgets its tiles at all other cells.+fn coords_to_key(+ cells: &mut BTreeMap<TileCoord, Vec<KeyedTile>>,+ cells_looked_at: &mut CellRange,+ bound_band: &BandBoundToListAndGeometry,+ holds_base_layer: bool,+ shown_rect: IntRect,+) -> Vec<TileCoord> {+ let shown_cells = CellRange::touched_by(shown_rect);+ if cells_looked_at.contains_range(shown_cells) {+ return Vec::new();+ }+ // The band of the base layer is in a space that an offset maps to the frame, so it shows about the cells of the+ // viewport. The budget holds a received stack that says otherwise.+ let mut ranges_of_content: Vec<CellRange> = if holds_base_layer || bound_band.items_replayed_in_every_tile.is_some()+ {+ vec![shown_cells]+ } else {+ let area_of_shown_cells = shown_cells.rect();+ bound_band+ .held_chunks+ .iter()+ .map(|held_chunk| CellRange::touched_by(held_chunk.reach_of_held_records.part_of(area_of_shown_cells)))+ .filter(|range| !range.is_empty())+ .collect()+ };+ ranges_of_content.sort_unstable();+ ranges_of_content.dedup();+ let coords_of_content = match coords_within_ranges_up_to(&ranges_of_content, MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME)+ {+ Some(coords_of_content) => {+ *cells_looked_at = shown_cells;+ coords_of_content+ }+ None => {+ let middle = TileCoord::of_pixel(+ shown_rect.x + shown_rect.width / 2,+ shown_rect.y + shown_rect.height / 2,+ );+ let window = window_within_budget(+ &ranges_of_content,+ shown_cells,+ middle,+ MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME,+ );+ cells.retain(|coord, _| window.contains(*coord));+ *cells_looked_at = window.intersected(shown_cells);+ ranges_of_content+ .iter()+ .flat_map(|range| range.intersected(window).coords())+ .collect()+ }+ };+ coords_of_content+ .into_iter()+ .filter(|coord| !cells.contains_key(coord))+ .collect()+}++/// The cells of `ranges`, row by row, or none where they are more than `limit`. It visits at most `limit` cells of a+/// range, and stops when it has found more than `limit`.+fn coords_within_ranges_up_to(ranges: &[CellRange], limit: usize) -> Option<BTreeSet<TileCoord>> {+ let mut coords = BTreeSet::new();+ for range in ranges {+ if range.cell_count() > limit as u64 {+ return None;+ }+ coords.extend(range.coords());+ if coords.len() > limit {+ return None;+ }+ }+ Some(coords)+}++/// The largest window of cells around `middle` where `ranges` hold at most `budget` cells, or no cell where the ranges+/// hold more at `middle` alone. The ranges lie within `shown_cells` and hold more than `budget` cells there. A cell of+/// two ranges counts twice, so ranges that overlap can make the window hold fewer cells than `budget`.+fn window_within_budget(ranges: &[CellRange], shown_cells: CellRange, middle: TileCoord, budget: usize) -> CellRange {+ let cells_of_ranges_within = |distance: i32| -> u64 {+ let window = CellRange::around(middle, distance);+ ranges.iter().map(|range| range.intersected(window).cell_count()).sum()+ };+ if cells_of_ranges_within(0) > budget as u64 {+ return CellRange::NONE;+ }+ // The window at the distance to the farthest shown cell holds every range whole.+ let mut distance_within_budget = 0;+ let mut distance_past_budget = [+ shown_cells.last_row - middle.row,+ middle.row - shown_cells.first_row,+ shown_cells.last_column - middle.column,+ middle.column - shown_cells.first_column,+ ]+ .into_iter()+ .max()+ .unwrap_or(0)+ .max(1);+ while distance_past_budget - distance_within_budget > 1 {+ let distance = distance_within_budget + (distance_past_budget - distance_within_budget) / 2;+ if cells_of_ranges_within(distance) <= budget as u64 {+ distance_within_budget = distance;+ } else {+ distance_past_budget = distance;+ }+ }+ CellRange::around(middle, distance_within_budget)+}++/// The indices of the nodes of a chain from `index` up to, but not with, the first node whose value `known_value` gives,+/// and that value, or `value_above_root` where no node up to the root has a known value. `parent_index` gives the index+/// of a node's parent, which is `u32::MAX` at the root. A caller then works out the values of the nodes down from there,+/// each from its parent's, in a loop: a tree from another process can chain clips and effects deeper than a call stack+/// holds.+fn nodes_up_to_known_value<Value>(+ index: u32,+ parent_index: impl Fn(u32) -> u32,+ value_above_root: Value,+ mut known_value: impl FnMut(u32) -> Option<Value>,+) -> (Vec<u32>, Value) {+ let mut indices = Vec::new();+ let mut index = index;+ while index != u32::MAX {+ if let Some(value) = known_value(index) {+ return (indices, value);+ }+ indices.push(index);+ index = parent_index(index);+ }+ (indices, value_above_root)+}++struct LazyContentHashesPerNode {+ content_hash_by_node_index: RefCell<Vec<Option<ContentHash>>>,+ node_count: usize,+}++impl LazyContentHashesPerNode {+ fn new(node_count: usize) -> Self {+ Self {+ content_hash_by_node_index: RefCell::new(Vec::new()),+ node_count,+ }+ }++ fn get(&self, index: u32) -> Option<ContentHash> {+ self.content_hash_by_node_index+ .borrow()+ .get(index as usize)+ .copied()+ .flatten()+ }++ fn cache(&self, index: u32, content_hash: ContentHash) -> ContentHash {+ let mut content_hash_by_node_index = self.content_hash_by_node_index.borrow_mut();+ if content_hash_by_node_index.is_empty() {+ content_hash_by_node_index.resize(self.node_count, None);+ }+ content_hash_by_node_index[index as usize] = Some(content_hash);+ content_hash+ }+}++#[derive(Clone, Copy, PartialEq)]+enum EffectHashScope {+ AllEffects,+ EffectsDrawnInsideTiles,+ /// Every effect, but of those the compositor composites only what places their content: not their opacity or+ /// blend mode, which compositing applies, so that a chunk stays placed while the compositor animates them.+ WhatPlacingReads,+}++pub struct TileKeyingOfRasterSpace<'a> {+ list: &'a TileKeyingOfList<'a>,+ geometry: &'a RasterSpaceGeometry,+ spatial_content_hashes: LazyContentHashesPerNode,+ clip_content_hashes: LazyContentHashesPerNode,+ effect_content_hashes_by_scope: [LazyContentHashesPerNode; 3],+ /// Per effect, once worked out, how far past each pixel its filter and the filters around it read, in device+ /// pixels, or none where that is not known.+ read_reach_of_filters_at_and_around_by_effect_index: RefCell<Vec<Option<Option<i32>>>>,+ rastered_bounds_of_clips_by_first_and_end_clip: RefCell<HashMap<(ClipNodeIndex, ClipNodeIndex), Option<FloatRect>>>,+ clips_without_rastered_bounds: RefCell<Vec<ClipNodeIndex>>,+ chunks_placed: Cell<u64>,+}++const CONTENT_HASH_OF_EFFECT_LEFT_OUT_OF_TILES: ContentHash = 1;++impl<'a> TileKeyingOfRasterSpace<'a> {+ pub fn new(list: &'a TileKeyingOfList<'a>, geometry: &'a RasterSpaceGeometry) -> Self {+ let tree = list.tree;+ Self {+ list,+ geometry,+ spatial_content_hashes: LazyContentHashesPerNode::new(tree.spatial_nodes.len()),+ clip_content_hashes: LazyContentHashesPerNode::new(tree.clip_nodes.len()),+ effect_content_hashes_by_scope: [+ LazyContentHashesPerNode::new(tree.effect_nodes.len()),+ LazyContentHashesPerNode::new(tree.effect_nodes.len()),+ LazyContentHashesPerNode::new(tree.effect_nodes.len()),+ ],+ read_reach_of_filters_at_and_around_by_effect_index: RefCell::new(Vec::new()),+ rastered_bounds_of_clips_by_first_and_end_clip: RefCell::new(HashMap::new()),+ clips_without_rastered_bounds: RefCell::new(Vec::new()),+ chunks_placed: Cell::new(0),+ }+ }++ /// How many chunks were placed in the space since it was made, rather than found placed alike before.+ pub fn chunks_placed(&self) -> u64 {+ self.chunks_placed.get()+ }++ fn reach_of_content_within(&self, rect: FloatRect, context: ContextRef) -> Reach<IntRect> {+ let list = self.list;+ let filters_and_clips = FiltersAndClipsOfList {+ tree: list.tree,+ filters: list.filters_of_effects(),+ effect_clips: list.effect_clips,+ };+ let composited_effect = if context.effect.is_none() {+ EffectNodeIndex::NONE+ } else {+ list.innermost_composited_effect_by_effect_index[context.effect.0 as usize]+ };+ if composited_effect.is_none()+ || list+ .filters_of_effects()+ .nearest_spreading_effect_at_or_above(composited_effect)+ .is_none()+ {+ return self.geometry.reach_of_content(&filters_and_clips, rect, context);+ }+ self.geometry.reach_of_content_inside_composited_effect(+ &filters_and_clips,+ list.filters_inside_composited_effects(),+ rect,+ context,+ composited_effect,+ self.read_reach_in_device_pixels_of_filters_at_and_around(composited_effect),+ |first_clip, end_clip| {+ self.geometry.rastered_bounds_of_clips_from_up_to(+ list.tree,+ first_clip,+ end_clip,+ &mut self.rastered_bounds_of_clips_by_first_and_end_clip.borrow_mut(),+ &mut self.clips_without_rastered_bounds.borrow_mut(),+ )+ },+ )+ }++ fn read_reach_in_device_pixels_of_filters_at_and_around(&self, composited_effect: EffectNodeIndex) -> Option<i32> {+ let tree = self.list.tree;+ let mut known_read_reach_by_effect_index =+ self.read_reach_of_filters_at_and_around_by_effect_index.borrow_mut();+ if known_read_reach_by_effect_index.is_empty() {+ known_read_reach_by_effect_index.resize(tree.effect_nodes.len(), None);+ }+ let (effects_to_work_out, mut read_reach) = nodes_up_to_known_value(+ composited_effect.0,+ |effect| tree.effect_nodes[effect as usize].parent.0,+ Some(0i32),+ |effect| known_read_reach_by_effect_index[effect as usize],+ );+ for &effect in effects_to_work_out.iter().rev() {+ let node = &tree.effect_nodes[effect as usize];+ if let Some(filter) = spreading_filter_of(node) {+ read_reach = read_reach.and_then(|sum| {+ let filter_read_reach =+ filter_read_reach_in_device_pixels(filter, &self.geometry.world.draw_matrix(node.spatial))?;+ Some(sum.saturating_add(filter_read_reach))+ });+ }+ known_read_reach_by_effect_index[effect as usize] = Some(read_reach);+ }+ read_reach+ }++ fn backdrop_read_in_layer(+ &self,+ effect: EffectNodeIndex,+ first_record_position: ListPosition,+ ) -> BackdropReadInLayer {+ let tree = self.list.tree;+ let node = &tree.effect_nodes[effect.0 as usize];+ let EffectNodeData::Effects(effects) = &node.data else {+ unreachable!("only effects with a backdrop filter are read as backdrops");+ };+ let backdrop_filter = effects+ .backdrop_filter+ .as_ref()+ .expect("only effects with a backdrop filter are read as backdrops");+ let region_in_effect_space = backdrop_filter.region.to_float();+ let backdrop_context = ContextRef {+ spatial: node.spatial,+ clip: self.list.effect_clips.output_clip(effect),+ effect,+ };+ let region_reach = self.reach_of_content_within(region_in_effect_space, backdrop_context);+ let region_in_device_pixels = Some(+ self.geometry+ .world+ .map_rect_to_root(node.spatial, region_in_effect_space),+ )+ .filter(|rect| is_finite_rect(*rect))+ .map(enclosing_int_rect_within_extent_limit);+ let read_reach_in_device_pixels = region_in_device_pixels.and_then(|_| {+ filter_read_reach_in_device_pixels(&backdrop_filter.filter, &self.geometry.world.draw_matrix(node.spatial))+ });+ let spread_past_region_in_device_pixels = match (region_reach, region_in_device_pixels) {+ (Reach::Within(spread), Some(region)) if read_reach_in_device_pixels.is_some() => [+ region.x - spread.x,+ spread.right() - region.right(),+ region.y - spread.y,+ spread.bottom() - region.bottom(),+ ]+ .into_iter()+ .fold(0, i32::max),+ _ => 0,+ };+ BackdropReadInLayer {+ first_record_position,+ region_reach,+ backdrop_read_reach: backdrop_filter_read_reach(tree, self.geometry, effect),+ read_reach_in_device_pixels,+ spread_past_region_in_device_pixels,+ mirroring_blur_region: libgfx_rust::filter::Filter::serialized_has_mirroring_blur(&backdrop_filter.filter)+ .then(|| region_in_device_pixels.map_or(Reach::Anywhere, Reach::Within)),+ }+ }++ fn spatial_content_hash(&self, spatial: SpatialNodeIndex) -> ContentHash {+ if let Some(cached) = self.spatial_content_hashes.get(spatial.0) {+ return cached;+ }+ let mut hasher = ContentHasher::new();+ hasher.write_matrix(&self.geometry.world.draw_matrix(spatial));+ hasher.write_bool(self.geometry.world.backface_culled[spatial.0 as usize]);+ self.spatial_content_hashes.cache(spatial.0, hasher.finish())+ }++ fn clip_content_hash(&self, clip: ClipNodeIndex) -> ContentHash {+ let tree = self.list.tree;+ let (clips_to_hash, mut content_hash) = nodes_up_to_known_value(+ clip.0,+ |clip| tree.clip_nodes[clip as usize].parent.0,+ 0,+ |clip| self.clip_content_hashes.get(clip),+ );+ for clip in clips_to_hash.into_iter().rev().map(ClipNodeIndex) {+ if !self.geometry.clip_is_left_to_composite(clip) {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(content_hash);+ self.write_clip_node(&mut hasher, clip);+ content_hash = hasher.finish();+ }+ self.clip_content_hashes.cache(clip.0, content_hash);+ }+ content_hash+ }++ fn write_clip_node(&self, hasher: &mut ContentHasher, clip: ClipNodeIndex) {+ let node = &self.list.tree.clip_nodes[clip.0 as usize];+ hasher.write_content_hash(self.spatial_content_hash(node.spatial));+ hasher.write_bool(node.clips_everything);+ match &node.data {+ ClipNodeData::Rect(data) => {+ hasher.write_u32(1);+ hasher.write_float_rect(data.rect);+ hasher.write_corner_radii(&data.corner_radii);+ hasher.write_u32(data.mode as u32);+ }+ ClipNodeData::Path(data) => {+ hasher.write_u32(2);+ hasher.write_int_rect(data.bounding_rect);+ hasher.write_u32(data.fill_rule as u32);+ hasher.write_bytes(&data.path.serialize_to_bytes());+ }+ ClipNodeData::Dead => hasher.write_u32(3),+ }+ }++ fn clip_content_hash_near_area(&self, clip: ClipNodeIndex, near_area: &mut ContentHashesNearArea) -> ContentHash {+ let tree = self.list.tree;+ let (clips_to_hash, mut content_hash) = nodes_up_to_known_value(+ clip.0,+ |clip| tree.clip_nodes[clip as usize].parent.0,+ 0,+ |clip| near_area.content_hash_by_clip.get(&clip).copied(),+ );+ for clip in clips_to_hash.into_iter().rev().map(ClipNodeIndex) {+ content_hash = self.content_hash_of_clip_near_area(clip, content_hash, near_area);+ near_area.content_hash_by_clip.insert(clip.0, content_hash);+ }+ content_hash+ }++ fn content_hash_of_clip_near_area(+ &self,+ clip: ClipNodeIndex,+ parent_hash: ContentHash,+ near_area: &ContentHashesNearArea,+ ) -> ContentHash {+ let node = &self.list.tree.clip_nodes[clip.0 as usize];+ if self.geometry.clip_is_left_to_composite(clip) {+ parent_hash+ } else {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(parent_hash);+ let device_aligned_rect_and_mode = match &node.data {+ ClipNodeData::Rect(ClipData {+ rect,+ corner_radii,+ mode,+ }) => RoundedRect::device_aligned_of(&self.geometry.world, node.spatial, *rect, corner_radii)+ .map(|rect| (rect, *mode)),+ _ => None,+ };+ match device_aligned_rect_and_mode {+ Some((rect, mode)) => {+ hasher.write_u32(4);+ hasher.write_bool(node.clips_everything);+ hasher.write_u32(mode as u32);+ rect.write_part_within_or_whole_if_corner_reaches_in(&mut hasher, near_area.area);+ }+ None => self.write_clip_node(&mut hasher, clip),+ }+ hasher.finish()+ }+ }++ fn effect_content_hash(&self, effect: EffectNodeIndex, scope: EffectHashScope) -> ContentHash {+ let tree = self.list.tree;+ let cached_hashes = &self.effect_content_hashes_by_scope[scope as usize];+ let (effects_to_hash, mut content_hash) = nodes_up_to_known_value(+ effect.0,+ |effect| tree.effect_nodes[effect as usize].parent.0,+ 0,+ |effect| {+ if scope == EffectHashScope::EffectsDrawnInsideTiles+ && self.list.compositor_composites(EffectNodeIndex(effect))+ {+ return Some(CONTENT_HASH_OF_EFFECT_LEFT_OUT_OF_TILES);+ }+ cached_hashes.get(effect)+ },+ );+ for effect in effects_to_hash.into_iter().rev().map(EffectNodeIndex) {+ content_hash = self.content_hash_of_effect_node(+ effect,+ content_hash,+ self.clip_content_hash(self.list.effect_clips.output_clip(effect)),+ scope,+ );+ cached_hashes.cache(effect.0, content_hash);+ }+ content_hash+ }++ fn effect_content_hash_inside_tiles_near_area(+ &self,+ effect: EffectNodeIndex,+ near_area: &mut ContentHashesNearArea,+ ) -> ContentHash {+ let tree = self.list.tree;+ let (effects_to_hash, mut content_hash) = nodes_up_to_known_value(+ effect.0,+ |effect| tree.effect_nodes[effect as usize].parent.0,+ 0,+ |effect| {+ if self.list.compositor_composites(EffectNodeIndex(effect)) {+ return Some(CONTENT_HASH_OF_EFFECT_LEFT_OUT_OF_TILES);+ }+ near_area.content_hash_by_effect.get(&effect).copied()+ },+ );+ for effect in effects_to_hash.into_iter().rev().map(EffectNodeIndex) {+ let output_clip_hash =+ self.clip_content_hash_near_area(self.list.effect_clips.output_clip(effect), near_area);+ content_hash = self.content_hash_of_effect_node(+ effect,+ content_hash,+ output_clip_hash,+ EffectHashScope::EffectsDrawnInsideTiles,+ );+ near_area.content_hash_by_effect.insert(effect.0, content_hash);+ }+ content_hash+ }++ fn content_hash_of_effect_node(+ &self,+ effect: EffectNodeIndex,+ parent_hash: ContentHash,+ output_clip_hash: ContentHash,+ scope: EffectHashScope,+ ) -> ContentHash {+ let tree = self.list.tree;+ let node = &tree.effect_nodes[effect.0 as usize];+ let mut hasher = ContentHasher::new();+ // Sibling nodes of equal values are composited as a group each, so the index tells them apart.+ hasher.write_u32(effect.0);+ hasher.write_content_hash(parent_hash);+ hasher.write_content_hash(self.spatial_content_hash(node.spatial));+ hasher.write_content_hash(output_clip_hash);+ hasher.write_bool(tree.root_isolation_effect == Some(effect));+ let tiles_leave_effect_out = self.list.compositor_composites(effect);+ hasher.write_bool(tiles_leave_effect_out);+ match &node.data {+ EffectNodeData::Effects(effects) => {+ hasher.write_u32(1);+ hasher.write_bool(effects.isolation);+ let hashes_what_compositing_applies =+ !(scope == EffectHashScope::WhatPlacingReads && tiles_leave_effect_out);+ if hashes_what_compositing_applies {+ hasher.write_f32(effects.opacity);+ hasher.write_u32(effects.blend_mode as u32);+ }+ match &effects.filter {+ Some(filter) => hasher.write_bytes(filter),+ None => hasher.write_u64(u64::MAX),+ }+ match &effects.backdrop_filter {+ Some(backdrop_filter) => {+ hasher.write_bytes(&backdrop_filter.filter);+ hasher.write_int_rect(backdrop_filter.region);+ hasher.write_corner_radii(&backdrop_filter.corner_radii);+ }+ None => hasher.write_u64(u64::MAX),+ }+ }+ EffectNodeData::Mask(mask) => {+ hasher.write_u32(2);+ hasher.write_int_rect(mask.rect);+ hasher.write_u32(mask.kind as u32);+ hasher.write_u32(mask.origin as u32);+ hasher.write_bool(mask.masks_backdrop);+ }+ EffectNodeData::BackgroundColorAnimation => hasher.write_u32(3),+ EffectNodeData::Dead => hasher.write_u32(4),+ }+ hasher.finish()+ }++ fn context_content_hash(&self, context: ContextRef, scope: EffectHashScope) -> ContentHash {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(self.spatial_content_hash(context.spatial));+ hasher.write_content_hash(self.clip_content_hash(context.clip));+ hasher.write_content_hash(self.effect_content_hash(context.effect, scope));+ hasher.finish()+ }++ fn content_hash_of_placed_range_near_area(+ &self,+ chunk: &ListChunk,+ range: &PlacedRecordRange,+ near_area: &mut ContentHashesNearArea,+ ) -> ContentHash {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(self.spatial_content_hash(range.context.spatial));+ hasher.write_content_hash(self.clip_content_hash_near_area(range.context.clip, near_area));+ hasher.write_content_hash(self.effect_content_hash_inside_tiles_near_area(range.context.effect, near_area));+ match &range.device_aligned_fill {+ Some(fill) => {+ hasher.write_content_hash(fill.content_hash_except_rects);+ fill.rect+ .write_part_within_or_whole_if_corner_reaches_in(&mut hasher, near_area.area);+ // The inner rect's corners curve only within the outer rect's, whose part tells of them.+ if let Some(unfilled_inner_rect) = &fill.unfilled_inner_rect_of_ring {+ unfilled_inner_rect.write_part_within_or_whole_if_corner_reaches_in(&mut hasher, near_area.area);+ }+ }+ None => {+ for record in chunk+ .record_table()+ .records_in(range.first_record_index..range.end_record_index)+ {+ hasher.write_content_hash(record.content_hash_of_bytes);+ }+ }+ }+ hasher.finish()+ }++ fn write_frame_state_read_by_record(&self, hasher: &mut ContentHasher, chunk: &ListChunk, record: &ChunkRecord) {+ let list = self.list;+ let frame_state = &list.frame_state;+ let record_bytes = &chunk.records()[record.offset as usize..record.end_offset as usize];+ let (header, payload) = chunk.record_at(record.offset);+ if record.frame_state_read_flags & FRAME_STATE_CARET_BLINK_PHASE != 0 {+ hasher.write_bool(caret_is_visible_at_time(+ &read_command::<PaintCaret>(payload),+ frame_state.time_ns,+ ));+ }+ if record.frame_state_read_flags & FRAME_STATE_SCROLL_BAR != 0 {+ let command = read_command::<PaintScrollBar>(payload);+ match scrollbar_shown_by_frame(frame_state.scrollbars, &command) {+ Some(scrollbar) => {+ hasher.write_u32(1);+ write_scrollbar_shown_by_frame(hasher, scrollbar);+ }+ None => {+ hasher.write_u32(2);+ hasher.write_float_point(device_offset_for_index(+ &self.geometry.raster_scroll_offsets,+ command.scroll_node_index,+ ));+ }+ }+ }+ if record.frame_state_read_flags & FRAME_STATE_SPACES_OF_INLINE_CLIPS != 0 {+ for clip in inline_clips_of(&header, payload).filter(|clip| clip.has_own_space) {+ match self.geometry.world.draw_matrix_if_known(clip.space) {+ Some(matrix) => hasher.write_matrix(&matrix),+ None => hasher.write_u64(u64::MAX),+ }+ }+ }+ if record.frame_state_read_flags & (FRAME_STATE_LIVE_CONTENT | FRAME_STATE_SAMPLED_BACKGROUND_COLOR) == 0 {+ return;+ }+ let tree = list.tree;+ for_each_command_including_nested(record_bytes, &mut |command_type, _, payload| {+ if let Some(content) = live_content_of(command_type, payload) {+ hasher.write_u32(match content {+ LiveContent::Canvas(_) => 1,+ LiveContent::VideoFrame(_) => 2,+ LiveContent::ImageFrame(_) => 3,+ LiveContent::CompositedContext(_) => 4,+ });+ hasher.write_u64(version_of_live_content(frame_state.live_content, content));+ if matches!(content, LiveContent::CompositedContext(_)) {+ let command = read_command::<DrawCompositedContext>(payload);+ hasher.write_bool(tree.translations_snap_to_device_pixels(command.spatial_node_index));+ }+ }+ let background_color_animation_effect = background_color_animation_effect_of(command_type, payload);+ if !background_color_animation_effect.is_none() {+ let sampled = tree.sampled_background_color(background_color_animation_effect);+ hasher.write_u32(sampled.map_or(u32::MAX, |color| color.0));+ hasher.write_bool(sampled.is_some());+ }+ });+ }++ fn content_hash_of_records_without_frame_state(+ &self,+ chunk: &ListChunk,+ record_indices: std::ops::Range<RecordIndexInChunk>,+ ) -> ContentHash {+ let table = chunk.record_table();+ let mut hasher = ContentHasher::new();+ let mut run_index_of_previous_record = RunIndexInChunk(u32::MAX);+ for record in table.records_in(record_indices) {+ if record.run_index != run_index_of_previous_record {+ run_index_of_previous_record = record.run_index;+ hasher.write_content_hash(self.context_content_hash(+ chunk.runs()[record.run_index.0 as usize].context,+ EffectHashScope::EffectsDrawnInsideTiles,+ ));+ }+ hasher.write_content_hash(record.content_hash_of_bytes);+ }+ hasher.finish()+ }++ fn frame_state_hash_of_records(+ &self,+ chunk: &ListChunk,+ record_indices: std::ops::Range<RecordIndexInChunk>,+ ) -> Option<ContentHash> {+ let table = chunk.record_table();+ let records = table.records_in(record_indices);+ if records.iter().all(|record| record.frame_state_read_flags == 0) {+ return None;+ }+ let mut hasher = ContentHasher::new();+ for record in records.iter().filter(|record| record.frame_state_read_flags != 0) {+ self.write_frame_state_read_by_record(&mut hasher, chunk, record);+ }+ Some(hasher.finish())+ }++ fn content_hash_of_records(+ &self,+ chunk: &ListChunk,+ record_indices: std::ops::Range<RecordIndexInChunk>,+ ) -> ContentHash {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(self.content_hash_of_records_without_frame_state(chunk, record_indices.clone()));+ if let Some(frame_state_hash) = self.frame_state_hash_of_records(chunk, record_indices) {+ hasher.write_content_hash(frame_state_hash);+ }+ hasher.finish()+ }++ /// The hash of what compositing the layers of a node inside `effect` reads of the effect: its values, where it is,+ /// and the clips it is entered within, which changes wherever the composited effect draws differently.+ pub fn content_hash_of_composited_effect(&self, effect: EffectNodeIndex) -> ContentHash {+ self.effect_content_hash(effect, EffectHashScope::AllEffects)+ }++ /// The hash of what the records within `span` draw in the frame.+ pub fn content_hash_of_records_within(&self, span: ListSpan) -> ContentHash {+ let display_list = self.list.display_list;+ let mut hasher = ContentHasher::new();+ for (chunk_index, begin_offset, end_offset) in display_list.parts_of_span(span) {+ let chunk = display_list.chunk(chunk_index);+ let table = chunk.record_table();+ let record_indices = table.record_indices_between_offsets(begin_offset, end_offset);+ let mut first_record_index_of_run_part = record_indices.start;+ while first_record_index_of_run_part < record_indices.end {+ let run_index = table.record(first_record_index_of_run_part).run_index;+ let end_record_index_of_run_part = table.record_indices_of_run(run_index).end.min(record_indices.end);+ hasher.write_content_hash(+ self.content_hash_of_records(chunk, first_record_index_of_run_part..end_record_index_of_run_part),+ );+ first_record_index_of_run_part = end_record_index_of_run_part;+ }+ }+ hasher.finish()+ }++ fn content_hash_of_replay_item(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ item: TileReplayItem,+ near_area: Option<&mut ContentHashesNearArea>,+ ) -> ContentHash {+ let display_list = self.list.display_list;+ let chunk = display_list.chunk(item.chunk_index());+ let (content_hash_without_frame_state, record_indices) = match item {+ TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index,+ } => {+ let range = bound_band.placed_record_range(chunk_index, range_index);+ let record_indices = range.first_record_index..range.end_record_index;+ let content_hash = match near_area {+ Some(near_area) if range.is_spread_by_no_filter => {+ self.content_hash_of_placed_range_near_area(chunk, range, near_area)+ }+ _ => self.content_hash_of_records_without_frame_state(chunk, record_indices.clone()),+ };+ (content_hash, record_indices)+ }+ TileReplayItem::RecordSpan {+ begin_offset,+ end_offset,+ ..+ } => {+ let record_indices = chunk+ .record_table()+ .record_indices_between_offsets(begin_offset, end_offset);+ (+ self.content_hash_of_records_without_frame_state(chunk, record_indices.clone()),+ record_indices,+ )+ }+ };+ match self.frame_state_hash_of_records(chunk, record_indices) {+ None => content_hash_without_frame_state,+ Some(frame_state_hash) => {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(content_hash_without_frame_state);+ hasher.write_content_hash(frame_state_hash);+ hasher.finish()+ }+ }+ }++ fn records_of_item(&self, bound_band: &BandBoundToListAndGeometry, item: TileReplayItem) -> &[ChunkRecord] {+ let table = self.list.display_list.chunk(item.chunk_index()).record_table();+ let record_indices = match item {+ TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index,+ } => {+ let range = bound_band.placed_record_range(chunk_index, range_index);+ range.first_record_index..range.end_record_index+ }+ TileReplayItem::RecordSpan {+ begin_offset,+ end_offset,+ ..+ } => table.record_indices_between_offsets(begin_offset, end_offset),+ };+ table.records_in(record_indices)+ }++ fn root_of_context_sorting_item_by_depth(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ item: TileReplayItem,+ ) -> Option<Option<SpatialNodeIndex>> {+ let chunk = self.list.display_list.chunk(item.chunk_index());+ let first_run_of_chunk = self.list.display_list.first_run_of_chunk(item.chunk_index());+ self.records_of_item(bound_band, item).iter().find_map(|record| {+ self.list+ .run_groups()+ .run_is_sorted_by_depth(first_run_of_chunk + record.run_index.0 as usize)+ .then(|| {+ self.list.run_groups().root_of_context_sorting_planes_by_depth(+ chunk.runs()[record.run_index.0 as usize].context.spatial,+ )+ })+ })+ }++ fn bind_band_to_list_and_geometry(&self, stack: &LayerStack, band_index: BandIndex) -> BandBoundToListAndGeometry {+ let display_list = self.list.display_list;+ let band = &stack.bands[band_index.0];+ let held_offset_ranges_by_chunk = held_offset_ranges_by_chunk(display_list, &band.record_spans);+ if self.list.replays_every_record_into_every_tile {+ return self.band_replaying_every_held_record_in_every_tile(&held_offset_ranges_by_chunk);+ }+ let held_chunks = self.held_chunks_with_their_placements(held_offset_ranges_by_chunk);+ let backdrop_reads = self.backdrop_reads_of_held_runs(stack, band, &held_chunks);+ let (runs_replayed_whole, masks_with_declared_content) =+ self.runs_replayed_whole(&held_chunks, &backdrop_reads);+ let held_runs_read_frame_state_hashed_for_the_list = held_chunks.iter().any(|held_chunk| {+ let table = display_list.chunk(held_chunk.chunk_index).record_table();+ held_chunk+ .held_run_indices+ .iter()+ .any(|&run_index| table.run_reads_frame_state_hashed_for_the_list(run_index))+ });+ let mut bound_band = BandBoundToListAndGeometry {+ held_chunks,+ runs_replayed_whole,+ declared_masks_around_runs_replayed_whole: HashMap::new(),+ backdrop_reads,+ items_replayed_in_every_tile: None,+ replays_records_reading_frame_state_hashed_for_the_list: held_runs_read_frame_state_hashed_for_the_list,+ };++ if !masks_with_declared_content.declaration_positions_by_mask.is_empty() {+ let (declared_masks, declarations_read_frame_state_hashed_for_the_list) =+ self.declared_masks_around_runs_replayed_whole(&bound_band, &masks_with_declared_content);+ bound_band.declared_masks_around_runs_replayed_whole = declared_masks;+ bound_band.replays_records_reading_frame_state_hashed_for_the_list |=+ declarations_read_frame_state_hashed_for_the_list;+ }++ bound_band.work_out_reach_of_held_records(display_list);+ bound_band+ }++ fn band_replaying_every_held_record_in_every_tile(+ &self,+ held_offset_ranges_by_chunk: &[(ChunkIndexInList, Vec<(u32, u32)>)],+ ) -> BandBoundToListAndGeometry {+ let list = self.list;+ let display_list = list.display_list;+ let mut items_replayed_in_every_tile: Vec<(ListPosition, TileReplayItem)> = held_offset_ranges_by_chunk+ .iter()+ .flat_map(|(chunk_index, held_offset_ranges)| {+ held_offset_ranges.iter().map(|&(begin_offset, end_offset)| {+ (+ ListPosition::new(*chunk_index, begin_offset),+ TileReplayItem::RecordSpan {+ chunk_index: *chunk_index,+ begin_offset,+ end_offset,+ },+ )+ })+ })+ .collect();+ let tree = list.tree;+ let mut effect_is_around_held_run = vec![false; tree.effect_nodes.len()];+ let mut replays_records_reading_frame_state_hashed_for_the_list = false;+ for (chunk_index, held_offset_ranges) in held_offset_ranges_by_chunk {+ let chunk = display_list.chunk(*chunk_index);+ let runs = chunk.runs();+ for run_index in runs_within_held_offset_ranges(runs, held_offset_ranges) {+ replays_records_reading_frame_state_hashed_for_the_list |= chunk+ .record_table()+ .run_reads_frame_state_hashed_for_the_list(run_index);+ let mut effect = runs[run_index.0 as usize].context.effect;+ while !effect.is_none() && !effect_is_around_held_run[effect.0 as usize] {+ effect_is_around_held_run[effect.0 as usize] = true;+ effect = tree.effect_nodes[effect.0 as usize].parent;+ }+ }+ }+ for declaration in &display_list.summary().mask_declarations {+ let (mask_effect, declaration_position) = (declaration.mask_effect, declaration.record.position);+ // A declaration can name any effect node.+ let mask_is_around_held_run = effect_is_around_held_run.get(mask_effect.0 as usize) == Some(&true)+ && matches!(tree.effect_nodes[mask_effect.0 as usize].data, EffectNodeData::Mask(_));+ let declaration_is_held = held_offset_ranges_by_chunk+ .binary_search_by_key(&declaration_position.chunk_index, |(chunk_index, _)| *chunk_index)+ .is_ok_and(|position| {+ offset_is_held(&held_offset_ranges_by_chunk[position].1, declaration_position.offset)+ });+ if !mask_is_around_held_run || declaration_is_held {+ continue;+ }+ let table = display_list.chunk(declaration_position.chunk_index).record_table();+ let record_index = table+ .record_indices_between_offsets(declaration_position.offset, declaration_position.offset + 1)+ .start;+ replays_records_reading_frame_state_hashed_for_the_list |=+ table.record(record_index).reads_frame_state_hashed_for_the_list();+ items_replayed_in_every_tile.push((+ declaration_position,+ TileReplayItem::RecordSpan {+ chunk_index: declaration_position.chunk_index,+ begin_offset: declaration_position.offset,+ end_offset: table.record(record_index).end_offset,+ },+ ));+ }+ BandBoundToListAndGeometry {+ held_chunks: Vec::new(),+ runs_replayed_whole: HashMap::new(),+ declared_masks_around_runs_replayed_whole: HashMap::new(),+ backdrop_reads: BackdropReadsOfBand::new(Vec::new()),+ items_replayed_in_every_tile: Some(items_replayed_in_every_tile),+ replays_records_reading_frame_state_hashed_for_the_list,+ }+ }++ fn held_chunks_with_their_placements(+ &self,+ held_offset_ranges_by_chunk: Vec<(ChunkIndexInList, Vec<(u32, u32)>)>,+ ) -> Vec<ChunkHeldByBand> {+ let display_list = self.list.display_list;+ let mut held_chunks: Vec<ChunkHeldByBand> = Vec::with_capacity(held_offset_ranges_by_chunk.len());+ for (chunk_index, held_offset_ranges) in held_offset_ranges_by_chunk {+ let held_run_indices =+ runs_within_held_offset_ranges(display_list.chunk(chunk_index).runs(), &held_offset_ranges);+ let placement = self.placement_of_runs_of_chunk(chunk_index, &held_run_indices);+ held_chunks.push(ChunkHeldByBand {+ chunk_index,+ placement,+ held_run_indices,+ reach_of_held_records: Reach::Nothing,+ });+ }+ debug_assert!(+ held_chunks+ .windows(2)+ .all(|pair| pair[0].chunk_index < pair[1].chunk_index),+ "the checks of a plan take only bands whose spans are in paint order"+ );+ held_chunks+ }++ fn backdrop_reads_of_held_runs(+ &self,+ stack: &LayerStack,+ band: &PlacementNodeBand,+ held_chunks: &[ChunkHeldByBand],+ ) -> BackdropReadsOfBand {+ let display_list = self.list.display_list;+ let tree = self.list.tree;+ let effect_composited_around_band = stack.nodes[band.placement_node_index.0]+ .composited_effect+ .unwrap_or(EffectNodeIndex::NONE);+ let mut effect_was_visited = vec![false; tree.effect_nodes.len()];+ let mut backdrop_reads_in_paint_order = Vec::new();+ for held_chunk in held_chunks {+ let runs = display_list.chunk(held_chunk.chunk_index).runs();+ for &run_index in &held_chunk.held_run_indices {+ let run = &runs[run_index.0 as usize];+ let mut effect = run.context.effect;+ while !effect.is_none()+ && effect != effect_composited_around_band+ && !effect_was_visited[effect.0 as usize]+ {+ effect_was_visited[effect.0 as usize] = true;+ let node = &tree.effect_nodes[effect.0 as usize];+ if matches!(&node.data, EffectNodeData::Effects(effects) if effects.backdrop_filter.is_some()) {+ backdrop_reads_in_paint_order.push(+ self.backdrop_read_in_layer(effect, ListPosition::new(held_chunk.chunk_index, run.offset)),+ );+ }+ effect = node.parent;+ }+ }+ }+ BackdropReadsOfBand::new(backdrop_reads_in_paint_order)+ }++ /// The held runs that replay whole wherever any run of their run group shows, and the masks with declared content+ /// around them.+ fn runs_replayed_whole(+ &self,+ held_chunks: &[ChunkHeldByBand],+ backdrop_reads: &BackdropReadsOfBand,+ ) -> (RunsReplayedWhole, MasksWithDeclaredContent) {+ let list = self.list;+ let display_list = list.display_list;+ let tree = list.tree;+ // A mask or a depth sort reads every run of its run group, so those runs replay whole wherever any of them+ // shows.+ let run_groups = list.run_groups();+ let mut reach_and_first_position_of_run_groups_replayed_whole: BTreeMap<+ RunGroupIndex,+ (Reach<IntRect>, ListPosition),+ > = BTreeMap::new();+ let mut held_runs_replayed_whole: Vec<(ChunkIndexInList, RunIndexInChunk, RunGroupIndex)> = Vec::new();+ for held_chunk in held_chunks {+ let runs = display_list.chunk(held_chunk.chunk_index).runs();+ for &run_index in &held_chunk.held_run_indices {+ let position = ListPosition::new(held_chunk.chunk_index, runs[run_index.0 as usize].offset);+ let run_group_index = run_groups+ .group_of_run(display_list.first_run_of_chunk(held_chunk.chunk_index) + run_index.0 as usize);+ if !run_groups.group_is_under_mask(run_group_index)+ && !run_groups.group_is_sorted_by_depth(run_group_index)+ {+ continue;+ }+ let ranges_of_run = &held_chunk.placement.ranges_of_each_run[run_index.0 as usize];+ let whole_run_reach =+ held_chunk.placement.record_ranges[ranges_of_run.whole_run_range_index.0 as usize].reach;+ reach_and_first_position_of_run_groups_replayed_whole+ .entry(run_group_index)+ .and_modify(|(united_reach, first_position)| {+ *united_reach = united_reach.united(whole_run_reach);+ *first_position = (*first_position).min(position);+ })+ .or_insert((whole_run_reach, position));+ held_runs_replayed_whole.push((held_chunk.chunk_index, run_index, run_group_index));+ }+ }+ let mut declaration_positions_by_mask: HashMap<EffectNodeIndex, Vec<ListPosition>> = HashMap::new();+ if !held_runs_replayed_whole.is_empty() {+ for declaration in &display_list.summary().mask_declarations {+ declaration_positions_by_mask+ .entry(declaration.mask_effect)+ .or_default()+ .push(declaration.record.position);+ }+ }+ let nearest_declared_mask_by_effect_index = if declaration_positions_by_mask.is_empty() {+ Vec::new()+ } else {+ nearest_effects_at_or_above_where(tree, |effect, node| {+ matches!(node.data, EffectNodeData::Mask(_)) && declaration_positions_by_mask.contains_key(&effect)+ })+ };+ let masks_with_declared_content = MasksWithDeclaredContent {+ declaration_positions_by_mask,+ nearest_declared_mask_by_effect_index,+ };+ let runs_replayed_whole = held_runs_replayed_whole+ .into_iter()+ .map(|(chunk_index, run_index, run_group_index)| {+ let (run_group_reach, first_position) =+ reach_and_first_position_of_run_groups_replayed_whole[&run_group_index];+ let run_replayed_whole = RunReplayedWholeWhereverRunGroupShows {+ reach: backdrop_reads.reach_extended_through_reads(run_group_reach, first_position),+ innermost_declared_mask_around: masks_with_declared_content.nearest_declared_mask_at_or_above(+ display_list.chunk(chunk_index).runs()[run_index.0 as usize]+ .context+ .effect,+ ),+ };+ ((chunk_index, run_index), run_replayed_whole)+ })+ .collect();+ (runs_replayed_whole, masks_with_declared_content)+ }++ fn declared_masks_around_runs_replayed_whole(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ masks_with_declared_content: &MasksWithDeclaredContent,+ ) -> (HashMap<EffectNodeIndex, DeclaredMaskAroundRunReplayedWhole>, bool) {+ let display_list = self.list.display_list;+ let tree = self.list.tree;+ // Each declared mask is looked at once, and every run inside it shares the chain of declared masks from it+ // out.+ let mut declared_masks: HashMap<EffectNodeIndex, DeclaredMaskAroundRunReplayedWhole> = HashMap::new();+ let mut declared_masks_not_looked_at = Vec::new();+ let mut declared_items_of_mask = HashSet::new();+ let mut declarations_read_frame_state_hashed_for_the_list = false;+ for run_replayed_whole in bound_band.runs_replayed_whole.values() {+ declared_masks_not_looked_at.clear();+ let mut mask = run_replayed_whole.innermost_declared_mask_around;+ while !mask.is_none() && !declared_masks.contains_key(&mask) {+ declared_masks_not_looked_at.push(mask);+ mask = masks_with_declared_content+ .nearest_declared_mask_at_or_above(tree.effect_nodes[mask.0 as usize].parent);+ }+ for &mask in &declared_masks_not_looked_at {+ let next_declared_mask_around = masks_with_declared_content+ .nearest_declared_mask_at_or_above(tree.effect_nodes[mask.0 as usize].parent);+ let mut declarations: Vec<(ListPosition, TileReplayItem, Reach<IntRect>)> = Vec::new();+ declared_items_of_mask.clear();+ for &declaration_position in &masks_with_declared_content.declaration_positions_by_mask[&mask] {+ let table = display_list.chunk(declaration_position.chunk_index).record_table();+ let record_index = table+ .record_indices_between_offsets(declaration_position.offset, declaration_position.offset + 1)+ .start;+ declarations_read_frame_state_hashed_for_the_list |=+ table.record(record_index).reads_frame_state_hashed_for_the_list();+ let item =+ bound_band.item_replaying_record(display_list, declaration_position.chunk_index, record_index);+ if !declared_items_of_mask.insert(item) {+ continue;+ }+ declarations.push((bound_band.span_of(item).begin, item, bound_band.reach_of_item(item)));+ }+ declared_masks.insert(+ mask,+ DeclaredMaskAroundRunReplayedWhole {+ declarations,+ next_declared_mask_around,+ },+ );+ }+ }+ (declared_masks, declarations_read_frame_state_hashed_for_the_list)+ }++ /// The tiles of `band_index` bound to the list and the geometry of the frame and to the band in `stack`, with no+ /// tile keyed yet.+ pub fn bind_band(&self, stack: &LayerStack, band_index: BandIndex) -> BandTileKeys {+ BandTileKeys {+ cells: BTreeMap::new(),+ cells_looked_at: CellRange::NONE,+ bound_band: self.bind_band_to_list_and_geometry(stack, band_index),+ values_of_frame_tiles_were_keyed_with: None,+ }+ }++ /// Keys the tiles of the layers of `band_index` within `shown_rect` that are not keyed yet: each replay item of the+ /// band that reaches a tile goes into the layer of the band its paint position falls in there, and the base layer,+ /// if it is one of the band's, holds every tile. Every tile keyed before is keyed again where the frame state that+ /// records of the band read, the tree, the raster settings of a layer of the band, or the edge of `frame` that its+ /// backdrop blurs mirror at changed, and those outside `kept_rect` are forgotten. `frame` is where the frame is in+ /// the band's space, where that is not the frame's own. The band is bound to the list and the geometry of the frame.+ ///+ /// Only the cells where the band can hold something are keyed, at most `MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME` of+ /// them, so the work and the tiles of a frame have a bound whatever rect of the space the frame shows.+ #[allow(clippy::too_many_arguments)]+ pub fn key_shown_tiles(+ &self,+ band_tile_keys: &mut BandTileKeys,+ stack: &LayerStack,+ band_index: BandIndex,+ raster_settings_hash_by_layer: &[ContentHash],+ shown_rect: IntRect,+ kept_rect: IntRect,+ frame: Option<IntRect>,+ ) -> TileKeyingCounts {+ let list = self.list;+ let band = &stack.bands[band_index.0];+ band_tile_keys+ .cells+ .retain(|coord, _| !coord.cell_rect().intersected(kept_rect).is_empty());+ band_tile_keys.cells_looked_at = band_tile_keys+ .cells_looked_at+ .intersected(CellRange::touched_by(kept_rect));+ let bound_band = &band_tile_keys.bound_band;+ let new_coords = coords_to_key(+ &mut band_tile_keys.cells,+ &mut band_tile_keys.cells_looked_at,+ bound_band,+ stack.base_layer == band.layer_below_all_cuts,+ shown_rect,+ );++ let mut counts = TileKeyingCounts::default();+ let mut raster_settings_hasher = ContentHasher::new();+ for layer_index in+ std::iter::once(band.layer_below_all_cuts).chain(band.cuts.iter().map(|cut| cut.layer_above_cut))+ {+ raster_settings_hasher.write_content_hash(raster_settings_hash_by_layer[layer_index.0]);+ }+ let values_of_frame = ValuesOfFrameThatTilesOfBandRead {+ frame_state_hash: bound_band+ .replays_records_reading_frame_state_hashed_for_the_list+ .then_some(list.frame_state_hash),+ tree_copy_number: list.tree.copy.number(),+ raster_settings_hash_of_layers_of_band: raster_settings_hasher.finish(),+ frame_edge_backdrop_blurs_mirror_at: bound_band.backdrop_reads.frame_edge_blurs_mirror_at(frame),+ };+ if band_tile_keys+ .values_of_frame_tiles_were_keyed_with+ .replace(values_of_frame)+ != Some(values_of_frame)+ {+ for (coord, tiles) in &mut band_tile_keys.cells {+ counts.tiles_keyed +=+ self.key_tiles_of_cell(bound_band, *coord, tiles, raster_settings_hash_by_layer, frame);+ }+ }++ if new_coords.is_empty() {+ return counts;+ }+ for (coord, mut tiles) in self.bin_new_cells(bound_band, stack, band_index, &new_coords) {+ counts.tiles_keyed +=+ self.key_tiles_of_cell(bound_band, coord, &mut tiles, raster_settings_hash_by_layer, frame);+ let band_holds_something_in_cell = !tiles.is_empty();+ if band_holds_something_in_cell {+ counts.cells_binned += 1;+ }+ band_tile_keys.cells.insert(coord, tiles);+ }+ counts+ }++ /// The tiles of the band at each of `new_coords`, not hashed yet: each replay item of the band that reaches a cell+ /// goes into the layer of the band its paint position falls in there, and the base layer, if it is the band's layer+ /// below all cuts, holds every cell.+ fn bin_new_cells(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ stack: &LayerStack,+ band_index: BandIndex,+ new_coords: &[TileCoord],+ ) -> Vec<(TileCoord, Vec<KeyedTile>)> {+ let band = &stack.bands[band_index.0];+ let base_layer = (stack.base_layer == band.layer_below_all_cuts).then_some(stack.base_layer);+ let new_cells_area = new_coords+ .iter()+ .fold(IntRect::default(), |cells, coord| cells.united(coord.cell_rect()));+ // Per layer that items go into in the cell, the items, and the declared masks whose declarations those items hold.+ type ItemsOfLayerInCell = (+ LayerIndex,+ Vec<(ListPosition, TileReplayItem, Reach<IntRect>)>,+ HashSet<EffectNodeIndex>,+ );+ struct BinOfCell<'a> {+ cuts: CutsOfCell<'a>,+ position_of_layer_by_count_of_cuts_below: Vec<Option<usize>>,+ items_by_layer: Vec<ItemsOfLayerInCell>,+ }+ let mut bins: BTreeMap<TileCoord, BinOfCell<'_>> = new_coords+ .iter()+ .map(|coord| {+ let cuts = CutsOfCell::of(band, coord.cell_rect());+ let layer_count = cuts.cuts().count() + 1;+ (+ *coord,+ BinOfCell {+ cuts,+ position_of_layer_by_count_of_cuts_below: vec![None; layer_count],+ items_by_layer: Vec::new(),+ },+ )+ })+ .collect();+ let mut add_to_bins = |paint_position: ListPosition,+ item: TileReplayItem,+ reach: Reach<IntRect>,+ innermost_declared_mask_around_item: EffectNodeIndex| {+ let reach_in_new_cells = reach.part_of(new_cells_area);+ if reach_in_new_cells.is_empty() {+ return;+ }+ // The new cells can lie far apart, with many more cells between them than they are.+ for_each_entry_within(&mut bins, CellRange::touched_by(reach_in_new_cells), |_, bin| {+ let (layer_index, count_of_cuts_below) = bin.cuts.layer_of_record(paint_position);+ // A frame composites only the base layer and the layers the stack says can hold content. A stretch and+ // a placed record range both take their reach from `RasterSpaceGeometry::reach_of_content`, the+ // stretch for the ink of its runs, so a range stays within the reach of its stretch wherever the+ // space's extent lets it show. A stack from another process can say otherwise, which only leaves out+ // what the item draws there.+ if layer_index != stack.base_layer && !stack.layers[layer_index.0].may_hold_content {+ return;+ }+ let position_of_layer = match bin.position_of_layer_by_count_of_cuts_below[count_of_cuts_below] {+ Some(position) => position,+ None => {+ bin.items_by_layer.push((layer_index, Vec::new(), HashSet::new()));+ let position = bin.items_by_layer.len() - 1;+ bin.position_of_layer_by_count_of_cuts_below[count_of_cuts_below] = Some(position);+ position+ }+ };+ let (_, items_of_layer, declared_masks_of_layer) = &mut bin.items_by_layer[position_of_layer];+ items_of_layer.push((paint_position, item, reach));+ // Where the layer holds the declarations of a mask, it holds those of the masks around it too.+ let mut mask = innermost_declared_mask_around_item;+ while !mask.is_none() && declared_masks_of_layer.insert(mask) {+ let declared_mask = &bound_band.declared_masks_around_runs_replayed_whole[&mask];+ items_of_layer.extend_from_slice(&declared_mask.declarations);+ mask = declared_mask.next_declared_mask_around;+ }+ });+ };+ match &bound_band.items_replayed_in_every_tile {+ Some(items_replayed_in_every_tile) => {+ for &(paint_position, item) in items_replayed_in_every_tile {+ add_to_bins(paint_position, item, Reach::Anywhere, EffectNodeIndex::NONE);+ }+ }+ None => {+ for held_chunk in &bound_band.held_chunks {+ if held_chunk.reach_of_held_records.part_of(new_cells_area).is_empty() {+ continue;+ }+ bound_band.for_each_held_item(held_chunk, &mut add_to_bins);+ }+ }+ }++ bins.into_iter()+ .map(|(coord, bin)| {+ let BinOfCell {+ cuts: cuts_of_cell,+ items_by_layer: mut bin,+ ..+ } = bin;+ // The base layer is the band's layer below all cuts.+ if let Some(base_layer) = base_layer+ && !bin.iter().any(|(layer_index, _, _)| *layer_index == base_layer)+ {+ bin.push((base_layer, Vec::new(), HashSet::new()));+ }+ let cell = coord.cell_rect();+ let raster_margin_in_device_pixels = bound_band.backdrop_reads.raster_margin_of_cell(cell);+ let cuts = cuts_of_cell.barrier_cuts();+ let tiles = bin+ .into_iter()+ .map(|(layer_index, mut items_of_layer, _)| {+ items_of_layer.sort_unstable_by_key(|(paint_position, item, _)| (*paint_position, *item));+ items_of_layer.dedup_by_key(|(_, item, _)| *item);+ let content_bounds =+ items_of_layer+ .iter()+ .fold(IntRect::default(), |bounds, (_, _, reach)| match reach {+ Reach::Within(rect) => bounds.united(rect.intersected(cell)),+ Reach::Anywhere => cell,+ Reach::Nothing => bounds,+ });+ KeyedTile {+ layer_index,+ coord,+ content_hash: 0,+ raster_margin_in_device_pixels,+ cuts: cuts.clone(),+ content_bounds,+ replay_items_in_paint_order: items_of_layer.into_iter().map(|(_, item, _)| item).collect(),+ }+ })+ .collect();+ (coord, tiles)+ })+ .collect()+ }++ /// Hashes the tiles of the cell at `coord`, which are keyed together with one raster margin, and returns how many it+ /// hashed.+ fn key_tiles_of_cell(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ coord: TileCoord,+ tiles: &mut [KeyedTile],+ raster_settings_hash_by_layer: &[ContentHash],+ frame: Option<IntRect>,+ ) -> usize {+ let frame_edge_backdrop_blurs_mirror_at = bound_band+ .backdrop_reads+ .frame_edge_blurs_of_cell_mirror_at(coord.cell_rect(), frame);+ let mut near_area = tiles+ .first()+ .and_then(|tile| ContentHashesNearArea::of_cell(coord, tile.raster_margin_in_device_pixels));+ for tile in tiles.iter_mut() {+ let mut hasher = ContentHasher::new();+ hasher.write_content_hash(raster_settings_hash_by_layer[tile.layer_index.0]);+ hasher.write_i32(coord.column);+ hasher.write_i32(coord.row);+ hasher.write_bool(self.list.replays_every_record_into_every_tile);+ match frame_edge_backdrop_blurs_mirror_at {+ Some(frame) => hasher.write_int_rect(frame),+ None => hasher.write_u32(0),+ }+ for &item in &tile.replay_items_in_paint_order {+ hasher.write_content_hash(self.content_hash_of_replay_item(bound_band, item, near_area.as_mut()));+ // Depth-sorted planes replay in an order their sorting context decides.+ if self.list.tree_sorts_planes_by_depth+ && let Some(root) = self.root_of_context_sorting_item_by_depth(bound_band, item)+ {+ hasher.write_u32(1);+ hasher.write_u32(root.map_or(u32::MAX, |root| root.0));+ }+ }+ tile.content_hash = hasher.finish();+ }+ tiles.len()+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::builder::DisplayListBuilder;+ use crate::display_list::commands::{+ ClipMode, DeclareMaskContent, FillRect, FillRoundedRectRing, VISUAL_VIEWPORT_NODE_INDEX,+ };+ use crate::display_list::layers::planning::{LayerStackInputs, plan_layer_stack};+ use crate::display_list::layers::{LayerIdentity, LayerStack, LayeringObstacles, SpaceToFrame, WhyListIsOneLayer};+ use crate::display_list::placement::{RasterSpaceIndex, RasterSpaces, WhatEverySpaceOfTreeShares};+ use crate::display_list::test_fixtures::{+ GREEN, ListOfOneChunk, NO_FRAME_STATE, VIEWPORT, animation_of, canvas, chunk_of, effects, fill, frosted_glass,+ opacity_animation_of, raster_settings_hash_by_layer, transform, transform_animation_of,+ tree_with_document_scroll, tree_with_root_isolation_effect,+ };+ use crate::display_list::tiles::TILE_SIZE_IN_DEVICE_PIXELS;+ use crate::host::FfiVisualAnimationTargetKind;+ use crate::visual_context::{EffectsData, SpatialData, TransformData, TransformDataRole};+ use libgfx_rust::{AffineTransform, CompositingAndBlendingOperator};++ const RED: Color = Color::from_rgb(255, 0, 0);+ const BLUE: Color = Color::from_rgb(0, 0, 255);++ // The recorder declares a mask's content under the effects of what the mask holds, so no page has a declaration made+ // around the mask.+ #[test]+ fn a_mask_declared_around_its_mask_is_replayed_with_what_it_masks() {+ use crate::visual_context::{MaskData, MaskLayerOrigin};+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let masked = tree.append_effect_node_under(+ root,+ EffectNodeData::Mask(MaskData {+ rect: IntRect::new(0, 0, 100, 100),+ kind: libgfx_rust::MaskKind::Alpha,+ origin: MaskLayerOrigin::CssMaskLayers,+ masks_backdrop: false,+ }),+ );+ let mut list = ListOfOneChunk::default().with(fill(VIEWPORT, GREEN), root);+ let declaration_position = ListPosition::new(ChunkIndexInList(0), list.builder.byte_size() as u32);+ let declaration = list.builder.begin_group::<DeclareMaskContent>(Vec::new());+ list.builder.append(&fill(IntRect::new(0, 0, 50, 50), RED), &[], root);+ let content = list.builder.group_content_span(&declaration);+ list.builder.finish_group(+ declaration,+ &DeclareMaskContent {+ rect: IntRect::new(0, 0, 100, 100),+ effect: masked.effect,+ content,+ },+ root,+ );+ let masked_position = ListPosition::new(ChunkIndexInList(0), list.builder.byte_size() as u32);+ list = list.with(fill(IntRect::new(10, 10, 80, 80), BLUE), masked);++ let display_list = DisplayListStorage::of_builder(&list.builder);+ let stack = plan_layer_stack(&LayerStackInputs {+ list: &display_list,+ tree: &tree,+ scroll_offsets: &[],+ viewport_rect: VIEWPORT,+ })+ .stack;+ assert_eq!(stack.why_list_is_one_layer, None);+ let band = BandIndex(+ stack+ .bands+ .iter()+ .position(|band| band.record_spans.iter().any(|span| span.contains(masked_position)))+ .unwrap(),+ );+ let (band_tile_keys, _) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ RasterSpaceIndex::VIEWPORT,+ band,+ &[VIEWPORT],+ );+ let tile_with_masked_content = band_tile_keys+ .tiles_within(TileCoord::new(0, 0).cell_rect())+ .find(|tile| {+ band_tile_keys+ .record_spans_of_tiles([*tile])+ .iter()+ .any(|span| span.contains(masked_position))+ })+ .unwrap();+ let spans = band_tile_keys.record_spans_of_tiles([tile_with_masked_content]);+ assert!(spans.iter().any(|span| span.contains(declaration_position)));+ assert!(spans.windows(2).all(|pair| pair[0].end <= pair[1].begin));+ }++ fn stack_of(display_list: &DisplayListStorage, tree: &VisualContextTree) -> LayerStack {+ plan_layer_stack(&LayerStackInputs {+ list: display_list,+ tree,+ scroll_offsets: &[],+ viewport_rect: VIEWPORT,+ })+ .stack+ }++ fn geometry_of_space(+ tree: &VisualContextTree,+ stack: &LayerStack,+ raster_space_index: RasterSpaceIndex,+ ) -> RasterSpaceGeometry {+ let spaces = RasterSpaces::of_spaces(tree, stack.spaces.clone());+ RasterSpaceGeometry::new(+ tree,+ &spaces,+ raster_space_index,+ &[],+ FloatMatrix4x4::identity(),+ &WhatEverySpaceOfTreeShares::of(tree),+ )+ }++ // Keys the tiles of the band within `shown_rect`, and forgets those outside it.+ fn key_band(+ raster_space: &TileKeyingOfRasterSpace<'_>,+ band_tile_keys: &mut BandTileKeys,+ stack: &LayerStack,+ band_index: BandIndex,+ shown_rect: IntRect,+ ) -> TileKeyingCounts {+ raster_space.key_shown_tiles(+ band_tile_keys,+ stack,+ band_index,+ &raster_settings_hash_by_layer(stack),+ shown_rect,+ shown_rect,+ None,+ )+ }++ fn tiles_within(band_tile_keys: &BandTileKeys, rect: IntRect) -> Vec<(TileCoord, LayerIndex, ContentHash)> {+ band_tile_keys+ .tiles_within(rect)+ .map(|tile| (tile.coord, tile.layer_index, tile.content_hash))+ .collect()+ }++ // Each frame binds the band again under a geometry of its own.+ fn key_band_in_frames_in_turn(+ frames: &[(&DisplayListStorage, &VisualContextTree, &LayerStack)],+ raster_space_index: RasterSpaceIndex,+ band_index: BandIndex,+ ) -> Vec<(u64, TileKeyingCounts, Vec<(TileCoord, LayerIndex, ContentHash)>)> {+ frames+ .iter()+ .map(|&(display_list, tree, stack)| {+ let list_keying = TileKeyingOfList::new(display_list, tree, stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(tree, stack, raster_space_index);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let mut band_tile_keys = raster_space.bind_band(stack, band_index);+ let counts = key_band(&raster_space, &mut band_tile_keys, stack, band_index, VIEWPORT);+ (+ raster_space.chunks_placed(),+ counts,+ tiles_within(&band_tile_keys, VIEWPORT),+ )+ })+ .collect()+ }++ fn sliding_box_tree_and_list(+ overshooting_easing: bool,+ ) -> (VisualContextTree, Arc<DisplayListStorage>, SpatialNodeIndex) {+ use crate::host::FfiVisualAnimationTransformOperationKind;+ use crate::visual_animation::VisualAnimation;+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let moving_node = tree.append_spatial(+ SpatialData::Transform(TransformData {+ matrix: FloatMatrix4x4::identity(),+ origin: FloatPoint::default(),+ sorting_context_root_index: None,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: false,+ bounds: FloatRect::new(0.0, 0.0, 50.0, 50.0),+ }),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ let easing = if overshooting_easing {+ crate::easing::Easing::CubicBezier {+ x1: 0.3,+ y1: 1.6,+ x2: 0.6,+ y2: 1.0,+ }+ } else {+ crate::easing::Easing::default()+ };+ tree.set_visual_animations(vec![VisualAnimation {+ easing,+ ..transform_animation_of(+ moving_node,+ FfiVisualAnimationTransformOperationKind::TranslateX,+ 0.0,+ 400.0,+ )+ }]);+ let moving = ContextRef {+ spatial: moving_node,+ ..root+ };+ let display_list = DisplayListStorage::of_chunks(vec![+ chunk_of(fill(VIEWPORT, GREEN), root),+ chunk_of(fill(IntRect::new(100, 300, 50, 50), BLUE), moving),+ chunk_of(fill(IntRect::new(600, 400, 20, 20), RED), root),+ ])+ .unwrap();+ (tree, display_list, moving_node)+ }++ // An easing that overshoots leaves nothing to bound where the box goes, so it stays in the tiles of the viewport.+ #[test]+ fn an_animation_sample_places_again_only_the_chunks_under_the_node_it_moves() {+ let (tree, display_list, _) = sliding_box_tree_and_list(true);+ let at_start = tree.with_visual_animation_samples(0);+ let halfway = tree.with_visual_animation_samples(500_000_000);+ let stack = stack_of(&display_list, &at_start);+ assert_eq!(stack.spaces.len(), 2);+ assert_eq!(stack.nodes.len(), 1);+ assert_eq!(stack_of(&display_list, &halfway).layers, stack.layers);++ let turns = key_band_in_frames_in_turn(+ &[(&display_list, &at_start, &stack), (&display_list, &halfway, &stack)],+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ );+ assert_eq!(turns[0].0, 3);+ // Only the chunk under the moving node is placed again.+ assert_eq!(turns[1].0, 1);+ }++ #[test]+ fn an_animation_sample_leaves_the_tiles_of_the_space_of_the_node_it_moves_alike() {+ let (tree, display_list, moving_node) = sliding_box_tree_and_list(false);+ let at_start = tree.with_visual_animation_samples(0);+ let halfway = tree.with_visual_animation_samples(500_000_000);+ let stack = stack_of(&display_list, &at_start);+ let animated_space = RasterSpaceIndex(1);+ assert_eq!(stack.spaces[animated_space.0].anchor, moving_node);+ let turns = key_band_in_frames_in_turn(+ &[(&display_list, &at_start, &stack), (&display_list, &halfway, &stack)],+ animated_space,+ band_of_space(&stack, animated_space),+ );+ assert_eq!(turns[0].0, 1);+ let (chunks_placed, _, hashes) = &turns[1];+ assert_eq!(*chunks_placed, 0);+ assert_eq!(hashes, &turns[0].2);+ }++ // As the compositor keys a band across the samples of its animations where the plan says the space of the band+ // holds nothing that moves within it: under the geometry of the first frame, to which the band is bound once.+ fn counts_and_viewport_tile_hashes_of_samples_keyed_in_turn_under_one_geometry(+ display_list: &DisplayListStorage,+ stack: &LayerStack,+ band_index: BandIndex,+ samples: &[&VisualContextTree],+ ) -> Vec<(TileKeyingCounts, Vec<(TileCoord, LayerIndex, ContentHash)>)> {+ let raster_space_index = stack.nodes[stack.bands[band_index.0].placement_node_index.0].raster_space_index;+ assert!(!stack.space_holds_content_that_moves_within_it(raster_space_index));+ let geometry = geometry_of_space(samples[0], stack, raster_space_index);+ let mut band_tile_keys_bound_in_first_frame = None;+ samples+ .iter()+ .map(|tree| {+ let list_keying = TileKeyingOfList::new(display_list, tree, stack, NO_FRAME_STATE);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let band_tile_keys = band_tile_keys_bound_in_first_frame+ .get_or_insert_with(|| raster_space.bind_band(stack, band_index));+ let counts = key_band(&raster_space, band_tile_keys, stack, band_index, VIEWPORT);+ (counts, tiles_within(band_tile_keys, VIEWPORT))+ })+ .collect()+ }++ #[test]+ fn a_ring_whose_inner_edges_lie_past_the_coordinate_range_is_no_device_aligned_fill() {+ let (tree, root) = tree_with_root_isolation_effect(1.0);+ let near_the_limit = i32::MAX - 100;+ let list = ListOfOneChunk::default().with(+ FillRoundedRectRing {+ rect: IntRect::new(near_the_limit, near_the_limit, 200, 200),+ corner_radii: CornerRadii::default(),+ top_width: 150,+ right_width: 10,+ bottom_width: 10,+ left_width: 150,+ color: GREEN,+ },+ root,+ );+ let display_list = DisplayListStorage::of_builder(&list.builder);+ let stack = stack_of(&display_list, &tree);+ let list_keying = TileKeyingOfList::new(&display_list, &tree, &stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(&tree, &stack, RasterSpaceIndex::VIEWPORT);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let chunk = display_list.chunk(ChunkIndexInList(0));+ let ring_record = chunk.record_table().record(RecordIndexInChunk(0));+ assert!(+ raster_space+ .device_aligned_fill_of_record(chunk, ring_record, root)+ .is_none()+ );+ }++ struct CanvasesAtGeneration(u64);++ impl LiveContentVersions for CanvasesAtGeneration {+ fn canvas_content_generation(&self, _: CanvasId) -> u64 {+ self.0+ }+ fn video_frame_id(&self, _: VideoSinkHandle) -> Option<u64> {+ None+ }+ fn image_frame_pixel_generation(&self, _: ImageFrameResourceId) -> Option<u64> {+ None+ }+ fn nested_context_frame_generation(&self, _: CompositorContextId) -> Option<u64> {+ None+ }+ }++ // How many tiles each frame keys of the band that holds the record of `run_index`, under one geometry, as the+ // canvases of the list are at a new generation in each frame, and the tiles of the band in the viewport after it.+ fn tiles_keyed_and_kept_in_frames_with_a_new_canvas_generation(+ list: &ListOfOneChunk,+ tree: &VisualContextTree,+ run_index: usize,+ ) -> Vec<(usize, Vec<(TileCoord, LayerIndex, ContentHash)>)> {+ let display_list = DisplayListStorage::of_builder(&list.builder);+ let stack = stack_of(&display_list, tree);+ let position = display_list.span_of_run(run_index).begin;+ let band_index = BandIndex(+ stack+ .bands+ .iter()+ .position(|band| band.record_spans.iter().any(|span| span.contains(position)))+ .expect("a band holds the record"),+ );+ let raster_space_index = stack.nodes[stack.bands[band_index.0].placement_node_index.0].raster_space_index;+ let geometry = geometry_of_space(tree, &stack, raster_space_index);+ let mut band_tile_keys_bound_in_first_frame = None;+ (0..3)+ .map(|generation| {+ let live_content = CanvasesAtGeneration(generation);+ let frame_state = FrameStateReadByReplay {+ live_content: &live_content,+ ..NO_FRAME_STATE+ };+ let list_keying = TileKeyingOfList::new(&display_list, tree, &stack, frame_state);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let band_tile_keys = band_tile_keys_bound_in_first_frame+ .get_or_insert_with(|| raster_space.bind_band(&stack, band_index));+ let tiles_keyed = key_band(&raster_space, band_tile_keys, &stack, band_index, VIEWPORT).tiles_keyed;+ (tiles_keyed, tiles_within(band_tile_keys, VIEWPORT))+ })+ .collect()+ }++ #[test]+ fn a_new_canvas_frame_keys_again_only_the_bands_whose_records_draw_the_canvas() {+ let canvas_rect = IntRect::new(100, 100, 200, 100);+ let (tree, root) = tree_with_root_isolation_effect(1.0);+ let list_with_canvas_in_own_layer = ListOfOneChunk::default()+ .with(fill(VIEWPORT, GREEN), root)+ .with(canvas(canvas_rect, 1), root);+ let display_list = DisplayListStorage::of_builder(&list_with_canvas_in_own_layer.builder);+ assert!(+ stack_of(&display_list, &tree)+ .layers+ .iter()+ .any(|layer| matches!(layer.identity, LayerIdentity::Media { .. }))+ );+ let frames =+ tiles_keyed_and_kept_in_frames_with_a_new_canvas_generation(&list_with_canvas_in_own_layer, &tree, 0);+ assert!(frames[0].0 > 0);+ assert_eq!([frames[1].0, frames[2].0], [0, 0]);++ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let moved_by_filter = tree.append_effect_node_under(+ root,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: Some(Arc::new(+ libgfx_rust::filter::Filter::Offset {+ dx: 40.0,+ dy: 0.0,+ input: None,+ }+ .serialize(),+ )),+ backdrop_filter: None,+ }),+ );+ let list_with_canvas_in_filter = ListOfOneChunk::default()+ .with(fill(VIEWPORT, GREEN), root)+ .with(canvas(canvas_rect, 1), moved_by_filter);+ let display_list = DisplayListStorage::of_builder(&list_with_canvas_in_filter.builder);+ assert!(+ !stack_of(&display_list, &tree)+ .layers+ .iter()+ .any(|layer| matches!(layer.identity, LayerIdentity::Media { .. }))+ );+ let frames = tiles_keyed_and_kept_in_frames_with_a_new_canvas_generation(&list_with_canvas_in_filter, &tree, 1);+ assert!(frames[0].0 > 0);+ assert_eq!([frames[1].0, frames[2].0], [frames[0].0, frames[0].0]);+ let cell_drawing_the_canvas = cell_of(canvas_rect);+ assert_eq!(+ cells_whose_hashes_differ(&frames[0].1, &frames[1].1),+ [cell_drawing_the_canvas]+ );+ assert_eq!(+ cells_whose_hashes_differ(&frames[1].1, &frames[2].1),+ [cell_drawing_the_canvas]+ );+ }++ fn cells_whose_hashes_differ(+ before: &[(TileCoord, LayerIndex, ContentHash)],+ after: &[(TileCoord, LayerIndex, ContentHash)],+ ) -> Vec<TileCoord> {+ before+ .iter()+ .zip(after)+ .filter(|(before, after)| before != after)+ .map(|(before, _)| before.0)+ .collect()+ }++ fn cell_of(rect: IntRect) -> TileCoord {+ TileCoord::new(rect.x / TILE_SIZE_IN_DEVICE_PIXELS, rect.y / TILE_SIZE_IN_DEVICE_PIXELS)+ }++ // Each sample keys every tile of the band again, and only the tile that draws a value the sample changed gets a new+ // hash.+ fn assert_only_the_cell_drawing_the_sampled_value_gets_a_new_hash(+ display_list: &DisplayListStorage,+ stack: &LayerStack,+ band_index: BandIndex,+ tree: &VisualContextTree,+ cell_drawing_the_sampled_value: TileCoord,+ ) {+ let at_start = tree.with_visual_animation_samples(0);+ let halfway = tree.with_visual_animation_samples(500_000_000);+ let halfway_again = tree.with_visual_animation_samples(500_000_000);+ let turns = counts_and_viewport_tile_hashes_of_samples_keyed_in_turn_under_one_geometry(+ display_list,+ stack,+ band_index,+ &[&at_start, &halfway, &halfway_again],+ );+ let keyed_from_nothing = key_band_in_frames_in_turn(+ &[(display_list, &halfway, stack)],+ RasterSpaceIndex::VIEWPORT,+ band_index,+ );+ assert_eq!(turns[1].1, keyed_from_nothing[0].2);+ assert_eq!(+ cells_whose_hashes_differ(&turns[0].1, &turns[1].1),+ [cell_drawing_the_sampled_value]+ );+ assert_eq!(turns[1].0.tiles_keyed, turns[1].1.len());+ assert_eq!(turns[2].0.tiles_keyed, turns[2].1.len());+ assert_eq!(turns[2].1, turns[1].1);+ }++ #[test]+ fn a_tile_kept_through_an_animation_sample_reads_the_sampled_background_color_again() {+ use crate::visual_animation::{VisualAnimationKeyframe, VisualAnimationValue};+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let animated_color = tree.append_effect(+ EffectNodeData::BackgroundColorAnimation,+ root.effect,+ VISUAL_VIEWPORT_NODE_INDEX,+ ClipNodeIndex::NONE,+ );+ let color_at = |offset: f64, color: Color| VisualAnimationKeyframe {+ offset,+ easing: crate::easing::Easing::default(),+ value: VisualAnimationValue::BackgroundColor(color),+ };+ tree.set_visual_animations(vec![animation_of(+ FfiVisualAnimationTargetKind::BackgroundColor,+ animated_color.0,+ vec![color_at(0.0, RED), color_at(1.0, BLUE)],+ )]);+ let animated_box = IntRect::new(600, 400, 20, 20);+ let display_list = DisplayListStorage::of_chunks(vec![+ chunk_of(fill(VIEWPORT, GREEN), root),+ chunk_of(+ FillRect {+ background_color_animation_effect: animated_color,+ ..fill(animated_box, RED)+ },+ ContextRef {+ effect: animated_color,+ ..root+ },+ ),+ ])+ .unwrap();+ let stack = stack_of(&display_list, &tree.with_visual_animation_samples(0));+ assert_only_the_cell_drawing_the_sampled_value_gets_a_new_hash(+ &display_list,+ &stack,+ BandIndex(0),+ &tree,+ cell_of(animated_box),+ );+ }++ struct ListWithBoxWhoseAnimatedOpacityHasNoLayer {+ display_list: Arc<DisplayListStorage>,+ stack: LayerStack,+ effect_without_layer: EffectNodeIndex,+ band_of_box_without_layer: BandIndex,+ }++ const BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER: IntRect = IntRect::new(600, 550, 20, 20);++ // The compositor gives layers of their own to the first effects in paint order whose opacity it animates, up to a+ // limit, and tiles draw the opacity of the others. The box of the last one is inside `around_box_without_layer`.+ fn list_with_a_box_whose_animated_opacity_has_no_layer(+ tree: &mut VisualContextTree,+ root: ContextRef,+ around_box_without_layer: ContextRef,+ ) -> ListWithBoxWhoseAnimatedOpacityHasNoLayer {+ use crate::display_list::layers::planning::MAXIMUM_ANIMATED_NODES_WITH_LAYERS;+ use crate::visual_animation::VisualAnimation;+ let faded: Vec<ContextRef> = (0..=MAXIMUM_ANIMATED_NODES_WITH_LAYERS)+ .map(|index| {+ let parent = if index == MAXIMUM_ANIMATED_NODES_WITH_LAYERS {+ around_box_without_layer+ } else {+ root+ };+ tree.append_effect_node_under(parent, effects(1.0, CompositingAndBlendingOperator::Normal))+ })+ .collect();+ tree.set_visual_animations(vec![VisualAnimation {+ node_indices: faded.iter().map(|context| context.effect.0).collect(),+ ..opacity_animation_of(faded[0].effect, 1.0, 0.2)+ }]);+ let mut chunks = vec![chunk_of(fill(VIEWPORT, GREEN), root)];+ chunks.extend(faded.iter().enumerate().map(|(index, &context)| {+ let rect = if index == MAXIMUM_ANIMATED_NODES_WITH_LAYERS {+ BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER+ } else {+ IntRect::new(10 + 12 * index as i32, 10, 10, 10)+ };+ chunk_of(fill(rect, BLUE), context)+ }));+ let display_list = DisplayListStorage::of_chunks(chunks).unwrap();+ let stack = stack_of(&display_list, &tree.with_visual_animation_samples(0));+ let effect_without_layer = faded[MAXIMUM_ANIMATED_NODES_WITH_LAYERS].effect;+ assert_eq!(stack.composited_effects.len(), MAXIMUM_ANIMATED_NODES_WITH_LAYERS);+ assert!(+ stack+ .composited_effects+ .iter()+ .all(|composited| composited.effect != effect_without_layer)+ );+ let position_of_box_without_layer = ListPosition::new(ChunkIndexInList(faded.len() as u32), 0);+ let band_of_box_without_layer = BandIndex(+ stack+ .bands+ .iter()+ .position(|band| {+ band.record_spans+ .iter()+ .any(|span| span.contains(position_of_box_without_layer))+ })+ .expect("a band holds the box"),+ );+ ListWithBoxWhoseAnimatedOpacityHasNoLayer {+ display_list,+ stack,+ effect_without_layer,+ band_of_box_without_layer,+ }+ }++ #[test]+ fn a_tile_kept_through_an_animation_sample_reads_the_sampled_opacity_of_an_effect_without_a_layer_again() {+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let list = list_with_a_box_whose_animated_opacity_has_no_layer(&mut tree, root, root);+ assert_only_the_cell_drawing_the_sampled_value_gets_a_new_hash(+ &list.display_list,+ &list.stack,+ list.band_of_box_without_layer,+ &tree,+ cell_of(BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER),+ );+ }++ #[test]+ fn a_kept_tile_reads_the_sampled_opacity_of_an_effect_without_a_layer_inside_a_blur_again() {+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let blurred = tree.append_effect_node_under(+ root,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: Some(Arc::new(libgfx_rust::filter::Filter::blur(4.0, 4.0, None).serialize())),+ backdrop_filter: None,+ }),+ );+ let list = list_with_a_box_whose_animated_opacity_has_no_layer(&mut tree, root, blurred);+ let list_keying = TileKeyingOfList::new(&list.display_list, &tree, &list.stack, NO_FRAME_STATE);+ assert_eq!(+ list_keying+ .filters_of_effects()+ .nearest_spreading_effect_at_or_above(list.effect_without_layer),+ blurred.effect+ );+ assert_only_the_cell_drawing_the_sampled_value_gets_a_new_hash(+ &list.display_list,+ &list.stack,+ list.band_of_box_without_layer,+ &tree,+ cell_of(BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER),+ );+ }++ // An effect that holds a backdrop filter gets no layer for the animation of its opacity.+ #[test]+ fn a_kept_tile_with_no_raster_margin_known_reads_the_sampled_opacity_of_an_effect_without_a_layer_again() {+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let faded = tree.append_effect_node_under(root, effects(1.0, CompositingAndBlendingOperator::Normal));+ tree.set_visual_animations(vec![opacity_animation_of(faded.effect, 1.0, 0.2)]);+ let region_of_glass = IntRect::new(590, 540, 40, 40);+ let blur_radius_past_largest_raster_margin = LARGEST_RASTER_MARGIN_IN_DEVICE_PIXELS as f32;+ let glass = tree.append_effect_node_under(+ faded,+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: Some(crate::visual_context::BackdropFilterData {+ filter: Arc::new(+ libgfx_rust::filter::Filter::blur(+ blur_radius_past_largest_raster_margin,+ blur_radius_past_largest_raster_margin,+ None,+ )+ .serialize(),+ ),+ region: region_of_glass,+ corner_radii: CornerRadii::default(),+ }),+ }),+ );+ let display_list = DisplayListStorage::of_chunks(vec![+ chunk_of(fill(VIEWPORT, GREEN), root),+ chunk_of(fill(BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER, BLUE), faded),+ chunk_of(fill(region_of_glass, BLUE), glass),+ ])+ .unwrap();+ let stack = stack_of(&display_list, &tree.with_visual_animation_samples(0));+ assert!(stack.composited_effects.is_empty());+ let (band_tile_keys, _) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ &[VIEWPORT],+ );+ let cell_of_box = cell_of(BOX_WHOSE_ANIMATED_OPACITY_HAS_NO_LAYER);+ assert_eq!(+ band_tile_keys+ .tile(cell_of_box, stack.base_layer)+ .map(|tile| tile.raster_margin_in_device_pixels),+ Some(None)+ );+ assert_only_the_cell_drawing_the_sampled_value_gets_a_new_hash(+ &display_list,+ &stack,+ BandIndex(0),+ &tree,+ cell_of_box,+ );+ }++ // A tree from another process can nest plain effects as deep as it likes, each clipped by a chain of clips as deep.+ // A red plane in front of a blue plane that covers the viewport, though the red plane comes first in the list, as+ // `transform-style: preserve-3d` and `translateZ()` make them, drawn as one layer.+ #[test]+ fn the_tiles_of_one_layer_over_planes_sorted_by_depth_replay_the_whole_list_and_have_no_coverage_known() {+ let (mut tree, viewport) = tree_with_root_isolation_effect(1.0);+ let context_root = tree.append_spatial(+ SpatialData::Transform(TransformData {+ establishes_sorting_context: true,+ ..transform(VIEWPORT.to_float())+ }),+ viewport.spatial,+ );+ let mut plane_at = |matrix: FloatMatrix4x4| ContextRef {+ spatial: tree.append_spatial(+ SpatialData::Transform(TransformData {+ matrix,+ sorting_context_root_index: Some(context_root),+ ..transform(VIEWPORT.to_float())+ }),+ context_root,+ ),+ ..viewport+ };+ let mut moved_forward = FloatMatrix4x4::identity();+ moved_forward.elements[2][3] = 10.0;+ let red_plane = plane_at(moved_forward);+ let blue_plane = plane_at(FloatMatrix4x4::identity());+ let display_list = ListOfOneChunk::default()+ .with(fill(VIEWPORT, RED), red_plane)+ .with(fill(VIEWPORT, BLUE), blue_plane)+ .storage();+ let stack = LayerStack::one_layer_replaying_whole_list(+ VIEWPORT,+ display_list.whole_span(),+ Some(WhyListIsOneLayer::FrameIsNotDrawnAsPlanned),+ LayeringObstacles::of(&display_list, &tree),+ );+ assert!(stack.one_layer_list_cannot_tell_which_records_show_in_tile());+ let list_keying = TileKeyingOfList::new(&display_list, &tree, &stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(&tree, &stack, RasterSpaceIndex::VIEWPORT);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let mut band_tile_keys = raster_space.bind_band(&stack, BandIndex(0));+ key_band(&raster_space, &mut band_tile_keys, &stack, BandIndex(0), VIEWPORT);+ // Walked in list order from the opaque clear color, the blue fill would cover what the red plane draws.+ let tile = band_tile_keys+ .tile(TileCoord::new(0, 0), stack.base_layer)+ .expect("the base layer holds a tile at every shown cell");+ let white = Color::from_rgb(255, 255, 255);+ assert_eq!(+ raster_space.coverage_of_tile(&band_tile_keys, tile, tile.coord.cell_rect(), white),+ TileCoverage::Unknown+ );+ }++ #[test]+ fn the_coverage_of_a_tile_under_deeply_nested_effects_and_clips_holds_what_its_fills_draw() {+ use crate::visual_context::VisualContextNodeSink;+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let mut innermost = root;+ for _ in 0..20_000 {+ innermost = tree.append_clip_node_under(+ innermost,+ ClipNodeData::Rect(ClipData {+ rect: VIEWPORT.to_float(),+ corner_radii: CornerRadii::default(),+ mode: ClipMode::Intersect,+ }),+ );+ innermost = tree.append_effect_node_under(innermost, effects(1.0, CompositingAndBlendingOperator::Normal));+ }+ let multiplied_fill = FillRect {+ compositing_and_blending_operator: CompositingAndBlendingOperator::Multiply,+ ..fill(VIEWPORT, BLUE)+ };+ let display_list = DisplayListStorage::of_chunks(vec![+ chunk_of(fill(VIEWPORT, GREEN), innermost),+ chunk_of(multiplied_fill, innermost),+ ])+ .unwrap();+ let stack = stack_of(&display_list, &tree);+ let list_keying = TileKeyingOfList::new(&display_list, &tree, &stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(&tree, &stack, RasterSpaceIndex::VIEWPORT);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let mut band_tile_keys = raster_space.bind_band(&stack, BandIndex(0));+ key_band(&raster_space, &mut band_tile_keys, &stack, BandIndex(0), VIEWPORT);+ let tile = band_tile_keys+ .tile(TileCoord::new(0, 0), stack.base_layer)+ .expect("the base layer holds a tile at every shown cell");+ let area = tile.coord.cell_rect();+ assert_eq!(+ raster_space.coverage_of_tile(&band_tile_keys, tile, area, Color::TRANSPARENT),+ TileCoverage::Opaque+ );+ }++ fn band_of_space(stack: &LayerStack, raster_space_index: RasterSpaceIndex) -> BandIndex {+ BandIndex(+ stack+ .bands+ .iter()+ .position(|band| stack.nodes[band.placement_node_index.0].raster_space_index == raster_space_index)+ .expect("the space has a band"),+ )+ }++ // The rect of the space that the viewport shows through a transform that scales the space by `scale`.+ fn viewport_in_space_scaled_by(scale: f32) -> IntRect {+ SpaceToFrame::Transform(AffineTransform::new(scale, 0.0, 0.0, scale, 0.0, 0.0)).rect_in_space(VIEWPORT)+ }++ fn band_tile_keys_after_frames_showing(+ frame: (&DisplayListStorage, &VisualContextTree, &LayerStack),+ raster_space_index: RasterSpaceIndex,+ band_index: BandIndex,+ shown_rects: &[IntRect],+ ) -> (BandTileKeys, Vec<TileKeyingCounts>) {+ let (display_list, tree, stack) = frame;+ let list_keying = TileKeyingOfList::new(display_list, tree, stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(tree, stack, raster_space_index);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let mut band_tile_keys = raster_space.bind_band(stack, band_index);+ let counts = shown_rects+ .iter()+ .map(|&shown_rect| key_band(&raster_space, &mut band_tile_keys, stack, band_index, shown_rect))+ .collect();+ (band_tile_keys, counts)+ }++ fn viewport_filled_with_green() -> (VisualContextTree, Arc<DisplayListStorage>) {+ let (tree, root) = tree_with_root_isolation_effect(1.0);+ let display_list = DisplayListStorage::of_chunks(vec![chunk_of(fill(VIEWPORT, GREEN), root)]).unwrap();+ (tree, display_list)+ }++ // A run that the held ranges skip, and a held range over several runs.+ #[test]+ fn held_runs_are_found_by_binary_search_of_the_held_ranges() {+ let run = |offset: u32, size: u32| DisplayListCommandRun {+ offset,+ size,+ ..DisplayListCommandRun::default()+ };+ let runs = [+ run(0, 16),+ run(16, 32),+ run(48, 16),+ run(64, 16),+ run(80, 16),+ run(96, 16),+ ];+ let held_offset_ranges = [(16, 48), (64, 112)];+ let overlap =+ |run: &DisplayListCommandRun, &(begin, end): &(u32, u32)| begin < run.offset + run.size && run.offset < end;+ let held_runs_one_by_one: Vec<RunIndexInChunk> = runs+ .iter()+ .enumerate()+ .filter(|(_, run)| held_offset_ranges.iter().any(|range| overlap(run, range)))+ .map(|(run_index, _)| RunIndexInChunk(run_index as u32))+ .collect();+ assert_eq!(+ runs_within_held_offset_ranges(&runs, &held_offset_ranges),+ held_runs_one_by_one+ );+ let held_offset_ranges = [(8, 24), (40, 56), (80, 112)];+ for offset in 0..120 {+ assert_eq!(+ offset_is_held(&held_offset_ranges, offset),+ held_offset_ranges+ .iter()+ .any(|&(begin, end)| begin <= offset && offset < end)+ );+ }+ }++ // A tree from another process can chain clips and effects as deep as it holds nodes.+ #[test]+ fn content_inside_a_chain_of_100000_clips_and_effects_is_keyed() {+ const CHAIN_LENGTH: usize = 100_000;+ let (mut tree, mut context) = tree_with_root_isolation_effect(1.0);+ for _ in 0..CHAIN_LENGTH {+ let clip = tree.append_clip(+ ClipNodeData::Rect(ClipData {+ rect: VIEWPORT.to_float(),+ corner_radii: CornerRadii::default(),+ mode: ClipMode::Intersect,+ }),+ context.clip,+ context.spatial,+ );+ context = tree.append_effect_node_under(+ ContextRef { clip, ..context },+ effects(1.0, CompositingAndBlendingOperator::Normal),+ );+ }+ let display_list =+ DisplayListStorage::of_builder(&ListOfOneChunk::default().with(fill(VIEWPORT, GREEN), context).builder);+ let stack = LayerStack::one_layer_replaying_whole_list(+ VIEWPORT,+ display_list.whole_span(),+ None,+ LayeringObstacles::default(),+ );+ let list_keying = TileKeyingOfList::new(&display_list, &tree, &stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(&tree, &stack, RasterSpaceIndex::VIEWPORT);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let mut band_tile_keys = raster_space.bind_band(&stack, BandIndex(0));+ key_band(&raster_space, &mut band_tile_keys, &stack, BandIndex(0), VIEWPORT);+ assert_eq!(tiles_within(&band_tile_keys, VIEWPORT).len(), 4);+ assert_ne!(raster_space.content_hash_of_composited_effect(context.effect), 0);+ }++ fn backdrop_read_of_viewport(read_reach: i32, spread_past_region: i32) -> BackdropReadInLayer {+ BackdropReadInLayer {+ first_record_position: ListPosition::default(),+ region_reach: Reach::Within(VIEWPORT),+ backdrop_read_reach: Reach::Within(VIEWPORT),+ read_reach_in_device_pixels: Some(read_reach),+ spread_past_region_in_device_pixels: spread_past_region,+ mirroring_blur_region: None,+ }+ }++ // A backdrop filter in a tree from another process can spread what it reads about as far as the extent of a space.+ #[test]+ fn a_tile_whose_backdrop_filters_read_farther_than_the_largest_raster_margin_has_no_margin_known() {+ let cell = TileCoord::new(0, 0).cell_rect();+ let largest = LARGEST_RASTER_MARGIN_IN_DEVICE_PIXELS;+ let at_largest = [+ backdrop_read_of_viewport(2000, largest - 2100),+ backdrop_read_of_viewport(100, 0),+ ];+ let raster_margin_of_cell =+ |reads: Vec<BackdropReadInLayer>| BackdropReadsOfBand::new(reads).raster_margin_of_cell(cell);+ assert_eq!(raster_margin_of_cell(at_largest.into()), Some(largest));+ let past_largest = [+ backdrop_read_of_viewport(2000, largest - 2100),+ backdrop_read_of_viewport(101, 0),+ ];+ assert_eq!(raster_margin_of_cell(past_largest.into()), None);+ let spread_as_far_as_the_extent: Vec<BackdropReadInLayer> =+ (0..5).map(|_| backdrop_read_of_viewport(2051, 1 << 29)).collect();+ assert_eq!(raster_margin_of_cell(spread_as_far_as_the_extent), None);+ let elsewhere = BackdropReadInLayer {+ region_reach: Reach::Within(TileCoord::new(4, 4).cell_rect()),+ ..backdrop_read_of_viewport(2051, 1 << 29)+ };+ assert_eq!(raster_margin_of_cell(vec![elsewhere]), Some(0));+ }++ // A tree from another process can put any number of backdrop filters in one band.+ #[test]+ fn a_band_follows_backdrop_reads_one_by_one_up_to_a_bound_and_takes_their_regions_as_reached_past_it() {+ let backdrop_reads = |count: usize| {+ BackdropReadsOfBand::new(+ (0..count as i32)+ .map(|index| {+ let region = IntRect::new(600 + index, 10, 1, 1);+ BackdropReadInLayer {+ first_record_position: ListPosition::new(ChunkIndexInList(0), 100 + index as u32),+ region_reach: Reach::Within(region),+ backdrop_read_reach: Reach::Within(region.inflated_edges(1, 1, 1, 1)),+ read_reach_in_device_pixels: Some(1),+ spread_past_region_in_device_pixels: 0,+ mirroring_blur_region: None,+ }+ })+ .collect(),+ )+ };+ let content_reach = Reach::Within(IntRect::new(0, 0, 10, 10));+ let painted_before_every_read = ListPosition::new(ChunkIndexInList(0), 0);+ let cell_of_regions = TileCoord::new(1, 0).cell_rect();+ let cell_of_content = TileCoord::new(0, 0).cell_rect();++ let followed = backdrop_reads(MAXIMUM_BACKDROP_READS_A_BAND_FOLLOWS_ONE_BY_ONE);+ assert_eq!(+ followed.reach_extended_through_reads(content_reach, painted_before_every_read),+ content_reach+ );+ assert_eq!(+ followed.raster_margin_of_cell(cell_of_regions),+ Some(MAXIMUM_BACKDROP_READS_A_BAND_FOLLOWS_ONE_BY_ONE as i32)+ );+ assert_eq!(followed.raster_margin_of_cell(cell_of_content), Some(0));++ let past_bound = backdrop_reads(MAXIMUM_BACKDROP_READS_A_BAND_FOLLOWS_ONE_BY_ONE + 1);+ assert_eq!(+ past_bound.reach_extended_through_reads(content_reach, painted_before_every_read),+ content_reach.united(past_bound.region_reach_of_every_read)+ );+ assert_eq!(past_bound.raster_margin_of_cell(cell_of_regions), None);+ assert_eq!(past_bound.raster_margin_of_cell(cell_of_content), Some(0));+ }++ // The region of a backdrop filter in a tree from another process can lie past the extent of any space.+ #[test]+ fn a_backdrop_filter_whose_region_lies_past_the_extent_limit_reads_within_rects_whose_edges_fit() {+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let region_past_extent_limit = IntRect::new(i32::MAX - 1000, 0, 1000, 100);+ let frosted = frosted_glass(&mut tree, root, region_past_extent_limit);+ let list = ListOfOneChunk::default()+ .with(fill(VIEWPORT, GREEN), root)+ .with(fill(region_past_extent_limit, BLUE), frosted);+ let display_list = DisplayListStorage::of_builder(&list.builder);+ let stack = LayerStack::one_layer_replaying_whole_list(+ VIEWPORT,+ display_list.whole_span(),+ None,+ LayeringObstacles::default(),+ );+ let list_keying = TileKeyingOfList::new(&display_list, &tree, &stack, NO_FRAME_STATE);+ let geometry = geometry_of_space(&tree, &stack, RasterSpaceIndex::VIEWPORT);+ let raster_space = TileKeyingOfRasterSpace::new(&list_keying, &geometry);+ let backdrop_read = raster_space.backdrop_read_in_layer(frosted.effect, display_list.whole_span().begin);+ let edges_fit_in_int_rect = |reach: Reach<IntRect>| match reach {+ Reach::Within(rect) => {+ rect.x.checked_add(rect.width).is_some() && rect.y.checked_add(rect.height).is_some()+ }+ Reach::Nothing | Reach::Anywhere => true,+ };+ assert!(edges_fit_in_int_rect(backdrop_read.backdrop_read_reach));+ assert!(edges_fit_in_int_rect(backdrop_read.region_reach));+ let (band_tile_keys, _) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ &[VIEWPORT],+ );+ assert_eq!(tiles_within(&band_tile_keys, VIEWPORT).len(), 4);+ }++ // A box that the compositor scales up from nothing shows at a tiny part of its raster scale at first.+ #[test]+ fn a_band_shown_at_a_tiny_part_of_its_raster_scale_keys_only_the_cells_its_content_reaches() {+ let (tree, display_list, _) = sliding_box_tree_and_list(false);+ let at_start = tree.with_visual_animation_samples(0);+ let stack = stack_of(&display_list, &at_start);+ let animated_space = RasterSpaceIndex(1);+ let band = band_of_space(&stack, animated_space);+ let shown_rect = viewport_in_space_scaled_by(1.0e-4);+ assert!(CellRange::touched_by(shown_rect).cell_count() > 100_000_000);++ let frame = (&*display_list, &at_start, &stack);+ let (keyed_at_tiny_scale, counts) =+ band_tile_keys_after_frames_showing(frame, animated_space, band, &[shown_rect, shown_rect]);+ let tiles = tiles_within(&keyed_at_tiny_scale, shown_rect);+ let (keyed_at_raster_scale, _) = band_tile_keys_after_frames_showing(frame, animated_space, band, &[VIEWPORT]);+ assert!(!tiles.is_empty());+ assert_eq!(tiles, tiles_within(&keyed_at_raster_scale, VIEWPORT));+ let mut cells_of_tiles: Vec<TileCoord> = tiles.iter().map(|(coord, _, _)| *coord).collect();+ cells_of_tiles.dedup();+ assert!(keyed_at_tiny_scale.cells.keys().copied().eq(cells_of_tiles));+ // A frame that shows the same rect again looks for no cell to key.+ assert_eq!(counts[1], TileKeyingCounts::default());+ }++ // A scroll within the rows and columns of cells that a frame showed shows no new cell, so the band must have keyed+ // every cell of those that it holds something in, also where its content lies outside the pixels that frame showed.+ #[test]+ fn a_band_keys_content_in_a_shown_cell_outside_the_shown_pixels_before_a_scroll_shows_it() {+ let (mut tree, _, document) = tree_with_document_scroll();+ let faded = tree.append_effect_node_under(document, effects(1.0, CompositingAndBlendingOperator::Normal));+ tree.set_visual_animations(vec![opacity_animation_of(faded.effect, 1.0, 0.2)]);+ let box_below_viewport = IntRect::new(100, 700, 100, 200);+ let display_list = DisplayListStorage::of_chunks(vec![+ chunk_of(fill(IntRect::new(0, 0, 800, 2600), GREEN), document),+ chunk_of(fill(box_below_viewport, BLUE), faded),+ ])+ .unwrap();+ let tree = tree.with_visual_animation_samples(0);+ let stack = stack_of(&display_list, &tree);+ let position_of_box = ListPosition::new(ChunkIndexInList(1), 0);+ let band_of_box = BandIndex(+ stack+ .bands+ .iter()+ .position(|band| band.record_spans.iter().any(|span| span.contains(position_of_box)))+ .expect("a band holds the box"),+ );+ assert_ne!(stack.bands[band_of_box.0].layer_below_all_cuts, stack.base_layer);+ let scrolled_by_200 = VIEWPORT.translated(0, 200);+ assert_eq!(CellRange::touched_by(scrolled_by_200), CellRange::touched_by(VIEWPORT));+ assert!(VIEWPORT.intersected(box_below_viewport).is_empty());++ let document_space = stack.nodes[stack.bands[band_of_box.0].placement_node_index.0].raster_space_index;+ assert_ne!(document_space, RasterSpaceIndex::VIEWPORT);+ let (band_tile_keys, _) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ document_space,+ band_of_box,+ &[VIEWPORT, scrolled_by_200],+ );+ assert_eq!(+ tiles_within(&band_tile_keys, scrolled_by_200.intersected(box_below_viewport))+ .iter()+ .map(|(coord, _, _)| *coord)+ .collect::<Vec<_>>(),+ [cell_of(box_below_viewport)]+ );+ }++ #[test]+ fn a_band_keys_at_most_the_budget_of_cells_nearest_to_the_middle_of_what_it_shows() {+ let (tree, display_list) = viewport_filled_with_green();+ let stack = stack_of(&display_list, &tree);+ assert_eq!(stack.base_layer, stack.bands[0].layer_below_all_cuts);+ // The band of the base layer holds a tile at every cell it shows.+ let shown_rect = viewport_in_space_scaled_by(1.0e-4);+ let moved_shown_rect = shown_rect.translated(10 * TILE_SIZE_IN_DEVICE_PIXELS, 0);+ let (band_tile_keys, counts) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ &[shown_rect, shown_rect, moved_shown_rect],+ );+ let middle_of = |rect: IntRect| TileCoord::of_pixel(rect.x + rect.width / 2, rect.y + rect.height / 2);+ assert!(+ counts+ .iter()+ .all(|counts| counts.tiles_keyed <= MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME)+ );+ assert!(counts[0].tiles_keyed > MAXIMUM_CELLS_ONE_BAND_KEYS_IN_A_FRAME / 2);+ assert_eq!(counts[1], TileKeyingCounts::default());+ // Moving the window by ten columns keys the cells it now holds and forgets those it left.+ let window = CellRange::around(middle_of(moved_shown_rect), 31);+ assert_eq!(window.cell_count(), 63 * 63);+ assert_eq!(counts[2].tiles_keyed, 10 * 63);+ assert!(+ band_tile_keys+ .cells+ .keys()+ .copied()+ .eq(window.coords().collect::<BTreeSet<_>>())+ );+ assert_eq!(+ tiles_within(&band_tile_keys, moved_shown_rect).len(),+ window.cell_count() as usize+ );+ }++ #[test]+ fn a_space_whose_transform_is_not_finite_or_has_no_inverse_keys_nothing() {+ let (tree, display_list) = viewport_filled_with_green();+ let stack = stack_of(&display_list, &tree);+ for transform in [+ AffineTransform::new(f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0),+ AffineTransform::new(1.0, 0.0, 0.0, 1.0, 0.0, f32::INFINITY),+ AffineTransform::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0),+ AffineTransform::new(1.0e-30, 0.0, 0.0, 1.0e-30, 0.0, 0.0),+ ] {+ let shown_rect = SpaceToFrame::Transform(transform).rect_in_space(VIEWPORT);+ assert_eq!(shown_rect, IntRect::default());+ let (band_tile_keys, counts) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, &stack),+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ &[shown_rect],+ );+ assert!(band_tile_keys.cells.is_empty());+ assert_eq!(counts[0], TileKeyingCounts::default());+ }+ }++ fn span_from_run_to_end_of_list(display_list: &DisplayListStorage, chunk_index: u32, run_index: usize) -> ListSpan {+ let chunk_index = ChunkIndexInList(chunk_index);+ ListSpan {+ begin: ListPosition::new(chunk_index, display_list.chunk(chunk_index).runs()[run_index].offset),+ end: display_list.whole_span().end,+ }+ }++ // A band of what a mask holds can hold the declaration of the mask's content, leave it out, or also hold other runs+ // of the chunk of the declaration, which draw away from the cells the masked content reaches.+ #[test]+ fn a_tile_of_masked_content_replays_the_declaration_of_its_mask_and_no_other_run_of_its_chunk() {+ use crate::visual_context::{MaskData, MaskLayerOrigin};+ let (mut tree, root) = tree_with_root_isolation_effect(1.0);+ let masked = tree.append_effect_node_under(+ root,+ EffectNodeData::Mask(MaskData {+ rect: IntRect::new(0, 0, 100, 100),+ kind: libgfx_rust::MaskKind::Alpha,+ origin: MaskLayerOrigin::CssMaskLayers,+ masks_backdrop: false,+ }),+ );+ let isolated = tree.append_effect_node_under(+ root,+ EffectNodeData::Effects(EffectsData {+ isolation: true,+ opacity: 1.0,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter: None,+ backdrop_filter: None,+ }),+ );+ // The first run of the first chunk is a box, and the second the declaration, which both draw in the cell to the+ // right of the cell of the masked box.+ let mut builder = DisplayListBuilder::new();+ builder.append(&fill(IntRect::new(700, 300, 50, 50), GREEN), &[], isolated);+ let declaration = builder.begin_group::<DeclareMaskContent>(Vec::new());+ builder.append(&fill(IntRect::new(600, 0, 50, 50), RED), &[], root);+ let content = builder.group_content_span(&declaration);+ builder.finish_group(+ declaration,+ &DeclareMaskContent {+ rect: IntRect::new(600, 0, 100, 100),+ effect: masked.effect,+ content,+ },+ root,+ );+ let display_list = DisplayListStorage::of_chunks(vec![+ Arc::new(ListChunk::copied(builder.bytes(), builder.command_runs(), 0)),+ chunk_of(fill(IntRect::new(10, 10, 80, 80), BLUE), masked),+ ])+ .unwrap();+ let declaration_and_masked_box = {+ let mut stack = LayerStack::one_layer_replaying_whole_list(+ VIEWPORT,+ display_list.whole_span(),+ None,+ LayeringObstacles::default(),+ );+ stack.bands[0].record_spans = vec![span_from_run_to_end_of_list(&display_list, 0, 1)];+ stack+ };+ let mut masked_box_alone = declaration_and_masked_box.clone();+ masked_box_alone.bands[0].record_spans = vec![span_from_run_to_end_of_list(&display_list, 1, 0)];+ let mut both_runs_and_masked_box = declaration_and_masked_box.clone();+ both_runs_and_masked_box.bands[0].record_spans = vec![display_list.whole_span()];++ let cell_of_masked_box = TileCoord::new(0, 0);+ for stack in [+ &declaration_and_masked_box,+ &masked_box_alone,+ &both_runs_and_masked_box,+ ] {+ let (band_tile_keys, _) = band_tile_keys_after_frames_showing(+ (&display_list, &tree, stack),+ RasterSpaceIndex::VIEWPORT,+ BandIndex(0),+ &[VIEWPORT],+ );+ let spans_of_masked_box =+ band_tile_keys.record_spans_of_tiles(band_tile_keys.tile(cell_of_masked_box, LayerIndex(0)));+ let declaration_position = ListPosition::new(+ ChunkIndexInList(0),+ display_list.chunk(ChunkIndexInList(0)).runs()[1].offset,+ );+ let first_box_position = ListPosition::new(ChunkIndexInList(0), 0);+ assert!(+ spans_of_masked_box+ .iter()+ .any(|span| span.contains(declaration_position))+ );+ assert!(!spans_of_masked_box.iter().any(|span| span.contains(first_box_position)));+ }+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/tile_keys/chunk_placement.rs b/Libraries/LibCompositing/Rust/src/display_list/tile_keys/chunk_placement.rsnew file mode 100644index 00000000000..5e195c18f14--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/tile_keys/chunk_placement.rs@@ -0,0 +1,440 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The records of a chunk with what placing them and hashing tile content read of each, and how the records of a chunk+//! are placed in a raster space: the record ranges they are binned into tiles as, with the reach of each.++use super::{ContentHash, ContentHasher, EffectHashScope, TileKeyingOfRasterSpace};+use crate::display_list::builder::{+ HEADER_SIZE, bounding_rect_computed_from_payload, for_each_command, has_inline_clip_in_its_own_space, read_command,+};+use crate::display_list::commands::{+ ContextRef, DisplayListCommandRun, DisplayListCommandType, EffectNodeIndex, FillRect, FillRectWithRoundedCorners,+ FillRoundedRectRing,+};+use crate::display_list::nested_records::{+ NestedRecordsRole, for_each_command_including_nested, for_each_nested_record_span, span_bytes,+};+use crate::display_list::reach::Reach;+use crate::display_list::storage::{ChunkIndexInList, ListChunk, RunIndexInChunk};+use crate::display_list::summary::{command_blend, live_content_of};+use crate::display_list::window_server_placement::RoundedRect;+use libgfx_rust::{Color, CompositingAndBlendingOperator, CornerRadii, IntRect};+use std::sync::Arc;++pub(super) const FRAME_STATE_CARET_BLINK_PHASE: u8 = 1 << 0;+pub(super) const FRAME_STATE_SCROLL_BAR: u8 = 1 << 1;+pub(super) const FRAME_STATE_LIVE_CONTENT: u8 = 1 << 2;+pub(super) const FRAME_STATE_SPACES_OF_INLINE_CLIPS: u8 = 1 << 3;+pub(super) const FRAME_STATE_SAMPLED_BACKGROUND_COLOR: u8 = 1 << 4;+const FRAME_STATE_HASHED_FOR_THE_LIST: u8 =+ FRAME_STATE_CARET_BLINK_PHASE | FRAME_STATE_SCROLL_BAR | FRAME_STATE_LIVE_CONTENT;++/// A top-level record of a chunk, with what placing it and hashing tile content read of it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct ChunkRecord {+ pub(crate) offset: u32,+ pub(crate) end_offset: u32,+ pub(crate) run_index: RunIndexInChunk,+ pub(crate) bounding_rect: IntRect,+ draws_something: bool,+ pub(super) frame_state_read_flags: u8,+ pub(super) can_lower_destination_alpha: bool,+ // Record bytes hold no offset into the chunk, so a record hashes alike wherever it is.+ pub(super) content_hash_of_bytes: ContentHash,+}++impl ChunkRecord {+ pub(super) fn reads_frame_state_hashed_for_the_list(&self) -> bool {+ self.frame_state_read_flags & FRAME_STATE_HASHED_FOR_THE_LIST != 0+ }+}++/// The index of a top-level record in the `RecordTable` of its chunk.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct RecordIndexInChunk(pub u32);++/// The top-level records of a chunk, by run, with what hashing tile content needs of each.+#[derive(Debug, PartialEq, Eq)]+pub struct RecordTable {+ records: Vec<ChunkRecord>,+ first_record_index_of_each_run: Vec<RecordIndexInChunk>,+ run_reads_frame_state_hashed_for_the_list_by_run_index: Vec<bool>,+}++fn frame_state_read_flags_of_record(+ header: &crate::display_list::commands::DisplayListCommandHeader,+ payload: &[u8],+ record_bytes: &[u8],+) -> u8 {+ let mut flags = match header.command_type {+ DisplayListCommandType::PaintCaret => FRAME_STATE_CARET_BLINK_PHASE,+ DisplayListCommandType::PaintScrollBar => FRAME_STATE_SCROLL_BAR,+ _ => 0,+ };+ if header.inline_clip_count != 0 && has_inline_clip_in_its_own_space(header, payload) {+ flags |= FRAME_STATE_SPACES_OF_INLINE_CLIPS;+ }+ for_each_command_including_nested(record_bytes, &mut |command_type, _, payload| {+ if live_content_of(command_type, payload).is_some() {+ flags |= FRAME_STATE_LIVE_CONTENT;+ }+ if !background_color_animation_effect_of(command_type, payload).is_none() {+ flags |= FRAME_STATE_SAMPLED_BACKGROUND_COLOR;+ }+ });+ flags+}++// Records nested in a group, a pattern tile or a mask draw into a layer of their own; only those of a vector image draw+// straight into the destination.+fn record_can_lower_destination_alpha(command_type: DisplayListCommandType, payload: &[u8]) -> bool {+ if command_blend(command_type, payload).is_some_and(|(operator, _)| operator.lowers_destination_alpha()) {+ return true;+ }+ let mut can_lower = false;+ for_each_nested_record_span(command_type, payload, |role, span| {+ if role == NestedRecordsRole::VectorImage {+ for_each_command(span_bytes(payload, span), |header, _, payload| {+ can_lower |= record_can_lower_destination_alpha(header.command_type, payload);+ });+ }+ });+ can_lower+}++pub(super) fn background_color_animation_effect_of(+ command_type: DisplayListCommandType,+ payload: &[u8],+) -> EffectNodeIndex {+ match command_type {+ DisplayListCommandType::FillRect => read_command::<FillRect>(payload).background_color_animation_effect,+ DisplayListCommandType::FillRectWithRoundedCorners => {+ read_command::<FillRectWithRoundedCorners>(payload).background_color_animation_effect+ }+ _ => EffectNodeIndex::NONE,+ }+}++impl RecordTable {+ pub fn new(records_of_chunk: &[u8], command_runs: &[DisplayListCommandRun]) -> Self {+ let mut records = Vec::new();+ let mut first_record_index_of_each_run = Vec::with_capacity(command_runs.len() + 1);+ let mut run_reads_frame_state_hashed_for_the_list_by_run_index = Vec::with_capacity(command_runs.len());+ for (run_index, run) in command_runs.iter().enumerate() {+ let first_record_index_of_run = records.len();+ first_record_index_of_each_run.push(RecordIndexInChunk(first_record_index_of_run as u32));+ let run_bytes = &records_of_chunk[run.offset as usize..(run.offset + run.size) as usize];+ for_each_command(run_bytes, |header, offset_in_run, payload| {+ let offset = run.offset + offset_in_run as u32;+ let end_offset = offset + (HEADER_SIZE + payload.len()) as u32;+ let record_bytes = &records_of_chunk[offset as usize..end_offset as usize];+ let mut hasher = ContentHasher::new();+ hasher.write_bytes(record_bytes);+ let bounding_rect = bounding_rect_computed_from_payload(header, payload);+ records.push(ChunkRecord {+ offset,+ end_offset,+ run_index: RunIndexInChunk(run_index as u32),+ bounding_rect: bounding_rect.unwrap_or_default(),+ draws_something: !header.command_type.is_compositor_metadata()+ && bounding_rect.is_some_and(|rect| !rect.is_empty()),+ frame_state_read_flags: frame_state_read_flags_of_record(header, payload, record_bytes),+ can_lower_destination_alpha: record_can_lower_destination_alpha(header.command_type, payload),+ content_hash_of_bytes: hasher.finish(),+ });+ });+ run_reads_frame_state_hashed_for_the_list_by_run_index.push(+ records[first_record_index_of_run..]+ .iter()+ .any(ChunkRecord::reads_frame_state_hashed_for_the_list),+ );+ }+ first_record_index_of_each_run.push(RecordIndexInChunk(records.len() as u32));+ Self {+ records,+ first_record_index_of_each_run,+ run_reads_frame_state_hashed_for_the_list_by_run_index,+ }+ }++ pub(super) fn run_reads_frame_state_hashed_for_the_list(&self, run_index: RunIndexInChunk) -> bool {+ self.run_reads_frame_state_hashed_for_the_list_by_run_index[run_index.0 as usize]+ }++ pub(crate) fn record(&self, index: RecordIndexInChunk) -> &ChunkRecord {+ &self.records[index.0 as usize]+ }++ pub(crate) fn records_in(&self, indices: std::ops::Range<RecordIndexInChunk>) -> &[ChunkRecord] {+ &self.records[indices.start.0 as usize..indices.end.0 as usize]+ }++ pub(crate) fn record_indices_of_run(&self, run_index: RunIndexInChunk) -> std::ops::Range<RecordIndexInChunk> {+ let run_index = run_index.0 as usize;+ self.first_record_index_of_each_run[run_index]..self.first_record_index_of_each_run[run_index + 1]+ }++ pub(crate) fn record_indices_between_offsets(+ &self,+ begin_offset: u32,+ end_offset: u32,+ ) -> std::ops::Range<RecordIndexInChunk> {+ let first = self.records.partition_point(|record| record.offset < begin_offset);+ let end = self.records.partition_point(|record| record.offset < end_offset);+ RecordIndexInChunk(first as u32)..RecordIndexInChunk(end as u32)+ }+}++#[derive(Clone, Copy, Debug)]+pub(super) struct DeviceAlignedFill {+ pub(super) rect: RoundedRect,+ pub(super) unfilled_inner_rect_of_ring: Option<RoundedRect>,+ pub(super) content_hash_except_rects: ContentHash,+ pub(super) color: Color,+ pub(super) draws_recorded_color_with_source_over: bool,+}++/// The index of a range in the `record_ranges` of a `ChunkPlacedInRasterSpace`.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct PlacedRecordRangeIndex(pub u32);++#[derive(Clone, Copy, Debug)]+pub(super) struct PlacedRecordRange {+ pub(super) run_index: RunIndexInChunk,+ pub(super) first_record_index: RecordIndexInChunk,+ pub(super) end_record_index: RecordIndexInChunk,+ pub(super) begin_offset: u32,+ pub(super) end_offset: u32,+ pub(super) reach: Reach<IntRect>,+ pub(super) context: ContextRef,+ pub(super) is_spread_by_no_filter: bool,+ pub(super) device_aligned_fill: Option<DeviceAlignedFill>,+}++/// The ranges of a run: those it is binned as, from `first_binned_range_index` up to the range of the whole run.+#[derive(Clone, Copy, Debug, Default)]+pub(super) struct PlacedRecordRangesOfRun {+ pub(super) first_binned_range_index: PlacedRecordRangeIndex,+ pub(super) whole_run_range_index: PlacedRecordRangeIndex,+ pub(super) reach_of_binned_ranges: Reach<IntRect>,+}++/// What the records of a chunk hold in one raster space, as the geometry of the space places the visual contexts of+/// the chunk's runs it holds: the record ranges the records are binned into tiles as, the reach of each, and the+/// content hash of what each draws. A chunk caches its latest placements for every list that names it.+pub struct ChunkPlacedInRasterSpace {+ placement_inputs_hash: ContentHash,+ pub(super) record_ranges: Vec<PlacedRecordRange>,+ pub(super) ranges_of_each_run: Vec<PlacedRecordRangesOfRun>,+}++impl ChunkPlacedInRasterSpace {+ pub fn placement_inputs_hash(&self) -> ContentHash {+ self.placement_inputs_hash+ }+}++impl TileKeyingOfRasterSpace<'_> {+ fn place_record_range(+ &self,+ chunk: &ListChunk,+ run_index: RunIndexInChunk,+ record_indices: std::ops::Range<RecordIndexInChunk>,+ reach: Reach<IntRect>,+ ) -> PlacedRecordRange {+ let table = chunk.record_table();+ let context = chunk.runs()[run_index.0 as usize].context;+ let is_spread_by_filters = !self+ .list+ .filters_of_effects()+ .nearest_spreading_effect_at_or_above(context.effect)+ .is_none();+ let is_one_record = (record_indices.start.0..record_indices.end.0).len() == 1;+ PlacedRecordRange {+ run_index,+ first_record_index: record_indices.start,+ end_record_index: record_indices.end,+ begin_offset: table.record(record_indices.start).offset,+ end_offset: table.record(RecordIndexInChunk(record_indices.end.0 - 1)).end_offset,+ reach,+ context,+ is_spread_by_no_filter: !is_spread_by_filters,+ device_aligned_fill: is_one_record+ .then(|| self.device_aligned_fill_of_record(chunk, table.record(record_indices.start), context))+ .flatten(),+ }+ }++ pub(super) fn device_aligned_fill_of_record(+ &self,+ chunk: &ListChunk,+ record: &ChunkRecord,+ context: ContextRef,+ ) -> Option<DeviceAlignedFill> {+ let (header, payload) = chunk.record_at(record.offset);+ if header.inline_clip_count != 0 || header.has_inline_transform {+ return None;+ }+ let mut hasher = ContentHasher::new();+ hasher.write_u32(header.command_type as u32);+ let color;+ let draws_recorded_color_with_source_over;+ let (rect, corner_radii, unfilled_inner_rect_of_ring) = match header.command_type {+ DisplayListCommandType::FillRect => {+ let fill = read_command::<FillRect>(payload);+ hasher.write_u32(fill.color.0);+ hasher.write_u32(fill.compositing_and_blending_operator as u32);+ hasher.write_u32(fill.background_color_animation_effect.0);+ color = fill.color;+ draws_recorded_color_with_source_over = fill.compositing_and_blending_operator+ == CompositingAndBlendingOperator::Normal+ && fill.background_color_animation_effect.is_none();+ (fill.rect, CornerRadii::default(), None)+ }+ DisplayListCommandType::FillRectWithRoundedCorners => {+ let fill = read_command::<FillRectWithRoundedCorners>(payload);+ hasher.write_u32(fill.color.0);+ hasher.write_u32(fill.background_color_animation_effect.0);+ color = fill.color;+ draws_recorded_color_with_source_over = fill.background_color_animation_effect.is_none();+ (fill.rect, fill.corner_radii, None)+ }+ DisplayListCommandType::FillRoundedRectRing => {+ let ring = read_command::<FillRoundedRectRing>(payload);+ hasher.write_u32(ring.color.0);+ color = ring.color;+ draws_recorded_color_with_source_over = true;+ let top_width = ring.top_width.clamp(0, ring.rect.height.max(0));+ let bottom_width = ring.bottom_width.clamp(0, (ring.rect.height - top_width).max(0));+ let left_width = ring.left_width.clamp(0, ring.rect.width.max(0));+ let right_width = ring.right_width.clamp(0, (ring.rect.width - left_width).max(0));+ for width in [top_width, right_width, bottom_width, left_width] {+ hasher.write_i32(width);+ }+ let (Some(unfilled_inner_x), Some(unfilled_inner_y)) =+ (ring.rect.x.checked_add(left_width), ring.rect.y.checked_add(top_width))+ else {+ return None;+ };+ let unfilled_inner_rect = IntRect::new(+ unfilled_inner_x,+ unfilled_inner_y,+ ring.rect.width - left_width - right_width,+ ring.rect.height - top_width - bottom_width,+ );+ (ring.rect, ring.corner_radii, Some(unfilled_inner_rect))+ }+ _ => return None,+ };+ let unfilled_inner_rect_of_ring = match unfilled_inner_rect_of_ring {+ Some(unfilled_inner_rect) => Some(RoundedRect::device_aligned_of(+ &self.geometry.world,+ context.spatial,+ unfilled_inner_rect.to_float(),+ &CornerRadii::default(),+ )?),+ None => None,+ };+ Some(DeviceAlignedFill {+ rect: RoundedRect::device_aligned_of(+ &self.geometry.world,+ context.spatial,+ rect.to_float(),+ &corner_radii,+ )?,+ unfilled_inner_rect_of_ring,+ content_hash_except_rects: hasher.finish(),+ color,+ draws_recorded_color_with_source_over,+ })+ }++ fn place_runs_of_chunk(+ &self,+ chunk: &ListChunk,+ run_indices: &[RunIndexInChunk],+ placement_inputs_hash: ContentHash,+ ) -> ChunkPlacedInRasterSpace {+ let table = chunk.record_table();+ let mut record_ranges = Vec::new();+ let mut ranges_of_each_run = vec![PlacedRecordRangesOfRun::default(); chunk.runs().len()];+ for &run_index in run_indices {+ let run = &chunk.runs()[run_index.0 as usize];+ let record_indices_of_run = table.record_indices_of_run(run_index);+ let run_reach = self.reach_of_content_within(run.ink_bounds.to_float(), run.context);+ let first_binned_range_index = PlacedRecordRangeIndex(record_ranges.len() as u32);+ let mut reach_of_binned_ranges = Reach::Nothing;+ if run_reach != Reach::Nothing {+ if !self.geometry.world.draw_matrix(run.context.spatial).is_2d_affine() {+ record_ranges.push(self.place_record_range(+ chunk,+ run_index,+ record_indices_of_run.clone(),+ run_reach,+ ));+ reach_of_binned_ranges = run_reach;+ } else {+ for record_index in+ (record_indices_of_run.start.0..record_indices_of_run.end.0).map(RecordIndexInChunk)+ {+ let record = table.record(record_index);+ if !record.draws_something {+ continue;+ }+ let record_reach = self.reach_of_content_within(record.bounding_rect.to_float(), run.context);+ if record_reach == Reach::Nothing {+ continue;+ }+ record_ranges.push(self.place_record_range(+ chunk,+ run_index,+ record_index..RecordIndexInChunk(record_index.0 + 1),+ record_reach,+ ));+ reach_of_binned_ranges = reach_of_binned_ranges.united(record_reach);+ }+ }+ }+ let whole_run_range_index = PlacedRecordRangeIndex(record_ranges.len() as u32);+ record_ranges.push(self.place_record_range(chunk, run_index, record_indices_of_run, run_reach));+ ranges_of_each_run[run_index.0 as usize] = PlacedRecordRangesOfRun {+ first_binned_range_index,+ whole_run_range_index,+ reach_of_binned_ranges,+ };+ }+ ChunkPlacedInRasterSpace {+ placement_inputs_hash,+ record_ranges,+ ranges_of_each_run,+ }+ }++ pub(super) fn placement_of_runs_of_chunk(+ &self,+ chunk_index: ChunkIndexInList,+ run_indices: &[RunIndexInChunk],+ ) -> Arc<ChunkPlacedInRasterSpace> {+ let chunk = self.list.display_list.chunk(chunk_index);+ let mut hasher = ContentHasher::new();+ for &run_index in run_indices {+ hasher.write_u32(run_index.0);+ hasher.write_content_hash(self.context_content_hash(+ chunk.runs()[run_index.0 as usize].context,+ EffectHashScope::WhatPlacingReads,+ ));+ }+ let placement_inputs_hash = hasher.finish();+ let (placement, newly_placed) = chunk.find_or_make_placement(placement_inputs_hash, || {+ self.place_runs_of_chunk(chunk, run_indices, placement_inputs_hash)+ });+ if newly_placed {+ self.chunks_placed.set(self.chunks_placed.get() + 1);+ }+ placement+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/tile_keys/coverage.rs b/Libraries/LibCompositing/Rust/src/display_list/tile_keys/coverage.rsnew file mode 100644index 00000000000..887adcfe705--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/tile_keys/coverage.rs@@ -0,0 +1,306 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Works out what a tile holds over a part of its cell from its records, without rastering it.++use super::{+ BandBoundToListAndGeometry, BandTileKeys, KeyedTile, TileKeyingOfList, TileKeyingOfRasterSpace, TileReplayItem,+};+use crate::display_list::commands::{ClipMode, ClipNodeIndex, ContextRef, EffectNodeIndex};+use crate::display_list::effect_geometry::nearest_effects_at_or_above_where;+use crate::display_list::window_server_placement::RoundedRect;+use crate::visual_context::{ClipData, ClipNode, ClipNodeData, EffectNodeData};+use libgfx_rust::{Color, CompositingAndBlendingOperator, FloatRect, IntRect};+use std::collections::HashSet;++/// What a tile holds over a part of its cell, as its records tell without rastering it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TileCoverage {+ /// Every pixel of one color, which a raster gives exactly: the clear color of its layer, or an opaque one.+ OneColor(Color),+ /// Every pixel opaque, of more than one color.+ Opaque,+ Unknown,+}++impl TileCoverage {+ pub fn is_opaque(self) -> bool {+ match self {+ TileCoverage::OneColor(color) => color.alpha() == 255,+ TileCoverage::Opaque => true,+ TileCoverage::Unknown => false,+ }+ }++ fn under_plain_fill_of(self, color: Color) -> Self {+ match color.alpha() {+ 255 => TileCoverage::OneColor(color),+ 0 => self,+ _ if self.is_opaque() => TileCoverage::Opaque,+ _ => TileCoverage::Unknown,+ }+ }++ fn under_content_other_than_plain_fill(self, content_can_lower_destination_alpha: bool) -> Self {+ if self.is_opaque() && !content_can_lower_destination_alpha {+ TileCoverage::Opaque+ } else {+ TileCoverage::Unknown+ }+ }+}++/// The clips, and the effects whose output clips, a walk for the coverage of a tile found to leave its area unclipped,+/// so that walks of chains that share nodes stop where they meet.+#[derive(Default)]+struct WhatLeavesAreaOfTileUnclipped {+ clips: HashSet<ClipNodeIndex>,+ effects: HashSet<EffectNodeIndex>,+}++enum WhatOneFillDoesWithinArea {+ DrawsNothing,+ CoversItWith(Color),+}++impl RoundedRect {+ fn covers(&self, area: FloatRect) -> bool {+ self.rect.contains_rect(area) && !self.rounded_corner_reaches_into(area)+ }++ fn misses(&self, area: FloatRect) -> bool {+ self.rect.intersected(area).is_empty()+ }+}++impl TileKeyingOfList<'_> {+ /// Whether the effects that tiles apply at and around `effect` are plain groups.+ fn effects_applied_in_tiles_are_plain_groups(&self, effect: EffectNodeIndex) -> bool {+ if effect.is_none() {+ return true;+ }+ let nearest = self+ .nearest_composited_or_not_plain_effect_by_effect_index+ .get_or_init(|| {+ nearest_effects_at_or_above_where(self.tree, |effect, node| {+ self.compositor_composites(effect)+ || !matches!(&node.data, EffectNodeData::Effects(effects)+ if effects.opacity == 1.0+ && effects.filter.is_none()+ && effects.backdrop_filter.is_none()+ && effects.blend_mode == CompositingAndBlendingOperator::Normal)+ })+ })[effect.0 as usize];+ nearest.is_none() || self.compositor_composites(nearest)+ }++ /// Whether an effect that tiles apply at or around `effect` blends in a way that can lower the alpha below it.+ fn effects_applied_in_tiles_can_lower_destination_alpha(&self, effect: EffectNodeIndex) -> bool {+ if effect.is_none() {+ return false;+ }+ let nearest = self+ .nearest_composited_or_alpha_lowering_effect_by_effect_index+ .get_or_init(|| {+ nearest_effects_at_or_above_where(self.tree, |effect, node| {+ self.compositor_composites(effect)+ || matches!(&node.data, EffectNodeData::Effects(effects)+ if effects.blend_mode.lowers_destination_alpha())+ })+ })[effect.0 as usize];+ !nearest.is_none() && !self.compositor_composites(nearest)+ }+}++impl TileKeyingOfRasterSpace<'_> {+ fn effect_chain_applied_in_tiles(&self, effect: EffectNodeIndex) -> impl Iterator<Item = EffectNodeIndex> {+ let tree = self.list.tree;+ std::iter::successors((!effect.is_none()).then_some(effect), move |effect| {+ Some(tree.effect_nodes[effect.0 as usize].parent).filter(|parent| !parent.is_none())+ })+ .take_while(|&effect| !self.list.compositor_composites(effect))+ }++ fn clip_node_leaves_area_unclipped(&self, node: &ClipNode, area_in_device_pixels: FloatRect) -> bool {+ let ClipNodeData::Rect(ClipData {+ rect,+ corner_radii,+ mode: ClipMode::Intersect,+ }) = &node.data+ else {+ return false;+ };+ !node.clips_everything+ && RoundedRect::device_aligned_of(&self.geometry.world, node.spatial, *rect, corner_radii)+ .is_some_and(|rect| rect.covers(area_in_device_pixels))+ }++ fn clip_chain_leaves_area_unclipped(+ &self,+ clip: ClipNodeIndex,+ area_in_device_pixels: FloatRect,+ known: &mut WhatLeavesAreaOfTileUnclipped,+ ) -> bool {+ let tree = self.list.tree;+ let mut clips_walked = Vec::new();+ let mut clip = clip;+ while !clip.is_none() && !known.clips.contains(&clip) {+ let node = &tree.clip_nodes[clip.0 as usize];+ if !self.geometry.clip_is_left_to_composite(clip)+ && !self.clip_node_leaves_area_unclipped(node, area_in_device_pixels)+ {+ return false;+ }+ clips_walked.push(clip);+ clip = node.parent;+ }+ known.clips.extend(clips_walked);+ true+ }++ fn output_clips_of_effects_applied_in_tiles_leave_area_unclipped(+ &self,+ effect: EffectNodeIndex,+ area_in_device_pixels: FloatRect,+ known: &mut WhatLeavesAreaOfTileUnclipped,+ ) -> bool {+ let mut effects_walked = Vec::new();+ for effect in self.effect_chain_applied_in_tiles(effect) {+ if known.effects.contains(&effect) {+ break;+ }+ if !self.clip_chain_leaves_area_unclipped(+ self.list.effect_clips.output_clip(effect),+ area_in_device_pixels,+ known,+ ) {+ return false;+ }+ effects_walked.push(effect);+ }+ known.effects.extend(effects_walked);+ true+ }++ fn context_applies_no_clip_or_effect_within(+ &self,+ context: ContextRef,+ area_in_device_pixels: FloatRect,+ known: &mut WhatLeavesAreaOfTileUnclipped,+ ) -> bool {+ let backface_culled = self+ .geometry+ .world+ .backface_culled+ .get(context.spatial.0 as usize)+ .copied()+ .unwrap_or(false);+ !backface_culled+ && self.list.effects_applied_in_tiles_are_plain_groups(context.effect)+ && self.clip_chain_leaves_area_unclipped(context.clip, area_in_device_pixels, known)+ && self.output_clips_of_effects_applied_in_tiles_leave_area_unclipped(+ context.effect,+ area_in_device_pixels,+ known,+ )+ }++ fn what_one_fill_item_does_within_area(+ &self,+ bound_band: &BandBoundToListAndGeometry,+ item: TileReplayItem,+ area_in_device_pixels: FloatRect,+ known: &mut WhatLeavesAreaOfTileUnclipped,+ ) -> Option<WhatOneFillDoesWithinArea> {+ let TileReplayItem::PlacedRecordRange {+ chunk_index,+ range_index,+ } = item+ else {+ return None;+ };+ let range = bound_band.placed_record_range(chunk_index, range_index);+ let fill = range.device_aligned_fill.as_ref()?;+ // The inner rect's corners curve only within the outer rect's corners.+ let area_is_inside_unfilled_inner_rect = fill.rect.covers(area_in_device_pixels)+ && fill+ .unfilled_inner_rect_of_ring+ .is_some_and(|unfilled_inner_rect| unfilled_inner_rect.covers(area_in_device_pixels));+ if (fill.rect.misses(area_in_device_pixels) || area_is_inside_unfilled_inner_rect)+ && range.is_spread_by_no_filter+ {+ return Some(WhatOneFillDoesWithinArea::DrawsNothing);+ }+ let fill_covers_area = fill.rect.covers(area_in_device_pixels)+ && fill+ .unfilled_inner_rect_of_ring+ .is_none_or(|unfilled_inner_rect| unfilled_inner_rect.misses(area_in_device_pixels));+ (fill_covers_area+ && fill.draws_recorded_color_with_source_over+ && self.context_applies_no_clip_or_effect_within(range.context, area_in_device_pixels, known))+ .then_some(WhatOneFillDoesWithinArea::CoversItWith(fill.color))+ }++ fn item_can_lower_destination_alpha(&self, bound_band: &BandBoundToListAndGeometry, item: TileReplayItem) -> bool {+ let chunk = self.list.display_list.chunk(item.chunk_index());+ self.records_of_item(bound_band, item).iter().any(|record| {+ let context = chunk.runs()[record.run_index.0 as usize].context;+ record.can_lower_destination_alpha+ || self+ .list+ .effects_applied_in_tiles_can_lower_destination_alpha(context.effect)+ })+ }++ /// What a raster of `tile` holds over `area` of its cell, in the device pixels of the space, as its replay items+ /// tell in paint order from `clear_color`, the color its layer's surface starts as.+ pub fn coverage_of_tile(+ &self,+ band_tile_keys: &BandTileKeys,+ tile: &KeyedTile,+ area: IntRect,+ clear_color: Color,+ ) -> TileCoverage {+ let bound_band = &band_tile_keys.bound_band;+ if self.list.replays_every_record_into_every_tile || area.is_empty() {+ return TileCoverage::Unknown;+ }+ // Fills are walked in list order, which depth-sorted planes are not replayed in.+ if self.list.tree_sorts_planes_by_depth+ && tile+ .replay_items_in_paint_order+ .iter()+ .any(|&item| self.root_of_context_sorting_item_by_depth(bound_band, item).is_some())+ {+ return TileCoverage::Unknown;+ }+ let area_in_device_pixels = area.to_float();+ let mut known_to_leave_area_unclipped = WhatLeavesAreaOfTileUnclipped::default();+ let mut coverage = TileCoverage::OneColor(clear_color);+ for &item in &tile.replay_items_in_paint_order {+ if matches!(item, TileReplayItem::PlacedRecordRange { .. })+ && bound_band.reach_of_item(item).part_of(area).is_empty()+ {+ continue;+ }+ coverage = match self.what_one_fill_item_does_within_area(+ bound_band,+ item,+ area_in_device_pixels,+ &mut known_to_leave_area_unclipped,+ ) {+ Some(WhatOneFillDoesWithinArea::DrawsNothing) => coverage,+ Some(WhatOneFillDoesWithinArea::CoversItWith(color)) => coverage.under_plain_fill_of(color),+ None => coverage+ .under_content_other_than_plain_fill(self.item_can_lower_destination_alpha(bound_band, item)),+ };+ if coverage == TileCoverage::Unknown {+ break;+ }+ }+ coverage+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/tiles.rs b/Libraries/LibCompositing/Rust/src/display_list/tiles.rsnew file mode 100644index 00000000000..b1532df1c6a--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/tiles.rs@@ -0,0 +1,355 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libgfx_rust::IntRect;+use std::cmp::Ordering;+use std::collections::BTreeMap;++pub const TILE_SIZE_IN_DEVICE_PIXELS: i32 = 512;+const MAXIMUM_CELLS_CONTENT_IS_FOLLOWED_INTO_ONE_BY_ONE: u64 = 4096;++/// A cell of the tile grid of a layer's raster space, which starts at the space's origin.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+#[repr(C)]+pub struct TileCoord {+ pub column: i32,+ pub row: i32,+}++impl TileCoord {+ pub const fn new(column: i32, row: i32) -> Self {+ Self { column, row }+ }++ /// The cell that holds the device pixel at `x` and `y`.+ pub const fn of_pixel(x: i32, y: i32) -> Self {+ Self::new(+ x.div_euclid(TILE_SIZE_IN_DEVICE_PIXELS),+ y.div_euclid(TILE_SIZE_IN_DEVICE_PIXELS),+ )+ }++ pub const fn cell_rect(self) -> IntRect {+ IntRect::new(+ self.column * TILE_SIZE_IN_DEVICE_PIXELS,+ self.row * TILE_SIZE_IN_DEVICE_PIXELS,+ TILE_SIZE_IN_DEVICE_PIXELS,+ TILE_SIZE_IN_DEVICE_PIXELS,+ )+ }+}++impl Ord for TileCoord {+ fn cmp(&self, other: &Self) -> Ordering {+ (self.row, self.column).cmp(&(other.row, other.column))+ }+}++impl PartialOrd for TileCoord {+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {+ Some(self.cmp(other))+ }+}++impl std::fmt::Display for TileCoord {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(formatter, "({},{})", self.column, self.row)+ }+}++/// The cells from a first to a last column and from a first to a last row. It holds no cell where a last column or row+/// comes before the first.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub struct CellRange {+ pub first_row: i32,+ pub last_row: i32,+ pub first_column: i32,+ pub last_column: i32,+}++impl Default for CellRange {+ fn default() -> Self {+ Self::NONE+ }+}++impl CellRange {+ pub const NONE: Self = Self {+ first_row: 0,+ last_row: -1,+ first_column: 0,+ last_column: -1,+ };++ /// The cells that `rect` reaches into.+ pub fn touched_by(rect: IntRect) -> Self {+ if rect.is_empty() {+ return Self::NONE;+ }+ let first = TileCoord::of_pixel(rect.x, rect.y);+ let last = TileCoord::of_pixel(rect.right() - 1, rect.bottom() - 1);+ Self {+ first_row: first.row,+ last_row: last.row,+ first_column: first.column,+ last_column: last.column,+ }+ }++ /// The cells at most `distance` columns and `distance` rows away from `center`.+ pub fn around(center: TileCoord, distance: i32) -> Self {+ Self {+ first_row: center.row.saturating_sub(distance),+ last_row: center.row.saturating_add(distance),+ first_column: center.column.saturating_sub(distance),+ last_column: center.column.saturating_add(distance),+ }+ }++ pub fn is_empty(self) -> bool {+ self.last_row < self.first_row || self.last_column < self.first_column+ }++ /// The rect its cells cover, which is empty where it holds no cell.+ pub fn rect(self) -> IntRect {+ if self.is_empty() {+ return IntRect::default();+ }+ TileCoord::new(self.first_column, self.first_row)+ .cell_rect()+ .united(TileCoord::new(self.last_column, self.last_row).cell_rect())+ }++ pub fn row_count(self) -> u64 {+ if self.is_empty() {+ return 0;+ }+ (i64::from(self.last_row) - i64::from(self.first_row) + 1) as u64+ }++ pub fn cell_count(self) -> u64 {+ if self.is_empty() {+ return 0;+ }+ self.row_count() * (i64::from(self.last_column) - i64::from(self.first_column) + 1) as u64+ }++ pub fn holds_every_cell_of(self, other: Self) -> bool {+ other.is_empty()+ || (self.first_row <= other.first_row+ && other.last_row <= self.last_row+ && self.first_column <= other.first_column+ && other.last_column <= self.last_column)+ }++ pub fn contains(self, coord: TileCoord) -> bool {+ (self.first_row..=self.last_row).contains(&coord.row)+ && (self.first_column..=self.last_column).contains(&coord.column)+ }++ pub fn contains_range(self, other: Self) -> bool {+ other.is_empty()+ || (self.first_row <= other.first_row+ && other.last_row <= self.last_row+ && self.first_column <= other.first_column+ && other.last_column <= self.last_column)+ }++ pub fn intersected(self, other: Self) -> Self {+ let intersection = Self {+ first_row: self.first_row.max(other.first_row),+ last_row: self.last_row.min(other.last_row),+ first_column: self.first_column.max(other.first_column),+ last_column: self.last_column.min(other.last_column),+ };+ if intersection.is_empty() {+ return Self::NONE;+ }+ intersection+ }++ /// Its cells, row by row.+ pub fn coords(self) -> impl Iterator<Item = TileCoord> {+ let columns = self.first_column..=self.last_column;+ (self.first_row..=self.last_row)+ .flat_map(move |row| columns.clone().map(move |column| TileCoord::new(column, row)))+ }+}++/// The cells that `rect` reaches into, row by row. A caller bounds `rect` first, since a rect far larger than the+/// viewport reaches into a great many cells; to find what a map holds within a rect of any size, it uses+/// `entries_within` or `for_each_entry_within`.+pub fn tile_coords_touching(rect: IntRect) -> impl Iterator<Item = TileCoord> {+ CellRange::touched_by(rect).coords()+}++/// Whether content within `rect` reaches too many cells to be followed into each of them, and is taken to reach every+/// cell it can instead.+pub fn reaches_too_many_cells_to_follow_one_by_one(rect: IntRect) -> bool {+ tile_count_touching(rect) > MAXIMUM_CELLS_CONTENT_IS_FOLLOWED_INTO_ONE_BY_ONE+}++/// How many cells `rect` reaches into.+pub fn tile_count_touching(rect: IntRect) -> u64 {+ CellRange::touched_by(rect).cell_count()+}++// A map is looked up row by row where the range has no more rows than the map has entries, and walked whole otherwise,+// so that a range of many more cells than the map holds costs no more than the map.+fn looks_up_rows_of_range<V>(cells: &BTreeMap<TileCoord, V>, range: CellRange) -> bool {+ range.row_count() <= cells.len() as u64+}++fn first_and_last_coord_of_row(range: CellRange, row: i32) -> std::ops::RangeInclusive<TileCoord> {+ TileCoord::new(range.first_column, row)..=TileCoord::new(range.last_column, row)+}++/// The entries of `cells` within `range`, row by row. It costs no more than the rows of `range` or the entries of+/// `cells`, whichever are fewer, and not the cells of `range`.+pub fn entries_within<V>(cells: &BTreeMap<TileCoord, V>, range: CellRange) -> impl Iterator<Item = (&TileCoord, &V)> {+ let looks_up_rows = looks_up_rows_of_range(cells, range);+ let rows_looked_up = (looks_up_rows && !range.is_empty()).then(|| {+ (range.first_row..=range.last_row).flat_map(move |row| cells.range(first_and_last_coord_of_row(range, row)))+ });+ let entries_walked = (!looks_up_rows).then(|| cells.iter().filter(move |(coord, _)| range.contains(**coord)));+ rows_looked_up+ .into_iter()+ .flatten()+ .chain(entries_walked.into_iter().flatten())+}++/// Visits the entries of `cells` within `range`, row by row, at the cost `entries_within` has.+pub fn for_each_entry_within<V>(+ cells: &mut BTreeMap<TileCoord, V>,+ range: CellRange,+ mut visit: impl FnMut(TileCoord, &mut V),+) {+ if range.is_empty() {+ return;+ }+ if !looks_up_rows_of_range(cells, range) {+ for (coord, value) in cells.iter_mut().filter(|(coord, _)| range.contains(**coord)) {+ visit(*coord, value);+ }+ return;+ }+ for row in range.first_row..=range.last_row {+ for (coord, value) in cells.range_mut(first_and_last_coord_of_row(range, row)) {+ visit(*coord, value);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_rect_touches_the_cells_it_reaches_into_row_by_row() {+ let coords: Vec<TileCoord> = tile_coords_touching(IntRect::new(+ TILE_SIZE_IN_DEVICE_PIXELS - 6,+ 10,+ TILE_SIZE_IN_DEVICE_PIXELS + 44,+ TILE_SIZE_IN_DEVICE_PIXELS - 6,+ ))+ .collect();+ assert_eq!(+ coords,+ [+ TileCoord::new(0, 0),+ TileCoord::new(1, 0),+ TileCoord::new(2, 0),+ TileCoord::new(0, 1),+ TileCoord::new(1, 1),+ TileCoord::new(2, 1),+ ]+ );+ }++ #[test]+ fn a_rect_ending_on_a_cell_edge_does_not_touch_the_next_cell() {+ let coords: Vec<TileCoord> = tile_coords_touching(IntRect::new(+ 0,+ 0,+ TILE_SIZE_IN_DEVICE_PIXELS,+ 2 * TILE_SIZE_IN_DEVICE_PIXELS,+ ))+ .collect();+ assert_eq!(coords, [TileCoord::new(0, 0), TileCoord::new(0, 1)]);+ }++ #[test]+ fn cells_left_of_and_above_the_origin_have_negative_coords() {+ let coords: Vec<TileCoord> =+ tile_coords_touching(IntRect::new(-1, -TILE_SIZE_IN_DEVICE_PIXELS - 1, 2, 1)).collect();+ assert_eq!(coords, [TileCoord::new(-1, -2), TileCoord::new(0, -2)]);+ }++ #[test]+ fn an_empty_rect_touches_no_cell() {+ assert_eq!(tile_coords_touching(IntRect::new(10, 10, 0, 20)).count(), 0);+ assert!(CellRange::touched_by(IntRect::new(10, 10, 0, 20)).is_empty());+ assert_eq!(CellRange::default(), CellRange::NONE);+ }++ #[test]+ fn the_entries_within_a_range_are_alike_whether_rows_are_looked_up_or_every_entry_is_walked() {+ let held: BTreeMap<TileCoord, u32> = [(-3, -2), (0, 0), (1, 0), (5, 0), (0, 1), (2, 7), (9, 9)]+ .into_iter()+ .enumerate()+ .map(|(index, (column, row))| (TileCoord::new(column, row), index as u32))+ .collect();+ let ranges = [+ CellRange::touched_by(IntRect::new(+ 0,+ 0,+ 2 * TILE_SIZE_IN_DEVICE_PIXELS,+ 2 * TILE_SIZE_IN_DEVICE_PIXELS,+ )),+ CellRange::around(TileCoord::new(0, 0), 3),+ CellRange::around(TileCoord::new(4, 4), 1 << 20),+ CellRange::touched_by(IntRect::new(-(1 << 28), -(1 << 28), 1 << 29, 1 << 29)),+ CellRange::NONE,+ ];+ for range in ranges {+ let expected: Vec<(TileCoord, u32)> = held+ .iter()+ .filter(|(coord, _)| range.contains(**coord))+ .map(|(coord, value)| (*coord, *value))+ .collect();+ let found: Vec<(TileCoord, u32)> = entries_within(&held, range)+ .map(|(coord, value)| (*coord, *value))+ .collect();+ assert_eq!(found, expected);+ let mut visited = Vec::new();+ for_each_entry_within(&mut held.clone(), range, |coord, value| visited.push((coord, *value)));+ assert_eq!(visited, expected);+ }+ }++ #[test]+ fn a_window_around_a_cell_holds_the_cells_at_most_its_distance_away() {+ let window = CellRange::around(TileCoord::new(10, -4), 2);+ assert_eq!(window.cell_count(), 25);+ assert!(window.contains(TileCoord::new(8, -6)) && window.contains(TileCoord::new(12, -2)));+ assert!(!window.contains(TileCoord::new(13, -4)));+ assert!(window.contains_range(CellRange::around(TileCoord::new(11, -3), 1)));+ assert!(!window.contains_range(CellRange::around(TileCoord::new(12, -4), 1)));+ assert_eq!(+ window.intersected(CellRange::around(TileCoord::new(13, -4), 1)),+ CellRange::touched_by(IntRect::new(+ 12 * TILE_SIZE_IN_DEVICE_PIXELS,+ -5 * TILE_SIZE_IN_DEVICE_PIXELS,+ TILE_SIZE_IN_DEVICE_PIXELS,+ 3 * TILE_SIZE_IN_DEVICE_PIXELS+ ))+ );+ assert_eq!(+ window.intersected(CellRange::around(TileCoord::new(20, 0), 1)),+ CellRange::NONE+ );+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/validate.rs b/Libraries/LibCompositing/Rust/src/display_list/validate.rsindex 32b2b8264c3..4277b217fb3 100644--- a/Libraries/LibCompositing/Rust/src/display_list/validate.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/validate.rs@@ -639,6 +639,7 @@ impl RunSummary {#[derive(Clone, Copy, PartialEq, Eq)]enum TapeKind {DisplayList,+ RecordsNestedInDisplayListRecord,Canvas2D,}@@ -654,10 +655,19 @@ fn validate_header_bytes(bytes: &[u8], kind: TapeKind) -> Result<DisplayListComm}let header = read_header(bytes);match kind {- TapeKind::DisplayList => {+ TapeKind::DisplayList | TapeKind::RecordsNestedInDisplayListRecord => {if header.command_type.is_canvas_2d() {return Err("Display list holds a command of the canvas 2D stream");}+ // Tile keys and caret blinks find carets and scroll bars only among top-level records.+ if kind == TapeKind::RecordsNestedInDisplayListRecord+ && matches!(+ header.command_type,+ DisplayListCommandType::PaintCaret | DisplayListCommandType::PaintScrollBar+ )+ {+ return Err("Display list holds a caret or scroll bar inside another record");+ }}TapeKind::Canvas2D => {if !header.command_type.is_canvas_2d() {@@ -788,7 +798,7 @@ pub fn validate_tape(tape: &[u8], run_bytes: &[u8]) -> Result<Vec<DisplayListComSome(&mut summary),)?;while let Some(records) = pending.pop() {- validate_records(records, TapeKind::DisplayList, &mut pending, None)?;+ validate_records(records, TapeKind::RecordsNestedInDisplayListRecord, &mut pending, None)?;}if !summary.matches(&run) {return Err("Display list command run summary disagrees with its records");@@ -824,7 +834,7 @@ pub fn validate_canvas_2d_tape(tape: &[u8]) -> Result<(), ValidationError> {mod tests {use super::*;use crate::display_list::builder::DisplayListBuilder;- use crate::display_list::storage::write_run;+ use crate::display_list::storage::write_run_with_zeroed_padding;fn fill_rect() -> FillRect {FillRect {@@ -838,11 +848,58 @@ mod tests {fn run_table_bytes(runs: &[DisplayListCommandRun]) -> Vec<u8> {let mut bytes = vec![0; runs.len() * RUN_SIZE];for (run, out) in runs.iter().zip(bytes.chunks_exact_mut(RUN_SIZE)) {- write_run(run, out);+ write_run_with_zeroed_padding(run, out);}bytes}+ // A list from another process can hold records whose rects, clips and shadows reach past where coordinates fit.+ #[test]+ fn records_reaching_past_where_coordinates_fit_validate_with_bounds_whose_edges_fit() {+ use crate::display_list::builder::PendingInlineClip;+ use crate::display_list::commands::PaintOuterBoxShadow;+ use libgfx_rust::{CornerRadii, FloatRect};+ let mut builder = DisplayListBuilder::new();+ let fill_past_the_right_edge = FillRect {+ rect: IntRect::new(2_147_483_000, 0, 1000, 10),+ ..fill_rect()+ };+ builder.append(&fill_past_the_right_edge, &[], ContextRef::default());+ builder.append(&fill_past_the_right_edge, &[], ContextRef::default());+ builder.append_with_inline_clips(+ &fill_rect(),+ &[],+ ContextRef::default(),+ &[PendingInlineClip::intersecting_float_rect(FloatRect::new(+ 2.0e9, 0.0, 2.0e8, 10.0,+ ))],+ );+ builder.append(+ &PaintOuterBoxShadow {+ color: Color::default(),+ blur_radius: i32::MAX,+ device_content_rect: IntRect::new(0, 0, 10, 10),+ content_corner_radii: CornerRadii::default(),+ shadow_rect: IntRect::new(0, 0, 10, 10),+ shadow_corner_radii: CornerRadii::default(),+ },+ &[],+ ContextRef::default(),+ );+ let recorded = builder.finish();+ assert!(validate_tape(&recorded.bytes, &run_table_bytes(&recorded.command_runs)).is_ok());+ let edge_fits = |near: i32, length: i32| i32::try_from(i64::from(near) + i64::from(length)).is_ok();+ assert!(recorded.command_runs.iter().all(|run| {+ edge_fits(run.ink_bounds.x, run.ink_bounds.width) && edge_fits(run.ink_bounds.y, run.ink_bounds.height)+ }));+ // The blur of the shadow reaches as far as bounds do.+ assert!(+ recorded.command_runs[0]+ .ink_bounds+ .contains_rect(IntRect::new(0, 0, 10, 10))+ );+ }+#[test]fn run_ink_bounds_are_checked_against_the_payloads_of_their_records() {let mut builder = DisplayListBuilder::new();@@ -865,4 +922,75 @@ mod tests {}];assert!(validate_tape(&widened_tape, &run_table_bytes(&widened_runs)).is_ok());}++ #[test]+ fn a_caret_or_scroll_bar_is_refused_inside_another_record() {+ let caret = PaintCaret {+ rect: IntRect::new(0, 0, 1, 10),+ color: Color::default(),+ blink_cycle_start_time_ns: 0,+ should_blink: true,+ };+ let scroll_bar = PaintScrollBar {+ scroll_node_index: SpatialNodeIndex(1),+ gutter_rect: IntRect::new(90, 0, 10, 100),+ thumb_rect: IntRect::new(90, 0, 10, 20),+ track_rect: IntRect::new(90, 0, 10, 100),+ expanded_gutter_rect: IntRect::new(86, 0, 14, 100),+ scroll_size: 0.5,+ thumb_color: Color::default(),+ thumb_outline_color: Color::default(),+ track_color: Color::default(),+ vertical: true,+ };+ let validate = |builder: DisplayListBuilder| {+ let recorded = builder.finish();+ validate_tape(&recorded.bytes, &run_table_bytes(&recorded.command_runs))+ };++ let mut top_level = DisplayListBuilder::new();+ top_level.append(&caret, &[], ContextRef::default());+ top_level.append(&scroll_bar, &[], ContextRef::default());+ assert!(validate(top_level).is_ok());++ let mut caret_in_group = DisplayListBuilder::new();+ let group = caret_in_group.begin_group::<DrawIsolatedGroup>(Vec::new());+ caret_in_group.append(&caret, &[], ContextRef::default());+ let content = caret_in_group.group_content_span(&group);+ caret_in_group.finish_group(+ group,+ &DrawIsolatedGroup {+ clip_rect: IntRect::new(0, 0, 10, 10).to_float(),+ content,+ mask: DisplayListDataSpan::default(),+ filter: DisplayListDataSpan::default(),+ opacity: 1.0,+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ mask_kind: MaskKind::Alpha,+ },+ ContextRef::default(),+ );+ assert_eq!(+ validate(caret_in_group),+ Err("Display list holds a caret or scroll bar inside another record")+ );++ let mut scroll_bar_in_mask_content = DisplayListBuilder::new();+ let declaration = scroll_bar_in_mask_content.begin_group::<DeclareMaskContent>(Vec::new());+ scroll_bar_in_mask_content.append(&scroll_bar, &[], ContextRef::default());+ let content = scroll_bar_in_mask_content.group_content_span(&declaration);+ scroll_bar_in_mask_content.finish_group(+ declaration,+ &DeclareMaskContent {+ rect: IntRect::new(0, 0, 100, 100),+ effect: EffectNodeIndex(1),+ content,+ },+ ContextRef::default(),+ );+ assert_eq!(+ validate(scroll_bar_in_mask_content),+ Err("Display list holds a caret or scroll bar inside another record")+ );+ }}diff --git a/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs b/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rsindex 45c0915b216..8c6a2dc7b2f 100644--- a/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Where the window server can show a canvas or a video that a layer plan draws by itself. The window server places+//! Where the window server can show by itself a canvas or a video that is a layer of its own. The window server places//! an image with a 2D affine transform and clips it to rectangles, one of which can have rounded corners of a single//! radius. A media layer drawn under any other clip has to be replayed instead.@@ -49,22 +49,26 @@ impl RoundedCorners {}#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum WindowServerRejection {+pub enum WhyWindowServerCannotShowMedia {ClippedByPath,ClippedByExcludingClip,ClippedInRotatedOrSkewedSpace,+ ClippedInSpaceTreeDoesNotHave,RoundedCornersOfDifferingRadii,MoreThanOneRoundedClip,}-impl std::fmt::Display for WindowServerRejection {+impl std::fmt::Display for WhyWindowServerCannotShowMedia {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter.write_str(match self {- WindowServerRejection::ClippedByPath => "clipped by a path",- WindowServerRejection::ClippedByExcludingClip => "clipped by an excluding clip",- WindowServerRejection::ClippedInRotatedOrSkewedSpace => "clipped in a rotated or skewed space",- WindowServerRejection::RoundedCornersOfDifferingRadii => "rounded corners of differing radii",- WindowServerRejection::MoreThanOneRoundedClip => "more than one rounded clip",+ WhyWindowServerCannotShowMedia::ClippedByPath => "clipped by a path",+ WhyWindowServerCannotShowMedia::ClippedByExcludingClip => "clipped by an excluding clip",+ WhyWindowServerCannotShowMedia::ClippedInRotatedOrSkewedSpace => "clipped in a rotated or skewed space",+ WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave => {+ "clipped in a space the tree does not have"+ }+ WhyWindowServerCannotShowMedia::RoundedCornersOfDifferingRadii => "rounded corners of differing radii",+ WhyWindowServerCannotShowMedia::MoreThanOneRoundedClip => "more than one rounded clip",})}}@@ -109,16 +113,19 @@ fn write_float_rect(formatter: &mut std::fmt::Formatter<'_>, name: &str, rect: F)}-// A rounded clip in viewport pixels, with the radii of its corners in the order of `CornerRadii`.-struct RoundedClipInViewport {- rect: FloatRect,- radii: [(f32, f32); 4],+/// A rect whose corners can be rounded, with the horizontal and the vertical radius of each corner.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct RoundedRect {+ pub(crate) rect: FloatRect,+ pub(crate) horizontal_and_vertical_radii_clockwise_from_top_left: [(f32, f32); 4],}-impl RoundedClipInViewport {+impl RoundedRect {+ /// The boxes that the rounded corners curve within, empty for a corner that is not rounded.fn corner_boxes(&self) -> [FloatRect; 4] {let rect = self.rect;- let [top_left, top_right, bottom_right, bottom_left] = self.radii;+ let [top_left, top_right, bottom_right, bottom_left] =+ self.horizontal_and_vertical_radii_clockwise_from_top_left;[FloatRect::new(rect.x, rect.y, top_left.0, top_left.1),FloatRect::new(rect.right() - top_right.0, rect.y, top_right.0, top_right.1),@@ -132,36 +139,44 @@ impl RoundedClipInViewport {]}- fn with_single_radius(&self) -> Result<RoundedClip, WindowServerRejection> {- let mut radius = None;- let mut rounded = [false; 4];- for (index, &(horizontal, vertical)) in self.radii.iter().enumerate() {+ pub(crate) fn rounded_corner_reaches_into(&self, area: FloatRect) -> bool {+ self.corner_boxes()+ .iter()+ .any(|corner_box| !corner_box.is_empty() && !corner_box.intersected(area).is_empty())+ }++ fn with_single_radius(&self) -> Result<RoundedClip, WhyWindowServerCannotShowMedia> {+ let mut single_radius = None;+ let mut corner_is_rounded = [false; 4];+ for (corner_index, &(horizontal, vertical)) in self+ .horizontal_and_vertical_radii_clockwise_from_top_left+ .iter()+ .enumerate()+ {if horizontal <= 0.0 || vertical <= 0.0 {continue;}- let corner_radius = *radius.get_or_insert(horizontal);- if (horizontal - corner_radius).abs() > RADIUS_TOLERANCE_IN_DEVICE_PIXELS- || (vertical - corner_radius).abs() > RADIUS_TOLERANCE_IN_DEVICE_PIXELS+ let radius_of_first_rounded_corner = *single_radius.get_or_insert(horizontal);+ if (horizontal - radius_of_first_rounded_corner).abs() > RADIUS_TOLERANCE_IN_DEVICE_PIXELS+ || (vertical - radius_of_first_rounded_corner).abs() > RADIUS_TOLERANCE_IN_DEVICE_PIXELS{- return Err(WindowServerRejection::RoundedCornersOfDifferingRadii);+ return Err(WhyWindowServerCannotShowMedia::RoundedCornersOfDifferingRadii);}- rounded[index] = true;+ corner_is_rounded[corner_index] = true;}Ok(RoundedClip {rect: self.rect,- radius: radius.unwrap_or(0.0),+ radius: single_radius.unwrap_or(0.0),rounded_corners: RoundedCorners {- top_left: rounded[0],- top_right: rounded[1],- bottom_right: rounded[2],- bottom_left: rounded[3],+ top_left: corner_is_rounded[0],+ top_right: corner_is_rounded[1],+ bottom_right: corner_is_rounded[2],+ bottom_left: corner_is_rounded[3],},})}}-// Whether a clip in the space of the content leaves all of it visible, as the clip of a video to its box does when-// the video fills the box. Such a clip needs no layer of its own, even where the space is rotated.fn clip_leaves_content_whole(rect: FloatRect,corner_radii: CornerRadii,@@ -171,39 +186,28 @@ fn clip_leaves_content_whole(if mode != ClipMode::Intersect || !rect.contains_rect(content_rect) {return false;}- let corner_box = |x: f32, y: f32, corner: CornerRadius| {+ let radii = |corner: CornerRadius| {if !corner.is_present() {- return FloatRect::default();+ return (0.0, 0.0);}- FloatRect::new(x, y, corner.horizontal_radius as f32, corner.vertical_radius as f32)+ (corner.horizontal_radius as f32, corner.vertical_radius as f32)};- let boxes = [- corner_box(rect.x, rect.y, corner_radii.top_left),- corner_box(- rect.right() - corner_radii.top_right.horizontal_radius as f32,- rect.y,- corner_radii.top_right,- ),- corner_box(- rect.right() - corner_radii.bottom_right.horizontal_radius as f32,- rect.bottom() - corner_radii.bottom_right.vertical_radius as f32,- corner_radii.bottom_right,- ),- corner_box(- rect.x,- rect.bottom() - corner_radii.bottom_left.vertical_radius as f32,- corner_radii.bottom_left,- ),- ];- boxes- .iter()- .all(|corner_box| corner_box.is_empty() || corner_box.intersected(content_rect).is_empty())+ let rounded_rect = RoundedRect {+ rect,+ horizontal_and_vertical_radii_clockwise_from_top_left: [+ radii(corner_radii.top_left),+ radii(corner_radii.top_right),+ radii(corner_radii.bottom_right),+ radii(corner_radii.bottom_left),+ ],+ };+ !rounded_rect.rounded_corner_reaches_into(content_rect)}#[derive(Default)]struct ClipsInViewport {rect_clips: Vec<FloatRect>,- rounded_clips: Vec<RoundedClipInViewport>,+ rounded_clips: Vec<RoundedRect>,}impl ClipsInViewport {@@ -214,22 +218,24 @@ impl ClipsInViewport {rect: FloatRect,corner_radii: CornerRadii,mode: ClipMode,- ) -> Result<(), WindowServerRejection> {+ ) -> Result<(), WhyWindowServerCannotShowMedia> {if mode == ClipMode::Difference {- return Err(WindowServerRejection::ClippedByExcludingClip);+ return Err(WhyWindowServerCannotShowMedia::ClippedByExcludingClip);}- let matrix = world.draw_matrix(space);+ let matrix = world+ .draw_matrix_if_known(space)+ .ok_or(WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave)?;let elements = &matrix.elements;if !matrix.is_2d_affine() || elements[0][1] != 0.0 || elements[1][0] != 0.0 {- return Err(WindowServerRejection::ClippedInRotatedOrSkewedSpace);+ return Err(WhyWindowServerCannotShowMedia::ClippedInRotatedOrSkewedSpace);}- let viewport_rect = matrix.extract_2d_affine().map_rect(rect);+ let rect_in_viewport = matrix.extract_2d_affine().map_rect(rect);if !corner_radii.has_any_radius() {- self.rect_clips.push(viewport_rect);+ self.rect_clips.push(rect_in_viewport);return Ok(());}let (scale_x, scale_y) = (elements[0][0], elements[1][1]);- let scaled = |corner: CornerRadius| {+ let radii_scaled_into_viewport = |corner: CornerRadius| {if !corner.is_present() {return (0.0, 0.0);}@@ -239,21 +245,22 @@ impl ClipsInViewport {)};let mut radii = [- scaled(corner_radii.top_left),- scaled(corner_radii.top_right),- scaled(corner_radii.bottom_right),- scaled(corner_radii.bottom_left),+ radii_scaled_into_viewport(corner_radii.top_left),+ radii_scaled_into_viewport(corner_radii.top_right),+ radii_scaled_into_viewport(corner_radii.bottom_right),+ radii_scaled_into_viewport(corner_radii.bottom_left),];- // A mirrored space swaps the corners that each radius lands on.- if scale_x < 0.0 {+ let mirrors_left_and_right = scale_x < 0.0;+ if mirrors_left_and_right {radii = [radii[1], radii[0], radii[3], radii[2]];}- if scale_y < 0.0 {+ let mirrors_top_and_bottom = scale_y < 0.0;+ if mirrors_top_and_bottom {radii = [radii[3], radii[2], radii[1], radii[0]];}- self.rounded_clips.push(RoundedClipInViewport {- rect: viewport_rect,- radii,+ self.rounded_clips.push(RoundedRect {+ rect: rect_in_viewport,+ horizontal_and_vertical_radii_clockwise_from_top_left: radii,});Ok(())}@@ -268,7 +275,7 @@ pub fn window_server_placement(run: &DisplayListCommandRun,header: &DisplayListCommandHeader,payload: &[u8],-) -> Result<WindowServerPlacement, WindowServerRejection> {+) -> Result<WindowServerPlacement, WhyWindowServerCannotShowMedia> {let (content_rect, scaling_mode) = match header.command_type {DisplayListCommandType::DrawCanvas => {let command = read_command::<DrawCanvas>(payload);@@ -281,7 +288,6 @@ pub fn window_server_placement(_ => unreachable!("the window server shows only canvases and videos"),};let mut content_to_viewport = world.draw_matrix(run.context.spatial).extract_2d_affine();- // Clips in the space of the record apply before its inline transform moves the content.let mut content_bounds_in_record_space = content_rect.to_float();if let Some(inline_transform) = inline_transform_of(header, payload) {content_to_viewport = multiply_affine(content_to_viewport, inline_transform);@@ -291,14 +297,14 @@ pub fn window_server_placement(let mut clips = ClipsInViewport::default();for clip in inline_clips_of(header, payload) {if clip.kind == InlineClipKind::Path {- return Err(WindowServerRejection::ClippedByPath);+ return Err(WhyWindowServerCannotShowMedia::ClippedByPath);}- let space = if clip.has_own_space {+ let clip_space = if clip.has_own_space {clip.space} else {run.context.spatial};- if space == run.context.spatial+ if clip_space == run.context.spatial&& clip_leaves_content_whole(clip.clip_rect_or_path_device_bounds,clip.corner_radii,@@ -310,7 +316,7 @@ pub fn window_server_placement(}clips.add(world,- space,+ clip_space,clip.clip_rect_or_path_device_bounds,clip.corner_radii,clip.mode,@@ -329,7 +335,7 @@ pub fn window_server_placement(content_bounds_in_record_space,) => {}ClipNodeData::Rect(data) => clips.add(world, node.spatial, data.rect, data.corner_radii, data.mode)?,- ClipNodeData::Path(_) => return Err(WindowServerRejection::ClippedByPath),+ ClipNodeData::Path(_) => return Err(WhyWindowServerCannotShowMedia::ClippedByPath),ClipNodeData::Dead => {}}clip = node.parent;@@ -343,21 +349,16 @@ pub fn window_server_placement({clip_rect = clip_rect.intersected(*rect);}- // A rounded clip whose corners all miss the visible part of the content clips it as its rectangle does.let visible_content = content_to_viewport.map_rect(content_rect.to_float()).intersected(clip_rect);let mut rounded_clip = None;for rounded_clip_in_viewport in &clips.rounded_clips {- let corners_cut_the_content = rounded_clip_in_viewport- .corner_boxes()- .iter()- .any(|corner_box| !corner_box.is_empty() && !corner_box.intersected(visible_content).is_empty());- if !corners_cut_the_content {+ if !rounded_clip_in_viewport.rounded_corner_reaches_into(visible_content) {continue;}if rounded_clip.is_some() {- return Err(WindowServerRejection::MoreThanOneRoundedClip);+ return Err(WhyWindowServerCannotShowMedia::MoreThanOneRoundedClip);}rounded_clip = Some(rounded_clip_in_viewport.with_single_radius()?);}@@ -370,3 +371,37 @@ pub fn window_server_placement(scaling_mode,})}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::builder::{DisplayListBuilder, PendingInlineClip};+ use crate::display_list::storage::DisplayListStorage;+ use crate::display_list::test_fixtures::{VIEWPORT, canvas, tree_with_root_isolation_effect};+ use libgfx_rust::FloatMatrix4x4;++ // A list from another process can give an inline clip any space.+ #[test]+ fn a_canvas_clipped_in_a_space_the_tree_does_not_have_is_not_shown_by_the_window_server() {+ let (tree, root) = tree_with_root_isolation_effect(1.0);+ let mut builder = DisplayListBuilder::new();+ builder.append_with_inline_clips(+ &canvas(IntRect::new(10, 10, 100, 100), 1),+ &[],+ root,+ &[+ PendingInlineClip::intersecting_float_rect(FloatRect::new(0.0, 0.0, 50.0, 50.0))+ .in_space(SpatialNodeIndex(0xFFFF_FFF0)),+ ],+ );+ let list = DisplayListStorage::of_builder(&builder);+ let canvas_position = list.whole_span().begin;+ let run = &list.chunk(canvas_position.chunk_index).runs()[0];+ let (header, payload) = list.record_at(canvas_position);+ let world = WorldTransforms::new(&tree, &[], Some(FloatMatrix4x4::identity()));+ assert_eq!(+ window_server_placement(&tree, &world, VIEWPORT, run, &header, payload),+ Err(WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave)+ );+ }+}diff --git a/Libraries/LibCompositing/Rust/src/filter_bytes.rs b/Libraries/LibCompositing/Rust/src/filter_bytes.rsindex 6658681fdd8..68394f88c10 100644--- a/Libraries/LibCompositing/Rust/src/filter_bytes.rs+++ b/Libraries/LibCompositing/Rust/src/filter_bytes.rs@@ -75,6 +75,12 @@ pub fn output_bounds(bytes: &[u8], source: FloatRect) -> Option<FloatRect> {Filter::serialized_output_bounds(bytes, source)}+/// Whether a serialized filter can show what it is applied to away from where that is drawn, rather+/// than only over it and around it.+pub fn may_move_what_it_filters(bytes: &[u8]) -> bool {+ Filter::serialized_may_move_its_source(bytes)+}+/// Where a serialized filter's output can change when what it is applied to changes only within/// `changed_source`, or `None` when it can change everywhere.pub fn changed_output_bounds(bytes: &[u8], changed_source: FloatRect) -> Option<FloatRect> {diff --git a/Libraries/LibCompositing/Rust/src/host/replay.rs b/Libraries/LibCompositing/Rust/src/host/replay.rsindex fb705c14e55..06d1e41fb0e 100644--- a/Libraries/LibCompositing/Rust/src/host/replay.rs+++ b/Libraries/LibCompositing/Rust/src/host/replay.rs@@ -5,7 +5,7 @@*/use crate::display_list::commands::{ClipMode, DisplayListCommandType, ReplayClip, ReplayLayer, ReplayMask};-use crate::display_list::replay::{ReplayPainter, ReplaySelection};+use crate::display_list::replay::ReplayPainter;use libgfx_rust::path::Path;use libgfx_rust::path::ffi::PathGeometryData;use libgfx_rust::{@@ -14,39 +14,6 @@ use libgfx_rust::{};use std::ffi::c_void;-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-#[repr(C)]-pub struct RecordSpan {- pub begin_offset: u32,- pub end_offset: u32,-}--#[derive(Clone, Copy)]-#[repr(C)]-pub struct FfiReplaySelection {- pub record_spans: *const RecordSpan,- pub record_span_count: usize,- pub replays_only_record_spans: bool,- pub skip_root_isolation_layer: bool,-}--impl FfiReplaySelection {- /// # Safety- ///- /// When the selection replays only record spans, `record_spans` must point at `record_span_count` spans that stay- /// live for the returned lifetime.- pub unsafe fn as_selection<'a>(&self) -> ReplaySelection<'a> {- ReplaySelection {- // SAFETY: The caller guarantees the spans are live.- record_spans: self- .replays_only_record_spans- .then(|| unsafe { ak::slice_from_raw_parts(self.record_spans, self.record_span_count) }),- skip_root_isolation_layer: self.skip_root_isolation_layer,- allows_lcd_text: false,- }- }-}-/// A rect fill whose color the replay resolved for the frame.#[derive(Clone, Copy, Debug, PartialEq)]#[repr(C)]@@ -101,6 +68,19 @@ pub struct CompositedContextDraw {pub scaling_mode: ScalingMode,}+/// Pixels of a surface of the compositor, such as a tile of a layer, drawn without resampling where the two rects have+/// one size and the painter's matrix only translates by whole pixels: those of `source_rect`, over `target_rect`.+/// Drawn `filtered`, they are sampled bilinearly, as a tile of a layer that the frame composites through a transform+/// is, never past `source_rect` and without antialiasing its edges, so that tiles meet without seams.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct SurfaceDraw {+ pub surface: *mut c_void,+ pub source_rect: IntRect,+ pub target_rect: IntRect,+ pub filtered: bool,+}+/// A group of records that is composited as one: inside `clip_rect`, with the opacity, the blend mode and the filter.#[derive(Clone, Copy, Debug)]#[repr(C)]@@ -184,6 +164,7 @@ pub struct FfiRasterPainter {/// the image is skipped, the replay of its records is followed by `end_vector_image`.pub begin_vector_image: unsafe extern "C" fn(*mut c_void, *const VectorImagePlacement, bool) -> VectorImageReplay,pub end_vector_image: unsafe extern "C" fn(*mut c_void),+ pub draw_surface: unsafe extern "C" fn(*mut c_void, *const SurfaceDraw),}impl ReplayPainter for FfiRasterPainter {@@ -331,4 +312,9 @@ impl ReplayPainter for FfiRasterPainter {// SAFETY: The C++ painter finishes the image synchronously.unsafe { (self.end_vector_image)(self.context) };}++ fn draw_surface(&mut self, draw: &SurfaceDraw) {+ // SAFETY: The caller keeps the surface alive, and the C++ painter draws it synchronously.+ unsafe { (self.draw_surface)(self.context, draw) };+ }}diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex c8da76fbe6e..a90f03ef65f 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -13,6 +13,7 @@use crate::css_pixels::CssPixelPoint;use crate::display_list::chunks::ChunkId;use crate::display_list::commands::{CompositorContextId, UniqueNodeId};+use crate::display_list::layers::{LayerPlan, UnvalidatedLayerPlan};use crate::display_list::storage::PackedChunkSize;use crate::visual_context::VisualContextTree;use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, File};@@ -30,6 +31,7 @@ pub type Gfx_Color = libgfx_rust::Color;pub type Compositing_VisualContextTree = Arc<VisualContextTree>;pub type Compositing_ScrollStateSnapshot = crate::scrolling::ScrollStateSnapshot;pub type Compositing_DisplayList = SharedDisplayList;+pub type Compositing_LayerPlan = LayerPlanOnWire;#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode)]pub struct Web_DevicePixelPoint {@@ -106,6 +108,44 @@ pub struct SharedDisplayList {pub async_scrolling_metadata: Option<Compositing_AsyncScrollingMetadata>,}+/// `Compositing::LayerPlan`: a plan of the layers of a display list on its way to the compositor. WebContent encodes a+/// plan it made, and the compositor decodes a plan that nothing reads until it passes the checks against the list and the+/// tree it is installed with.+#[derive(Debug)]+pub enum LayerPlanOnWire {+ Planned(Arc<LayerPlan>),+ Received(Box<UnvalidatedLayerPlan>),+}++impl LayerPlanOnWire {+ /// The plan a message from WebContent carried, which nothing reads until it is checked.+ pub fn into_received(self) -> UnvalidatedLayerPlan {+ match self {+ Self::Received(layer_plan) => *layer_plan,+ Self::Planned(_) => unreachable!("a message the compositor decoded carries a received plan"),+ }+ }+}++impl Encode for LayerPlanOnWire {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ match self {+ Self::Planned(plan) => encoder.encode(&**plan),+ Self::Received(_) => Err(EncodeError::InvalidValue(+ "A plan of layers goes on only from the process that planned it",+ )),+ }+ }+}++impl Decode for LayerPlanOnWire {+ const MIN_ENCODED_SIZE: usize = UnvalidatedLayerPlan::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self::Received(Box::new(decoder.decode()?)))+ }+}+impl Encode for ChunkId {fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {encoder.encode(&self.0[0])?;diff --git a/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rsindex 76dbb74780c..2c3271f798e 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs@@ -4,13 +4,12 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Everything about a list that travels alongside its tape when it is sent to the Compositor.+//! Everything about a list that travels alongside its chunks when it is sent to the Compositor.use super::ContextRef;use crate::display_list::builder::{bounding_rect_computed_from_payload, read_command};use crate::display_list::commands::{DisplayListCommandType, PaintCaret};use crate::display_list::storage::DisplayListStorage;-use crate::display_list::summary::{for_each_compositor_metadata, for_each_indexed_record};use crate::display_list::window::RecordedWindow;use libgfx_rust::{Color, IntRect};use std::sync::Arc;@@ -18,7 +17,6 @@ use std::sync::Arc;pub use crate::ipc_types::Compositing_AsyncScrollingMetadata as AsyncScrollingMetadata;pub struct DisplayList {- // One strong reference to the Rust storage, which owns the tape.pub(crate) storage: Arc<DisplayListStorage>,id: u64,compatible_visual_context_tree_structural_epoch: u64,@@ -85,23 +83,19 @@ impl DisplayList {// Visits the compositor metadata commands with the context of their run and their payload, in tape order.pub fn for_each_compositor_metadata(&self, visit: impl FnMut(ContextRef, DisplayListCommandType, &[u8])) {- for_each_compositor_metadata(self.storage.bytes(), self.storage.command_runs(), visit);+ self.storage.for_each_compositor_metadata(visit);}// Visits the carets the list draws outside of any group, with the context of their run and their bounding rect.pub fn for_each_caret(&self, mut visit: impl FnMut(ContextRef, IntRect, &PaintCaret)) {- for_each_indexed_record(- self.storage.bytes(),- self.storage.command_runs(),- &self.storage.summary().carets,- |context, header, payload| {+ self.storage+ .for_each_indexed_record(&self.storage.summary().carets, |context, header, payload| {let command = read_command::<PaintCaret>(payload);visit(context,bounding_rect_computed_from_payload(header, payload).unwrap_or_default(),&command,);- },- );+ });}}diff --git a/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rsindex 59e8e81a60d..2405fa7bcf1 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs@@ -41,7 +41,7 @@ impl AccumulatedVisualContextTree {pub fn has_every_node_the_runs_of_display_list_name(&self, display_list: &DisplayList) -> bool {self.0- .display_list_references_only_live_nodes(display_list.storage.command_runs())+ .display_list_references_only_live_nodes(display_list.storage.runs())}pub fn visual_viewport_transform(&self) -> TransformWithOrigin {@@ -154,9 +154,8 @@ pub fn animated_content_may_affect_viewport(viewport_rect: IntRect,sample_time_ns: i64,) -> AnimatedContentViewportEffect {- let effect = crate::display_list::damage::animated_content_may_affect_viewport_at(- display_list.storage.bytes(),- display_list.storage.command_runs(),+ let effect = crate::display_list::animated_content::animated_content_may_affect_viewport_at(+ &display_list.storage,visual_context_tree.as_arc(),scroll_state.device_offsets(),viewport_rect,diff --git a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs b/Libraries/LibCompositing/Rust/src/visual_context/mod.rsindex 199aad77ec3..47650229e11 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/mod.rs@@ -24,14 +24,14 @@ use libipc_rust::wire::{Decode, Encode};use scroll_state::{NO_SCROLL_STATE_SLOT, ScrollStateSlot};pub use crate::display_list::commands::{- ClipMode, ClipNodeIndex, ContextRef, EffectNodeIndex, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,+ ClipMode, ClipNodeIndex, ContextRef, EffectNodeIndex, SpatialNodeIndex, UniqueNodeId, VISUAL_VIEWPORT_NODE_INDEX,};pub use queries::{ClipBehavior, should_cull_back_face};pub use scroll_table::{CompositorScrollNodeKind, CompositorScrollNodeRecord, CompositorScrollTable, CompositorSnapAreaRecord,CompositorSnapContainerRecord,};-pub use world_transforms::{RectMapping, WorldTransforms};+pub use world_transforms::{RasterRoot, RectMapping, WorldTransforms};#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode)]#[repr(u8)]@@ -88,8 +88,17 @@ pub struct ClipPathData {pub fill_rule: WindingRule,}-// The filtered backdrop, limited to the box's rounded border box, is the initial content of the box's-// layer, so the layer's opacity, blend mode and filter apply to it along with the box's content.+impl PartialEq for ClipPathData {+ fn eq(&self, other: &Self) -> bool {+ self.bounding_rect == other.bounding_rect+ && self.fill_rule == other.fill_rule+ && (std::sync::Arc::ptr_eq(&self.path, &other.path)+ || self.path.serialize_to_bytes() == other.path.serialize_to_bytes())+ }+}++/// The filtered backdrop, limited to the box's rounded border box, is the initial content of the box's layer, so the+/// layer's opacity, blend mode and filter apply to it along with the box's content.#[derive(Clone, PartialEq, Encode, Decode)]pub struct BackdropFilterData {pub region: IntRect,@@ -97,7 +106,7 @@ pub struct BackdropFilterData {pub filter: std::sync::Arc<Vec<u8>>,}-#[derive(Clone, Encode, Decode)]+#[derive(Clone, PartialEq, Encode, Decode)]pub struct EffectsData {pub opacity: f32,pub blend_mode: CompositingAndBlendingOperator,@@ -164,29 +173,31 @@ pub struct ScrollData {pub owner_paintable: NodeSlotId,}-// A sticky box's shift is derived when the scroll state snapshot is resolved, from the scroller's-// entry and the parent sticky chain. Both references follow the containing block chain, which-// continues through fixed-position ancestors, so they need not be spatial ancestors of the node.-// Geometry is in device pixels.+/// A sticky box's shift is derived when the scroll state snapshot is resolved, from the scroller's entry and the parent+/// sticky chain. Both references follow the containing block chain, which continues through fixed-position ancestors,+/// so they need not be spatial ancestors of the node. Geometry is in device pixels.#[derive(Clone, Copy, Debug, PartialEq, Encode, Decode)]pub struct StickyData {pub scroller: SpatialNodeIndex,pub parent_sticky: Option<SpatialNodeIndex>,pub position_relative_to_scroller: FloatPoint,- // Where the box's border box was recorded, in device pixels — which is where replay rounds it to.+ /// Where the box's border box was recorded, which is where replay rounds it to.pub border_box_origin: FloatPoint,pub border_box_size: FloatSize,pub scrollport_size: FloatSize,pub containing_block_region: FloatRect,pub needs_parent_offset_adjustment: bool,- // The nearest scroll container of the box when it has no scroll node, because it has no scrollable overflow and- // passes its scrolls on. Its scrollport never moves, and the geometry above is relative to it rather than to the- // scroller.+ /// The nearest scroll container of the box when it has no scroll node, because it has no scrollable overflow and+ /// passes its scrolls on. Its scrollport never moves, and the geometry above is relative to it rather than to the+ /// scroller.pub non_scrolling_scroll_container: NodeSlotId,pub inset_top: Option<f32>,pub inset_right: Option<f32>,pub inset_bottom: Option<f32>,pub inset_left: Option<f32>,+ /// The element the box is generated for, which names the box across relayouts, trees and processes.+ pub box_node_id: UniqueNodeId,+ pub box_pseudo_element_type: u8,#[ipc(skip = NO_SCROLL_STATE_SLOT)]pub state_slot: ScrollStateSlot,#[ipc(skip = NodeSlotId::INVALID)]@@ -214,6 +225,8 @@ impl StickyData {inset_right: None,inset_bottom: None,inset_left: None,+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot,owner_paintable,}@@ -296,7 +309,7 @@ impl LocalTransform {}}-#[derive(Clone, Encode, Decode)]+#[derive(Clone, PartialEq, Encode, Decode)]pub enum SpatialData {Scroll(ScrollData),Sticky(StickyData),@@ -307,17 +320,17 @@ pub enum SpatialData {Dead,}-// The clip tree holds what narrows the painted region without a layer: rectangle (possibly rounded,-// possibly subtractive) clips and clip paths. The effect tree holds what needs a layer or a-// per-box marker: opacity/blend/filter layers, masks and compositor background-color animations.-#[derive(Clone, Encode, Decode)]+/// The clip tree holds what narrows the painted region without a layer: rectangle (possibly rounded, possibly+/// subtractive) clips and clip paths. The effect tree holds what needs a layer or a per-box marker: opacity, blend and+/// filter layers, masks and compositor background-color animations.+#[derive(Clone, PartialEq, Encode, Decode)]pub enum ClipNodeData {Rect(ClipData),Path(ClipPathData),Dead,}-#[derive(Clone, Encode, Decode)]+#[derive(Clone, PartialEq, Encode, Decode)]pub enum EffectNodeData {Effects(EffectsData),Mask(MaskData),@@ -333,6 +346,22 @@ impl SpatialData {pub fn is_scroll_like(&self) -> bool {matches!(self, Self::Scroll(_) | Self::Sticky(_))}++ /// Whether the node is what `other` is, but for the scroll state slot and the paintable that the main thread keeps+ /// of a scroll node or a sticky box.+ fn has_same_content_as(&self, other: &Self) -> bool {+ match (self, other) {+ (Self::Scroll(_), Self::Scroll(_)) => true,+ (Self::Sticky(sticky), Self::Sticky(other_sticky)) => {+ StickyData {+ state_slot: other_sticky.state_slot,+ owner_paintable: other_sticky.owner_paintable,+ ..*sticky+ } == *other_sticky+ }+ _ => self == other,+ }+ }}impl ClipNodeData {@@ -361,19 +390,19 @@ impl EffectNodeData {matches!(self, Self::Effects(_) | Self::Mask(_))}- // An empty mask leaves nothing of the content it wraps.+ /// An empty mask leaves nothing of the content it wraps.pub fn culls_everything(&self) -> bool {matches!(self, Self::Mask(mask) if mask.rect.is_empty())}}-#[derive(Clone)]+#[derive(Clone, PartialEq)]pub struct SpatialNode {pub data: SpatialData,pub parent: SpatialNodeIndex,}-#[derive(Clone)]+#[derive(Clone, PartialEq)]pub struct ClipNode {pub data: ClipNodeData,pub parent: ClipNodeIndex,@@ -393,9 +422,9 @@ impl ClipNode {}}-// The clip in force where an effect begins is a local visual-context fact. Replay-// widens this boundary to accommodate the recorded descendants' clip chains.-#[derive(Clone)]+/// `local_clip` is the clip in force where the effect begins. Replay widens this boundary to accommodate the recorded+/// descendants' clip chains.+#[derive(Clone, PartialEq)]pub struct EffectNode {pub data: EffectNodeData,pub parent: EffectNodeIndex,@@ -419,9 +448,8 @@ impl EffectNode {}}-// The slot lifecycle every node kind shares: a slot is allocated from the free list or by growing-// the array, retired into quarantine until the recording that may still name it completes, and-// released to the free list afterwards.+/// The slot lifecycle every node kind shares: a slot is allocated from the free list or by growing the array, retired+/// into quarantine until the recording that may still name it completes, and released to the free list afterwards.pub trait SlotNode: Sized {type Index: Copy + PartialEq + std::fmt::Debug;fn index(raw: u32) -> Self::Index;@@ -431,7 +459,7 @@ pub trait SlotNode: Sized {fn tombstone(&mut self);}-#[derive(Clone)]+#[derive(Clone, PartialEq)]struct SlotAccounting<Index> {live_count: u32,free: Vec<Index>,@@ -556,18 +584,17 @@ impl SlotNode for EffectNode {}}-// Marks a spatial node whose content belongs to no 3D rendering context.pub const NO_SORTING_CONTEXT: SpatialNodeIndex = SpatialNodeIndex(u32::MAX);-// The plane and 3D rendering context that an established context's own plane renders into.+/// The plane and 3D rendering context that an established context's own plane renders into.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct SortingContextLink {pub parent_context: SpatialNodeIndex,pub parent_leaf: SpatialNodeIndex,}-// Per-spatial-node 3D rendering context membership: the plane each node's content renders into and the context that-// sorts that plane. A tree without 3D rendering contexts resolves to empty per-node vectors.+/// Per-spatial-node 3D rendering context membership: the plane each node's content renders into and the context that+/// sorts that plane. A tree without 3D rendering contexts resolves to empty per-node vectors.#[derive(Default)]pub struct SortingContexts {pub links: HashMap<u32, SortingContextLink>,@@ -593,6 +620,17 @@ impl SortingContexts {}}+fn maps_depth_zero_plane_onto_itself_without_foreshortening(matrix: &FloatMatrix4x4) -> bool {+ let m = &matrix.elements;+ m[2][0] == 0.0 && m[2][1] == 0.0 && m[2][3] == 0.0 && m[3][0] == 0.0 && m[3][1] == 0.0 && m[3][3] == 1.0+}++fn plane_leaves_plane_of_its_sorting_context(node: &SpatialNode) -> bool {+ matches!(&node.data, SpatialData::Transform(transform)+ if transform.sorting_context_root_index.is_some()+ && !maps_depth_zero_plane_onto_itself_without_foreshortening(&transform.matrix))+}+pub fn resolve_sorting_contexts_over_nodes(node_count: usize,nodes_in_dependency_order: &[u32],@@ -611,8 +649,8 @@ pub fn resolve_sorting_contexts_over_nodes(return SortingContexts::default();}- // The dependency order lists a node after its parent and its sorting context root, so a single- // walk along it resolves every node from entries already written.+ // The dependency order lists a node after its parent and its sorting context root, so a single walk along it+ // resolves every node from entries already written.let mut contexts = SortingContexts {links: HashMap::new(),leaf_by_node: vec![NO_SORTING_CONTEXT; node_count],@@ -712,7 +750,7 @@ pub struct VisualContextTreeCopy(u64);impl VisualContextTreeCopy {fn new() -> Self {- // NB: The process's counter numbers nothing but what its numbers are told apart from.+ // NB: Sharing the counter with structural epochs is fine, as copy numbers are only told apart from each other.Self(allocate_structural_epoch())}@@ -727,22 +765,33 @@ impl Clone for VisualContextTreeCopy {}}+/// For a tree that holds the values the compositor's animations take at a time, the number of the copy it took them+/// from. A copy of it takes no number, as anything written to the copy makes it a tree of its own.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct AnimationSamplesTakenFromCopy(Option<u64>);++impl Clone for AnimationSamplesTakenFromCopy {+ fn clone(&self) -> Self {+ Self(None)+ }+}+#[derive(Clone)]pub struct VisualContextTree {pub copy: VisualContextTreeCopy,+ pub animation_samples_taken_from_copy: AnimationSamplesTakenFromCopy,pub spatial_nodes: Vec<SpatialNode>,pub clip_nodes: Vec<ClipNode>,pub effect_nodes: Vec<EffectNode>,- // The layer at the root of the effect tree that 3D plane clips are pushed right above.+ /// The layer at the root of the effect tree that 3D plane clips are pushed right above.pub root_isolation_effect: Option<EffectNodeIndex>,pub structural_epoch: u64,spatial_slots: SlotAccounting<SpatialNodeIndex>,clip_slots: SlotAccounting<ClipNodeIndex>,effect_slots: SlotAccounting<EffectNodeIndex>,- // Keyed by effect node index.- sampled_background_colors: HashMap<u32, libgfx_rust::Color>,- // The compositor animations the main thread published with this tree, which name its nodes.+ sampled_background_color_by_effect_index: HashMap<u32, libgfx_rust::Color>,visual_animations: std::sync::Arc<[VisualAnimation]>,+ visual_animation_targets: std::sync::Arc<visual_animations::VisualAnimationTargets>,compositor_scroll_table: CompositorScrollTable,}@@ -786,9 +835,7 @@ fn for_each_spatial_node_reference(}}-// Calls `visit` for every live node after its parent, by walking up from each node through the-// ancestors not yet visited. Unlike the dependency orders this materializes no order and follows-// parent links only, which is all that per-node values derived from the parent's value need.+// Unlike the dependency orders, follows parent links only, which is all that values derived from a parent's value need.fn visit_nodes_parents_first(node_count: usize,is_live: impl Fn(usize) -> bool,@@ -892,6 +939,7 @@ impl VisualContextTree {effect_nodes: Vec::new(),root_isolation_effect: None,copy: VisualContextTreeCopy::new(),+ animation_samples_taken_from_copy: AnimationSamplesTakenFromCopy::default(),structural_epoch: allocate_structural_epoch(),spatial_slots: SlotAccounting {live_count: 1,@@ -899,13 +947,13 @@ impl VisualContextTree {},clip_slots: SlotAccounting::default(),effect_slots: SlotAccounting::default(),- sampled_background_colors: HashMap::new(),+ sampled_background_color_by_effect_index: HashMap::new(),visual_animations: std::sync::Arc::from(Vec::new()),+ visual_animation_targets: std::sync::Arc::default(),compositor_scroll_table: CompositorScrollTable::default(),}}- // A tree with no node but an identity visual viewport transform, for a list that names no other node.pub fn create_identity() -> Self {Self::create(TransformData {matrix: libgfx_rust::FloatMatrix4x4::identity(),@@ -919,7 +967,7 @@ impl VisualContextTree {})}- // A tree over decoded arrays: no slot is free or quarantined, the live counts are recounted.+ /// A tree over decoded arrays: no slot is free or quarantined, the live counts are recounted.pub fn from_nodes(spatial_nodes: Vec<SpatialNode>,clip_nodes: Vec<ClipNode>,@@ -942,13 +990,43 @@ impl VisualContextTree {effect_nodes,root_isolation_effect,copy: VisualContextTreeCopy::new(),+ animation_samples_taken_from_copy: AnimationSamplesTakenFromCopy::default(),structural_epoch,- sampled_background_colors: HashMap::new(),+ sampled_background_color_by_effect_index: HashMap::new(),visual_animations: std::sync::Arc::from(Vec::new()),+ visual_animation_targets: std::sync::Arc::default(),compositor_scroll_table: CompositorScrollTable::default(),}}+ /// Whether the tree is what `other` is in everything but which copy it is, so that whatever is worked out of one+ /// holds for the other. What only the main thread reads is left out: which slots are free, and the scroll state+ /// slots and the paintables of scroll nodes and sticky boxes, which a tree from another process does not carry.+ pub fn has_same_content_as(&self, other: &Self) -> bool {+ self.structural_epoch == other.structural_epoch+ && self.animation_samples_taken_from_copy == other.animation_samples_taken_from_copy+ && self.root_isolation_effect == other.root_isolation_effect+ && self.spatial_nodes.len() == other.spatial_nodes.len()+ && self+ .spatial_nodes+ .iter()+ .zip(&other.spatial_nodes)+ .all(|(node, other_node)| {+ node.parent == other_node.parent && node.data.has_same_content_as(&other_node.data)+ })+ && self.clip_nodes == other.clip_nodes+ && self.effect_nodes == other.effect_nodes+ && self.sampled_background_color_by_effect_index == other.sampled_background_color_by_effect_index+ && self.visual_animations == other.visual_animations+ && self.compositor_scroll_table == other.compositor_scroll_table+ }++ /// The number of the copy of the tree without the samples of the compositor's animations, which changes only as the+ /// main thread publishes a tree or the compositor writes to the tree other than by sampling its animations.+ pub fn copy_without_animation_samples(&self) -> u64 {+ self.animation_samples_taken_from_copy.0.unwrap_or(self.copy.number())+ }+pub fn compositor_scroll_table(&self) -> &CompositorScrollTable {&self.compositor_scroll_table}@@ -980,7 +1058,6 @@ impl VisualContextTree {.is_some_and(|node| node.data.is_live())}- // The absent node passes for live where a reference may be absent.pub fn clip_is_none_or_live(&self, index: ClipNodeIndex) -> bool {index.is_none() || self.clip_is_live(index)}@@ -1156,13 +1233,12 @@ impl VisualContextTree {VisualContextNodeSink::clip_is_ancestor_or_self(self, ancestor, node)}- // Record the clip in force where this effect begins.pub fn append_effect_node_under(&mut self, context: ContextRef, data: EffectNodeData) -> ContextRef {let effect = self.append_effect(data, context.effect, context.spatial, context.clip);ContextRef { effect, ..context }}- // Root path lengths of the clip nodes; the absent clip has depth 0.+ /// Root path lengths of the clip nodes; the absent clip has depth 0.pub fn clip_depths(&self) -> Vec<u32> {let mut depths = vec![0; self.clip_nodes.len()];self.visit_clip_nodes_parents_first(|index| {@@ -1176,7 +1252,6 @@ impl VisualContextTree {depths}- // Visits every live spatial node after its parent, ending at the visual viewport.pub fn visit_spatial_nodes_parents_first(&self, visit: impl FnMut(usize)) {visit_nodes_parents_first(self.spatial_nodes.len(),@@ -1331,7 +1406,7 @@ impl VisualContextTree {)}- // Output clips live in the clip tree, so they are validated separately rather than ordered here.+ /// Output clips live in the clip tree, so they are validated separately rather than ordered here.pub fn effect_dependency_order_with_back_edges(&self) -> NodeDependencyOrder {dependency_order(self.effect_nodes.len(),@@ -1378,6 +1453,73 @@ impl VisualContextTree {dependency_order.order}+ /// Whether some plane of a 3D sorting context of the tree leaves the plane of its context, so that the planes of+ /// the context have to be sorted by depth. Planes that all stay in the plane of their context are coplanar, which+ /// paint order sorts as depth does.+ pub fn sorts_planes_by_depth(&self) -> bool {+ self.spatial_nodes.iter().any(plane_leaves_plane_of_its_sorting_context)+ }++ // A plane whose transform an animation animates holds the value the tree holds while the animation shows none, and+ // the samples of the animation otherwise.+ fn plane_may_leave_plane_of_its_sorting_context(&self, index: usize) -> bool {+ let node = &self.spatial_nodes[index];+ plane_leaves_plane_of_its_sorting_context(node)+ || (matches!(&node.data, SpatialData::Transform(transform) if transform.sorting_context_root_index.is_some())+ && self.transform_animation_of_node_leaves_plane(SpatialNodeIndex(index as u32)))+ }++ /// As `sorts_planes_by_depth`, for some sample of the animations of the tree: what a plan that holds for every+ /// sample is made for.+ pub fn may_sort_planes_by_depth(&self) -> bool {+ (0..self.spatial_nodes.len()).any(|index| self.plane_may_leave_plane_of_its_sorting_context(index))+ }++ /// Per spatial node, the root of the outermost 3D sorting context around the content of the node, where some+ /// plane of that context or of one inside it leaves the plane of its context at some sample of the animations of+ /// the tree, so that the content is sorted by depth with the rest of the context. The samples of the tree have the+ /// same roots, unless a transform animation animates a plane whose matrix in the tree leaves the plane of its+ /// context while the values of the animation stay in it.+ pub fn roots_of_contexts_sorting_planes_by_depth(&self) -> Vec<Option<SpatialNodeIndex>> {+ let mut root_of_outermost_context: Vec<Option<SpatialNodeIndex>> = vec![None; self.spatial_nodes.len()];+ if !self.may_sort_planes_by_depth() {+ return root_of_outermost_context;+ }+ let sorting_context_root_of = |node: &SpatialNode| match &node.data {+ SpatialData::Transform(transform) => transform.sorting_context_root_index,+ _ => None,+ };+ let mut is_sorting_context_root = vec![false; self.spatial_nodes.len()];+ for root in self.spatial_nodes.iter().filter_map(sorting_context_root_of) {+ is_sorting_context_root[root.0 as usize] = true;+ }+ self.visit_spatial_nodes_parents_first(|index| {+ let node = &self.spatial_nodes[index];+ let root_of_context_around_parent = if index == VISUAL_VIEWPORT_NODE_INDEX.0 as usize {+ None+ } else {+ root_of_outermost_context[node.parent.0 as usize]+ };+ root_of_outermost_context[index] = root_of_context_around_parent+ .or(sorting_context_root_of(node))+ .or(is_sorting_context_root[index].then_some(SpatialNodeIndex(index as u32)));+ });+ let mut context_of_root_sorts_by_depth = vec![false; self.spatial_nodes.len()];+ for (index, root) in root_of_outermost_context.iter().enumerate() {+ if self.plane_may_leave_plane_of_its_sorting_context(index)+ && let Some(root) = root+ {+ context_of_root_sorts_by_depth[root.0 as usize] = true;+ }+ }+ for root in &mut root_of_outermost_context {+ if root.is_some_and(|root| !context_of_root_sorts_by_depth[root.0 as usize]) {+ *root = None;+ }+ }+ root_of_outermost_context+ }+pub fn resolve_sorting_contexts(&self) -> SortingContexts {self.resolve_sorting_contexts_in_order(&self.spatial_dependency_order())}@@ -1422,8 +1564,7 @@ pub fn clip_is_ancestor_or_self(}}-// The deepest clip on both root paths; the absent clip when the paths only share the root. The-// deeper node climbs first, then both climb together.+/// The deepest clip on both root paths, or the absent clip when the paths only share the root.pub fn clip_lowest_common_ancestor_with_depths(parent_of: impl Fn(ClipNodeIndex) -> ClipNodeIndex,depth_of: impl Fn(ClipNodeIndex) -> u32,diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rsindex 2d810697462..b7c5cbfb8f0 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs@@ -7,8 +7,8 @@use super::world_transforms::MINIMUM_PROJECTION_W;use super::{ClipData, ClipMode, ClipNode, ClipNodeData, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex,- IncludeVisualViewportTransform, SpatialData, SpatialNodeIndex, TransformDataRole, VISUAL_VIEWPORT_NODE_INDEX,- VisualContextTree, WorldTransforms, device_offset_for_index,+ IncludeVisualViewportTransform, SpatialData, SpatialNodeIndex, StickyData, TransformDataRole,+ VISUAL_VIEWPORT_NODE_INDEX, VisualContextTree, WorldTransforms, device_offset_for_index,};use ak::math;use libgfx_rust::{CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, FloatRect, IntPoint, IntRect};@@ -16,8 +16,8 @@ use libgfx_rust::{CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, Fl#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum ClipBehavior {Respect,- // Transform the point without rejecting it against clip rects and clip paths. Used when searching for the- // closest caret position within a scope the point may lie entirely outside of.+ /// Transform the point without rejecting it against clip rects and clip paths. Used when searching for the+ /// closest caret position within a scope the point may lie entirely outside of.Ignore,}@@ -57,21 +57,19 @@ impl ClipData {}}-// One root path of spatial nodes with the screen point mapped down it one step at a time. Clips attach to a path in-// non-decreasing depth order, so the steps still to apply before a clip always start where the previous clip left off.+// Clips attach to a path in non-decreasing depth order, so the steps still to apply before a clip always start where+// the previous clip left off.struct SpatialChainWalk {chain: Vec<SpatialNodeIndex>,- // A path through a 3D transform maps the screen point onto each node's plane through the node's flattened matrix,- // where per-node 2D inverses would lose the depth.- projective: bool,+ // Through a 3D transform, per-node 2D inverses would lose the depth.+ maps_point_onto_each_plane_through_flattened_matrix: bool,point: FloatPoint,applied_steps: usize,}-// Whether nothing painted under a node can show, plus the clip-// depths the replay needs to place effects on a context's clip chain. Depth counts the absent clip-// as 0, so a node's depth is the length of its root path.-#[derive(Default)]+/// Whether nothing painted under a node can show, plus the clip depths the replay needs to place effects on a context's+/// clip chain. Depth counts the absent clip as 0, so a node's depth is the length of its root path.+#[derive(Clone, Default)]pub struct TreeCullingScratch {pub clip_depths: Vec<u32>,clip_has_empty_effective_clip: Vec<bool>,@@ -137,7 +135,7 @@ impl VisualContextTree {chain.reverse();SpatialChainWalk {chain,- projective: !world.to_root[leaf.0 as usize].is_2d_affine(),+ maps_point_onto_each_plane_through_flattened_matrix: !world.to_root[leaf.0 as usize].is_2d_affine(),point: screen_point,applied_steps: 0,}@@ -150,15 +148,15 @@ impl VisualContextTree {screen_point: FloatPoint,) -> bool {let node = walk.chain[position];- if !walk.projective {+ if !walk.maps_point_onto_each_plane_through_flattened_matrix {let Some(inverse) = world.local[node.0 as usize].extract_2d_affine().inverse() else {return false;};walk.point = inverse.map_point(walk.point);return true;}- // Content directly under a backface marker lies in the plane of the marker's parent.- if world.draw_space[node.0 as usize] != node {+ let is_backface_marker_drawing_in_plane_of_parent = world.draw_space[node.0 as usize] != node;+ if is_backface_marker_drawing_in_plane_of_parent {return true;}let Some(inverse) = world@@ -201,14 +199,13 @@ impl VisualContextTree {}}- fn point_passes_clip(clip: &ClipNode, point: FloatPoint, clip_behavior: ClipBehavior) -> bool {+ fn point_passes_clip(clip: &ClipNode, point_in_device_pixels: FloatPoint, clip_behavior: ClipBehavior) -> bool {if clip_behavior == ClipBehavior::Ignore {return true;}+ let point = point_in_device_pixels;match &clip.data {ClipNodeData::Rect(clip) => {- // NOTE: The clip rect is in absolute device-pixel coordinates. After inverse-transforming, `point`- // is also in device-pixel coordinates, so we compare them directly.let inside = clip.contains(point);if clip.mode == ClipMode::Intersect {inside@@ -217,8 +214,6 @@ impl VisualContextTree {}}ClipNodeData::Path(clip_path) => {- // NOTE: The clip path is in absolute device-pixel coordinates. After inverse-transforming, `point`- // is also in device-pixel coordinates, so we compare them directly.if !clip_path.bounding_rect.contains_point(IntPoint {x: point.x.floor() as i32,y: point.y.floor() as i32,@@ -238,7 +233,6 @@ impl VisualContextTree {screen_point: FloatPoint,clip_behavior: ClipBehavior,) -> Option<FloatPoint> {- // Effects never clip a point, so only the clip chain takes part.let mut clip_chain: Vec<ClipNodeIndex> = Vec::with_capacity(8);let mut clip = context.clip;while !clip.is_none() {@@ -254,8 +248,7 @@ impl VisualContextTree {let walk = if context_walk.chain.contains(&clip.spatial) {&mut context_walk} else {- // A fixed-background context is rooted above the scroll nodes its clips record in, so such a clip- // hangs below the context's node and takes its own walk from the root.+ // A fixed-background context is rooted above the scroll nodes its clips record in.clip_walk = self.begin_hit_test_walk(world, clip.spatial, screen_point);&mut clip_walk};@@ -364,11 +357,10 @@ impl VisualContextTree {continue;}- // NB: A fixed-position ancestor can disconnect the sticky box's spatial chain from its- // scrollport. Only offsets on the spatial chain move the box, even though the scrollport- // is still used for its size and insets.- // NB: A non-scrolling scroll container moves with the sticky ancestors outside it, so only the- // sticky ancestors inside it move the box within its scrollport.+ // NB: A fixed-position ancestor can disconnect the sticky box's spatial chain from its scrollport. Only+ // offsets on the spatial chain move the box, though the scrollport still gives its size and insets.+ // NB: A non-scrolling scroll container moves with the sticky ancestors outside it, so only the sticky+ // ancestors inside it move the box within its scrollport.let mut parent_sticky_offset = FloatPoint::default();let mut ancestor = node.parent;while ancestor != sticky.scroller && ancestor != VISUAL_VIEWPORT_NODE_INDEX {@@ -383,7 +375,7 @@ impl VisualContextTree {}ancestor = ancestor_node.parent;}- let scroller_entry = if ancestor == sticky.scroller && !scrollport_is_static {+ let negated_scroll_offset_of_scroller = if ancestor == sticky.scroller && !scrollport_is_static {device_offset_for_index(offsets, sticky.scroller)} else {FloatPoint::default()@@ -404,16 +396,15 @@ impl VisualContextTree {y: containing_block_region.bottom() - sticky.border_box_size.height,};- // A scroll container's entry is its negated scroll offset.let scrollport_rect = FloatRect::new(- -scroller_entry.x,- -scroller_entry.y,+ -negated_scroll_offset_of_scroller.x,+ -negated_scroll_offset_of_scroller.y,sticky.scrollport_size.width,sticky.scrollport_size.height,);// NB: An inset only pushes the box in its own direction. A box that already overflows its containing- // block is not pulled back into it, matching other engines.+ // block is not pulled back into it.let mut sticky_offset = FloatPoint::default();if let Some(inset_top) = sticky.inset_top&& scrollport_rect.y > position_in_scroller.y - inset_top@@ -447,19 +438,53 @@ impl VisualContextTree {}}+impl StickyData {+ /// The lowest and the highest offset that resolving can give the box, on each axis, where no sticky box on its+ /// spatial chain moves it within its scroller. An inset pushes the box from where it is laid out to as far as its+ /// containing block lets it go, the way resolving does.+ pub fn offset_range_without_sticky_ancestors(&self) -> (FloatPoint, FloatPoint) {+ let position_in_scroller = self.position_relative_to_scroller;+ let containing_block_region = self.containing_block_region;+ let min_offset_within_containing_block = containing_block_region.top_left();+ let max_offset_within_containing_block = FloatPoint {+ x: containing_block_region.right() - self.border_box_size.width,+ y: containing_block_region.bottom() - self.border_box_size.height,+ };+ let mut lowest = FloatPoint::default();+ let mut highest = FloatPoint::default();+ if self.inset_top.is_some() {+ highest.y = (max_offset_within_containing_block.y - position_in_scroller.y).max(0.0);+ }+ if self.inset_left.is_some() {+ highest.x = (max_offset_within_containing_block.x - position_in_scroller.x).max(0.0);+ }+ if self.inset_bottom.is_some() {+ lowest.y = (min_offset_within_containing_block.y - position_in_scroller.y).min(0.0);+ }+ if self.inset_right.is_some() {+ lowest.x = (min_offset_within_containing_block.x - position_in_scroller.x).min(0.0);+ }+ (lowest, highest)+ }+}+impl VisualContextTree {- // An effects node whose values are all no-ops (opacity 1, normal blending, no filters) exists- // as the target of values that may arrive later; replay draws its content directly rather than- // through a layer. The root isolation effect keeps its layer at those values.+ /// An effects node whose values are all no-ops (opacity 1, normal blending, no filters) exists as the target of+ /// values that may arrive later; replay draws its content directly rather than through a layer. The root isolation+ /// effect keeps its layer at those values, and so does an effect whose opacity or filter an animation of the tree+ /// animates, which isolates its content at every sample of the animation.pub fn effect_pushes_layer_at_replay(&self, effect: EffectNodeIndex) -> bool {match &self.effect_nodes[effect.0 as usize].data {- EffectNodeData::Effects(effects) => effects.needs_layer() || self.root_isolation_effect == Some(effect),+ EffectNodeData::Effects(effects) => {+ effects.needs_layer()+ || self.root_isolation_effect == Some(effect)+ || self.effect_opacity_or_filter_is_animated(effect)+ }EffectNodeData::Mask(_) => true,EffectNodeData::BackgroundColorAnimation | EffectNodeData::Dead => false,}}- // Whether the effect or one of its ancestors pushes a layer.pub fn effect_is_isolated_by_layer(&self, mut effect: EffectNodeIndex) -> bool {while !effect.is_none() {if self.effect_pushes_layer_at_replay(effect) {@@ -485,29 +510,51 @@ impl VisualContextTree {.is_none_or(|layer| self.root_isolation_effect == Some(layer))}- // The backdrop of an effect whose box's masks draw it is read where the outermost of those masks composites.- pub fn effect_backdrop_is_root_group(&self, effect: EffectNodeIndex) -> bool {- let mut reader = effect;- loop {- let parent = self.effect_nodes[reader.0 as usize].parent;- if parent.is_none()- || !matches!(&self.effect_nodes[parent.0 as usize].data, EffectNodeData::Mask(mask) if mask.masks_backdrop)- {- break;- }- reader = parent;- }- self.content_under_effect_composites_into_root_group(self.effect_nodes[reader.0 as usize].parent)+ /// Per live effect node, the node whose layer reads its backdrop: the outermost of the masks of the effect's box+ /// that draw its filtered backdrop, or the effect itself. None for a node that is not live.+ pub fn nodes_reading_the_backdrops_of_effects(&self) -> Vec<EffectNodeIndex> {+ let mut reader_by_effect_index = vec![EffectNodeIndex::NONE; self.effect_nodes.len()];+ self.visit_effect_nodes_parents_first(|index| {+ let parent = self.effect_nodes[index].parent;+ let reader_of_parent_masking_backdrop = (!parent.is_none()+ && matches!(&self.effect_nodes[parent.0 as usize].data, EffectNodeData::Mask(mask) if mask.masks_backdrop))+ .then(|| reader_by_effect_index[parent.0 as usize])+ .filter(|reader| !reader.is_none());+ reader_by_effect_index[index] = reader_of_parent_masking_backdrop.unwrap_or(EffectNodeIndex(index as u32));+ });+ reader_by_effect_index}- pub fn has_blend_mode_reading_root_group(&self) -> bool {+ /// Whether a blend mode or a backdrop filter reads the root group. The backdrop of an effect whose box's masks draw+ /// it is read where the outermost of those masks composites.+ pub fn blend_mode_or_backdrop_filter_reads_root_group(&self) -> bool {+ let reads_backdrop = |data: &EffectNodeData| {+ matches!(data, EffectNodeData::Effects(effects)+ if effects.blend_mode != CompositingAndBlendingOperator::Normal || effects.backdrop_filter.is_some())+ };+ if !self.effect_nodes.iter().any(|node| reads_backdrop(&node.data)) {+ return false;+ }+ let reader_by_effect_index = self.nodes_reading_the_backdrops_of_effects();+ let mut content_composites_into_root_group_by_effect_index = vec![true; self.effect_nodes.len()];+ self.visit_effect_nodes_parents_first(|index| {+ let effect = EffectNodeIndex(index as u32);+ let parent = self.effect_nodes[index].parent;+ content_composites_into_root_group_by_effect_index[index] = if self.effect_pushes_layer_at_replay(effect) {+ self.root_isolation_effect == Some(effect)+ } else {+ parent.is_none() || content_composites_into_root_group_by_effect_index[parent.0 as usize]+ };+ });self.effect_nodes.iter().enumerate().any(|(index, node)| {- matches!(&node.data, EffectNodeData::Effects(effects) if effects.blend_mode != CompositingAndBlendingOperator::Normal)- && self.effect_backdrop_is_root_group(EffectNodeIndex(index as u32))+ let parent_of_reader = || self.effect_nodes[reader_by_effect_index[index].0 as usize].parent;+ reads_backdrop(&node.data)+ && (parent_of_reader().is_none()+ || content_composites_into_root_group_by_effect_index[parent_of_reader().0 as usize])})}- // A blend mode or a backdrop filter reads what the canvas holds outside the effect's own layer.+ /// A blend mode or a backdrop filter reads what the canvas holds outside the effect's own layer.pub fn has_unisolated_destination_reading_effect(&self) -> bool {self.effect_nodes.iter().any(|node| {matches!(@@ -519,6 +566,124 @@ impl VisualContextTree {}}+#[derive(Clone, Copy)]+pub(crate) struct BackdropReader {+ pub(crate) effect_with_backdrop_filter: Option<EffectNodeIndex>,+}++// Per effect node, whether it reads what is below it, and if it reads for a backdrop filter, the effect of the filter.+pub(crate) fn backdrop_reader_by_reading_effect_index(tree: &VisualContextTree) -> Vec<Option<BackdropReader>> {+ let mut backdrop_reader_by_reading_effect_index = vec![None; tree.effect_nodes.len()];+ let mut node_reading_backdrop_by_effect_index = None;+ for (index, effect_node) in tree.effect_nodes.iter().enumerate() {+ let EffectNodeData::Effects(effects) = &effect_node.data else {+ continue;+ };+ let effect = EffectNodeIndex(index as u32);+ if effects.backdrop_filter.is_some() {+ let reading_effect = node_reading_backdrop_by_effect_index+ .get_or_insert_with(|| tree.nodes_reading_the_backdrops_of_effects())[index];+ backdrop_reader_by_reading_effect_index[reading_effect.0 as usize] = Some(BackdropReader {+ effect_with_backdrop_filter: Some(effect),+ });+ } else if effects.blend_mode != CompositingAndBlendingOperator::Normal {+ backdrop_reader_by_reading_effect_index[index] = Some(BackdropReader {+ effect_with_backdrop_filter: None,+ });+ }+ }+ backdrop_reader_by_reading_effect_index+}++/// Whether one live effect node of a tree is inside another, without a walk up the tree for each question. Decoding a+/// tree checks the parents of its live nodes only, so a node that is not live is in no effect and holds none. The+/// table is worked out at the first question.+pub(crate) struct NestingOfLiveEffects<'a> {+ tree: &'a VisualContextTree,+ // Where a walk of the live nodes enters each node and how many nodes it walks from there until it leaves it, or+ // zero nodes for a node the walk does not enter.+ walk_step_and_node_count_by_effect_index: std::cell::OnceCell<Vec<(u32, u32)>>,+}++impl<'a> NestingOfLiveEffects<'a> {+ pub(crate) fn of(tree: &'a VisualContextTree) -> Self {+ Self {+ tree,+ walk_step_and_node_count_by_effect_index: std::cell::OnceCell::new(),+ }+ }++ fn walk_step_and_node_count_of(&self, effect: EffectNodeIndex) -> Option<(u32, u32)> {+ self.walk_step_and_node_count_by_effect_index+ .get_or_init(|| walk_steps_and_node_counts_of_live_effects(self.tree))+ .get(effect.0 as usize)+ .copied()+ .filter(|&(_, node_count)| node_count != 0)+ }++ pub(crate) fn is_or_is_inside(&self, effect: EffectNodeIndex, ancestor: EffectNodeIndex) -> bool {+ match (+ self.walk_step_and_node_count_of(effect),+ self.walk_step_and_node_count_of(ancestor),+ ) {+ (Some((effect_step, _)), Some((ancestor_step, ancestor_node_count))) => {+ ancestor_step <= effect_step && effect_step - ancestor_step < ancestor_node_count+ }+ _ => false,+ }+ }++ pub(crate) fn is_strictly_inside(&self, effect: EffectNodeIndex, ancestor: EffectNodeIndex) -> bool {+ effect != ancestor && self.is_or_is_inside(effect, ancestor)+ }+}++// A node goes into the walk after its parent, so a parent that a broken tree visits later is taken as no parent.+fn walk_steps_and_node_counts_of_live_effects(tree: &VisualContextTree) -> Vec<(u32, u32)> {+ let effect_count = tree.effect_nodes.len();+ let mut live_effects_parents_first: Vec<u32> = Vec::with_capacity(effect_count);+ tree.visit_effect_nodes_parents_first(|index| live_effects_parents_first.push(index as u32));+ let mut visit_position_by_effect_index = vec![u32::MAX; effect_count];+ for (position, &index) in live_effects_parents_first.iter().enumerate() {+ visit_position_by_effect_index[index as usize] = position as u32;+ }+ let walked_parent_by_effect_index: Vec<Option<u32>> = (0..effect_count)+ .map(|index| {+ let parent = tree.effect_nodes[index].parent;+ (!parent.is_none()+ && visit_position_by_effect_index+ .get(parent.0 as usize)+ .is_some_and(|&parent_position| parent_position < visit_position_by_effect_index[index]))+ .then_some(parent.0)+ })+ .collect();+ let mut walk_step_and_node_count_by_effect_index = vec![(0u32, 0u32); effect_count];+ for &index in live_effects_parents_first.iter().rev() {+ let index = index as usize;+ walk_step_and_node_count_by_effect_index[index].1 += 1;+ if let Some(parent) = walked_parent_by_effect_index[index] {+ walk_step_and_node_count_by_effect_index[parent as usize].1 +=+ walk_step_and_node_count_by_effect_index[index].1;+ }+ }+ // The walk enters each child of a node right after the nodes inside the children before it.+ let mut next_step_inside_by_effect_index = visit_position_by_effect_index;+ let mut next_step_of_root = 0u32;+ for &index in &live_effects_parents_first {+ let index = index as usize;+ let next_step = match walked_parent_by_effect_index[index] {+ Some(parent) => &mut next_step_inside_by_effect_index[parent as usize],+ None => &mut next_step_of_root,+ };+ let step = *next_step;+ let node_count = walk_step_and_node_count_by_effect_index[index].1;+ *next_step += node_count;+ walk_step_and_node_count_by_effect_index[index].0 = step;+ next_step_inside_by_effect_index[index] = step + 1;+ }+ walk_step_and_node_count_by_effect_index+}+impl VisualContextTree {pub fn visual_animation_target_is_valid(&self,@@ -542,9 +707,8 @@ impl VisualContextTree {}}- // A recorded fill directly names its background-color animation effect.pub fn sampled_background_color(&self, effect: EffectNodeIndex) -> Option<libgfx_rust::Color> {- self.sampled_background_colors.get(&effect.0).copied()+ self.sampled_background_color_by_effect_index.get(&effect.0).copied()}pub fn visual_animation_targets_are_valid(@@ -590,15 +754,15 @@ impl VisualContextTree {}}- pub fn display_list_references_only_live_nodes(+ pub fn display_list_references_only_live_nodes<'a>(&self,- command_runs: &[crate::display_list::commands::DisplayListCommandRun],+ command_runs: impl IntoIterator<Item = &'a crate::display_list::commands::DisplayListCommandRun>,) -> bool {- command_runs.iter().all(|run| self.context_is_valid(run.context))+ command_runs.into_iter().all(|run| self.context_is_valid(run.context))}- // Bound every possible angle, rather than just the current sample: content outside the viewport now- // may rotate into it later. Repeatedly enclosing rectangles also conservatively handles nested rotations.+ /// Bounds every possible angle, rather than just the current sample: content outside the viewport now may rotate+ /// into it later. Repeatedly enclosing rectangles also conservatively handles nested rotations.pub fn rect_with_rotation_bounds_to_viewport(&self,mut index: SpatialNodeIndex,@@ -659,7 +823,7 @@ mod tests {use crate::node_slot_id::NodeSlotId;use crate::visual_context::{BackfaceVisibilityData, ClipData, ClipMode, EffectsData, PerspectiveData, ScrollData, SpatialData, SpatialNode,- StickyData, TransformData, TransformDataRole, scroll_state::NO_SCROLL_STATE_SLOT,+ StickyData, TransformData, TransformDataRole, UniqueNodeId, scroll_state::NO_SCROLL_STATE_SLOT,};use libgfx_rust::{CornerRadii, FloatMatrix4x4, FloatSize, perspective_matrix, scale_matrix, translation_matrix};@@ -701,8 +865,11 @@ mod tests {scratch.clip_has_empty_effective_clip}- // A context under a fresh clip node with no effect.- fn clip_context(tree: &mut VisualContextTree, data: ClipNodeData, spatial: SpatialNodeIndex) -> ContextRef {+ fn context_under_new_clip_without_effect(+ tree: &mut VisualContextTree,+ data: ClipNodeData,+ spatial: SpatialNodeIndex,+ ) -> ContextRef {let clip = tree.append_clip(data, ClipNodeIndex::NONE, spatial);ContextRef {clip,@@ -711,6 +878,66 @@ mod tests {}}+ // A backdrop is read where the outermost of the masks of its box that draw it composites, which is the root group+ // where no layer but the root isolation layer is around that mask.+ #[test]+ fn a_blend_mode_or_backdrop_filter_reads_the_root_group_where_no_other_layer_is_around_where_it_reads() {+ let effects = |opacity: f32, blend_mode, backdrop_filter: Option<crate::visual_context::BackdropFilterData>| {+ EffectNodeData::Effects(EffectsData {+ isolation: false,+ opacity,+ blend_mode,+ filter: None,+ backdrop_filter,+ })+ };+ let backdrop_filter = || {+ Some(crate::visual_context::BackdropFilterData {+ filter: std::sync::Arc::new(Vec::new()),+ region: IntRect::new(0, 0, 10, 10),+ corner_radii: CornerRadii::default(),+ })+ };+ let mask_drawing_backdrop = || {+ EffectNodeData::Mask(crate::visual_context::MaskData {+ rect: IntRect::new(0, 0, 10, 10),+ kind: crate::visual_context::MaskKind::Luminance,+ origin: crate::visual_context::MaskLayerOrigin::CssMaskLayers,+ masks_backdrop: true,+ })+ };+ let append = |tree: &mut VisualContextTree, data: EffectNodeData, parent: EffectNodeIndex| {+ tree.append_effect(data, parent, VISUAL_VIEWPORT_NODE_INDEX, ClipNodeIndex::NONE)+ };+ let normal = CompositingAndBlendingOperator::Normal;++ let mut tree = identity_tree();+ let plain_group = append(&mut tree, effects(1.0, normal, None), EffectNodeIndex::NONE);+ assert!(!tree.blend_mode_or_backdrop_filter_reads_root_group());+ append(+ &mut tree,+ effects(1.0, CompositingAndBlendingOperator::Multiply, None),+ plain_group,+ );+ assert!(tree.blend_mode_or_backdrop_filter_reads_root_group());++ let mut tree = identity_tree();+ let root_isolation = append(&mut tree, effects(1.0, normal, None), EffectNodeIndex::NONE);+ tree.root_isolation_effect = Some(root_isolation);+ let translucent_group = append(&mut tree, effects(0.5, normal, None), root_isolation);+ let mask_in_translucent_group = append(&mut tree, mask_drawing_backdrop(), translucent_group);+ append(+ &mut tree,+ effects(1.0, normal, backdrop_filter()),+ mask_in_translucent_group,+ );+ assert!(!tree.blend_mode_or_backdrop_filter_reads_root_group());+ let outer_mask = append(&mut tree, mask_drawing_backdrop(), root_isolation);+ let inner_mask = append(&mut tree, mask_drawing_backdrop(), outer_mask);+ append(&mut tree, effects(1.0, normal, backdrop_filter()), inner_mask);+ assert!(tree.blend_mode_or_backdrop_filter_reads_root_group());+ }+#[test]fn translations_snap_under_identities_as_the_world_transforms_table_says() {let mut tree = identity_tree();@@ -956,7 +1183,7 @@ mod tests {#[test]fn a_difference_clip_passes_only_points_outside_its_rect() {let mut tree = identity_tree();- let context = clip_context(+ let context = context_under_new_clip_without_effect(&mut tree,clip(FloatRect::new(10.0, 10.0, 20.0, 20.0), ClipMode::Difference),VISUAL_VIEWPORT_NODE_INDEX,@@ -969,7 +1196,7 @@ mod tests {#[test]fn a_fractional_clip_rect_contains_points_by_float_containment() {let mut tree = identity_tree();- let context = clip_context(+ let context = context_under_new_clip_without_effect(&mut tree,clip(FloatRect::new(10.5, 10.5, 20.0, 20.0), ClipMode::Intersect),VISUAL_VIEWPORT_NODE_INDEX,@@ -982,7 +1209,7 @@ mod tests {#[test]fn an_integral_clip_rect_contains_points_by_integer_containment() {let mut tree = identity_tree();- let context = clip_context(+ let context = context_under_new_clip_without_effect(&mut tree,clip(FloatRect::new(10.0, 10.0, 20.0, 20.0), ClipMode::Intersect),VISUAL_VIEWPORT_NODE_INDEX,@@ -996,7 +1223,7 @@ mod tests {#[test]fn a_rounded_clip_rejects_points_outside_its_corner_ellipses() {let mut tree = identity_tree();- let context = clip_context(+ let context = context_under_new_clip_without_effect(&mut tree,ClipNodeData::Rect(ClipData {rect: FloatRect::new(0.0, 0.0, 100.0, 100.0),@@ -1165,7 +1392,7 @@ mod tests {fn a_context_below_the_context_node_takes_its_own_walk_from_the_root() {let mut tree = identity_tree();let scroll_node = tree.append_spatial(scroll(), VISUAL_VIEWPORT_NODE_INDEX);- let context = clip_context(+ let context = context_under_new_clip_without_effect(&mut tree,clip(FloatRect::new(0.0, 0.0, 50.0, 50.0), ClipMode::Intersect),scroll_node,@@ -1281,6 +1508,8 @@ mod tests {inset_right: None,inset_bottom: None,inset_left: None,+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,}),@@ -1308,6 +1537,8 @@ mod tests {inset_right: None,inset_bottom: None,inset_left: None,+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,}),@@ -1358,6 +1589,8 @@ mod tests {inset_right: None,inset_bottom: None,inset_left: None,+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,})diff --git a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rsindex 742bf52766d..f75a2299386 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs@@ -388,6 +388,8 @@ mod tests {inset_right: None,inset_bottom: Some(2.5),inset_left: None,+ box_node_id: UniqueNodeId(41),+ box_pseudo_element_type: 2,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,}),@@ -414,6 +416,8 @@ mod tests {inset_right: Some(1.0),inset_bottom: None,inset_left: Some(3.0),+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,}),diff --git a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rsindex cf9192f64b6..3e0e7a48e6e 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs@@ -10,9 +10,74 @@ use super::{ClipBehavior, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex, EffectsData, SpatialData,SpatialNodeIndex, VisualContextTree, WorldTransforms,};+use crate::filter_bytes::filter_functions_graph;use crate::host::{FfiVisualAnimationSummary, FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};use crate::visual_animation::{VisualAnimation, VisualAnimationSample, VisualAnimationValue};use libgfx_rust::FloatPoint;+use libgfx_rust::filter::Filter;++/// What the animations of a tree animate, per node, worked out once as they are set, so that the copies of the tree+/// that share the animations share it too.+#[derive(Default)]+pub(crate) struct VisualAnimationTargets {+ effect_targets: Vec<AnimatedEffect>,+ transform_animation_leaves_plane_by_spatial_index: Vec<bool>,+}++#[derive(Clone, Copy, Default)]+struct AnimatedEffect {+ opacity_or_filter_is_animated: bool,+ filter_is_animated: bool,+ some_keyframe_filter_spreads: bool,+}++impl VisualAnimationTargets {+ fn of(animations: &[VisualAnimation]) -> Self {+ let mut targets = Self::default();+ for animation in animations {+ match animation.target_kind {+ FfiVisualAnimationTargetKind::Opacity | FfiVisualAnimationTargetKind::Filter => {+ let is_filter = animation.target_kind == FfiVisualAnimationTargetKind::Filter;+ let some_keyframe_filter_spreads = is_filter+ && animation.keyframes.iter().any(|keyframe| {+ matches!(&keyframe.value, VisualAnimationValue::Filter(functions)+ if filter_functions_graph(functions.iter().copied().map(Filter::from))+ .is_some_and(|graph| graph.may_affect_output_bounds()))+ });+ for &node_index in &animation.node_indices {+ let index = node_index as usize;+ if targets.effect_targets.len() <= index {+ targets.effect_targets.resize(index + 1, AnimatedEffect::default());+ }+ let target = &mut targets.effect_targets[index];+ target.opacity_or_filter_is_animated = true;+ target.filter_is_animated |= is_filter;+ target.some_keyframe_filter_spreads |= some_keyframe_filter_spreads;+ }+ }+ FfiVisualAnimationTargetKind::Transform => {+ if crate::display_list::animated_transform_spaces::transform_animation_stays_in_plane(animation) {+ continue;+ }+ for &node_index in &animation.node_indices {+ let index = node_index as usize;+ let leaves_plane = &mut targets.transform_animation_leaves_plane_by_spatial_index;+ if leaves_plane.len() <= index {+ leaves_plane.resize(index + 1, false);+ }+ leaves_plane[index] = true;+ }+ }+ FfiVisualAnimationTargetKind::BackgroundColor => {}+ }+ }+ targets+ }++ fn effect(&self, effect: EffectNodeIndex) -> AnimatedEffect {+ self.effect_targets.get(effect.0 as usize).copied().unwrap_or_default()+ }+}/// What a frame scheduler needs to bound the content the running animations move: the nodes of the/// animations whose swept area is bounded, sorted by how the bound is computed, and whether every@@ -37,15 +102,60 @@ impl VisualContextTree {}pub fn set_visual_animations(&mut self, animations: Vec<VisualAnimation>) {+ self.visual_animation_targets = std::sync::Arc::new(VisualAnimationTargets::of(&animations));self.visual_animations = std::sync::Arc::from(animations);}pub fn clear_visual_animations(&mut self) {if self.has_visual_animations() {self.visual_animations = std::sync::Arc::from(Vec::new());+ self.visual_animation_targets = std::sync::Arc::default();}}+ /// Whether an opacity or filter animation of the tree animates the effect node.+ pub fn effect_opacity_or_filter_is_animated(&self, effect: EffectNodeIndex) -> bool {+ self.visual_animation_targets+ .effect(effect)+ .opacity_or_filter_is_animated+ }++ /// Whether a filter animation of the tree animates the effect node.+ pub fn effect_filter_is_animated(&self, effect: EffectNodeIndex) -> bool {+ self.visual_animation_targets.effect(effect).filter_is_animated+ }++ /// Whether the filter a keyframe of a filter animation of the effect node gives it can spread what it filters+ /// outside its bounds.+ pub fn some_keyframe_filter_of_effect_spreads(&self, effect: EffectNodeIndex) -> bool {+ self.visual_animation_targets+ .effect(effect)+ .some_keyframe_filter_spreads+ }++ /// Whether a transform animation of the tree that turns what it transforms out of the plane at some sample+ /// animates the spatial node.+ pub fn transform_animation_of_node_leaves_plane(&self, node: SpatialNodeIndex) -> bool {+ self.visual_animation_targets+ .transform_animation_leaves_plane_by_spatial_index+ .get(node.0 as usize)+ .copied()+ .unwrap_or(false)+ }++ /// Whether a transform animation of the tree animates a plane of a 3D sorting context, whose samples can hold the+ /// plane in the plane of its context where the tree turns it out of it, or the other way around.+ pub fn transform_animation_animates_plane_of_sorting_context(&self) -> bool {+ self.visual_animations+ .iter()+ .filter(|animation| animation.target_kind == FfiVisualAnimationTargetKind::Transform)+ .flat_map(|animation| animation.node_indices.iter())+ .any(|&node_index| {+ matches!(self.spatial_nodes.get(node_index as usize).map(|node| &node.data),+ Some(SpatialData::Transform(transform)) if transform.sorting_context_root_index.is_some())+ })+ }+pub fn shared_visual_animations(&self) -> std::sync::Arc<[VisualAnimation]> {self.visual_animations.clone()}@@ -66,7 +176,9 @@ impl VisualContextTree {/// resolved, leaves its nodes as the main thread published them.pub fn with_visual_animation_samples(&self, sample_time_ns: i64) -> Self {let mut sampled = self.clone();- sampled.sampled_background_colors.clear();+ sampled.animation_samples_taken_from_copy =+ super::AnimationSamplesTakenFromCopy(Some(self.copy_without_animation_samples()));+ sampled.sampled_background_color_by_effect_index.clear();for animation in self.visual_animations.iter() {let Some(sample) = animation.sample(animation.elapsed_since_anchor_ns(sample_time_ns)) else {continue;@@ -79,7 +191,9 @@ impl VisualContextTree {}}VisualAnimationSample::BackgroundColor(color) => {- sampled.sampled_background_colors.insert(node_index, *color);+ sampled+ .sampled_background_color_by_effect_index+ .insert(node_index, *color);}VisualAnimationSample::Filter(filter) => {if let Some(effects) = sampled.effects_mut(node_index) {diff --git a/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rsindex 69c10d6b3c5..d33523c5a6d 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs@@ -10,10 +10,19 @@ use super::{};use libgfx_rust::{AffineTransform, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, map_rect_through_matrix, multiply_affine,- translation_matrix,+ scale_matrix, translation_matrix,};-// Homogeneous coordinates this close to the eye plane have no meaningful projection.+/// A spatial node whose subtree a table maps into the node's own coordinates times `raster_scale`, under the root's+/// parent matrix, rather than through the node's transform, which the compositor animates: the subtree lands alike in+/// every sample of the animation.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct RasterRoot {+ pub anchor: SpatialNodeIndex,+ pub raster_scale: f32,+}++/// Homogeneous coordinates this close to the eye plane have no meaningful projection.pub const MINIMUM_PROJECTION_W: f32 = 0.0001;/// The to-root matrix of every spatial node under one set of scroll offsets, filled in dependency order so that any@@ -34,14 +43,29 @@ pub struct WorldTransforms {pub translations_snap_to_device_pixels: Vec<bool>,}-// The cull state of the element that establishes the 3D rendering context rooted at root: the cull state of the-// plane the context is flattened into.-fn backface_culled_outside_sorting_context(+/// The translation by `offset` of a scroll, sticky or anchor scroll shift node under no transform, on whole device+/// pixels. A sticky offset carries the fraction of the box's own position, which replay rounds the box by already, so+/// for a sticky box recorded at `sticky_box_origin` where the box lands is rounded, not the offset, or a box at a half+/// pixel would round twice.+pub fn translation_on_whole_device_pixels(offset: FloatPoint, sticky_box_origin: Option<FloatPoint>) -> FloatPoint {+ match sticky_box_origin {+ Some(origin) => FloatPoint {+ x: (origin.x + offset.x).round() - origin.x.round(),+ y: (origin.y + offset.y).round() - origin.y.round(),+ },+ None => FloatPoint {+ x: offset.x.round(),+ y: offset.y.round(),+ },+ }+}++fn backface_culled_at_element_establishing_sorting_context(tree: &VisualContextTree,backface_culled: &[bool],- root: SpatialNodeIndex,+ sorting_context_root: SpatialNodeIndex,) -> bool {- let mut index = root;+ let mut index = sorting_context_root;loop {if tree.local_transform(index, &[]).establishes_sorting_context {return backface_culled[index.0 as usize];@@ -58,6 +82,15 @@ impl WorldTransforms {tree: &VisualContextTree,scroll_offsets: &[FloatPoint],root_parent_matrix: Option<FloatMatrix4x4>,+ ) -> Self {+ Self::with_raster_root(tree, scroll_offsets, root_parent_matrix, None)+ }++ pub fn with_raster_root(+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ root_parent_matrix: Option<FloatMatrix4x4>,+ raster_root: Option<RasterRoot>,) -> Self {let mut world = Self::default();world.fill(@@ -65,6 +98,7 @@ impl WorldTransforms {&tree.spatial_dependency_order(),scroll_offsets,root_parent_matrix,+ raster_root,);world}@@ -79,13 +113,14 @@ impl WorldTransforms {}/// Fills the table, with `root_parent_matrix` as what the visual viewport node's transform applies on top of, or- /// with that transform left out.+ /// with that transform left out, and the subtree of `raster_root` mapped as it says.pub fn fill(&mut self,tree: &VisualContextTree,spatial_dependency_order: &[u32],scroll_offsets: &[FloatPoint],root_parent_matrix: Option<FloatMatrix4x4>,+ raster_root: Option<RasterRoot>,) {let node_count = tree.spatial_nodes.len();self.clear();@@ -100,32 +135,33 @@ impl WorldTransforms {let i = index as usize;let parent = tree.spatial_nodes[i].parent.0 as usize;let mut local = tree.local_transform(SpatialNodeIndex(index), scroll_offsets);- let transforms = local.is_transform_or_perspective() && local.matrix != FloatMatrix4x4::identity();- let snaps = i == 0 || (self.translations_snap_to_device_pixels[parent] && !transforms);- self.translations_snap_to_device_pixels[i] = snaps;+ let raster_root_here = raster_root.filter(|raster_root| raster_root.anchor.0 == index);+ if let Some(raster_root) = raster_root_here {+ let scale = scale_matrix(raster_root.raster_scale, raster_root.raster_scale, 1.0);+ local.matrix = scale;+ local.flattens_inherited_transform = false;+ }+ let has_non_identity_transform = raster_root_here.is_some()+ || (local.is_transform_or_perspective() && local.matrix != FloatMatrix4x4::identity());+ let translations_snap =+ i == 0 || (self.translations_snap_to_device_pixels[parent] && !has_non_identity_transform);+ self.translations_snap_to_device_pixels[i] = translations_snap;if let LocalTransformKind::Translation(offset) = local.kind- && snaps+ && translations_snap{- let snapped = match &tree.spatial_nodes[i].data {- // A sticky offset carries the fraction of the box's own position, which replay rounds the box- // by already. So snap where the box lands, not the offset — or a box at a half pixel rounds twice.- SpatialData::Sticky(sticky) => {- let origin = sticky.border_box_origin;- FloatPoint {- x: (origin.x + offset.x).round() - origin.x.round(),- y: (origin.y + offset.y).round() - origin.y.round(),- }- }- _ => FloatPoint {- x: offset.x.round(),- y: offset.y.round(),- },+ let sticky_box_origin = match &tree.spatial_nodes[i].data {+ SpatialData::Sticky(sticky) => Some(sticky.border_box_origin),+ _ => None,};- local.matrix = translation_matrix(snapped.x, snapped.y, 0.0);+ let snapped_offset = translation_on_whole_device_pixels(offset, sticky_box_origin);+ local.matrix = translation_matrix(snapped_offset.x, snapped_offset.y, 0.0);}self.to_root[i] = match (i, root_parent_matrix) {(0, None) => FloatMatrix4x4::identity(),(0, Some(root_parent_matrix)) => local.applied_to(root_parent_matrix),+ _ if raster_root_here.is_some() => {+ local.applied_to(root_parent_matrix.unwrap_or(FloatMatrix4x4::identity()))+ }_ => local.applied_to(self.to_root[parent]),};self.local[i] = local.matrix;@@ -139,7 +175,7 @@ impl WorldTransforms {// culls the 3D rendering contexts nested in it:// https://github.com/w3c/csswg-drafts/issues/918if let Some(root) = local.sorting_context_root {- culled = backface_culled_outside_sorting_context(tree, &self.backface_culled, root);+ culled = backface_culled_at_element_establishing_sorting_context(tree, &self.backface_culled, root);}if let Some(plane_root) = local.backface_plane_root {self.draw_space[i] = self.draw_space[parent];diff --git a/Libraries/LibGfx/Rust/src/filter.rs b/Libraries/LibGfx/Rust/src/filter.rsindex abb4098f4b9..78da10c1548 100644--- a/Libraries/LibGfx/Rust/src/filter.rs+++ b/Libraries/LibGfx/Rust/src/filter.rs@@ -411,6 +411,23 @@ impl Filter {.into()}+ /// Whether the graph can show what its source graphic draws away from where it draws it, as an+ /// offset does, rather than only over it and around it, as a blur or a drop shadow does. Crops+ /// are left out, as they only hide what they cut.+ pub fn may_move_its_source(&self) -> bool {+ let probe = FloatRect::new(0.0, 0.0, 1.0, 1.0);+ match self.bounds_for_source(OutputBounds::Rect(probe), BoundsQuestion::ChangeUncropped) {+ OutputBounds::Rect(bounds) => !bounds.contains_rect(probe),+ OutputBounds::Unbounded => false,+ }+ }++ /// [`Self::may_move_its_source`] for a serialized graph. Bytes that do not hold a graph are+ /// assumed to change everywhere, which moves nothing away from where it changes.+ pub fn serialized_may_move_its_source(bytes: &[u8]) -> bool {+ Self::deserialize(bytes).is_some_and(|filter| filter.may_move_its_source())+ }+/// [`Self::output_bounds`] for a serialized graph. Bytes that do not hold a graph are assumed/// to paint everywhere.pub fn serialized_output_bounds(bytes: &[u8], source: FloatRect) -> Option<FloatRect> {@@ -430,8 +447,8 @@ impl Filter {.map_or(source, |input| input.bounds_for_source(source, question))};let painted_inputs = |painted_inputs: PaintedInputs| match (question, painted_inputs) {- (BoundsQuestion::Change, PaintedInputs::Neither) | (BoundsQuestion::Output, _) => painted_inputs,- (BoundsQuestion::Change, _) => PaintedInputs::Either,+ (BoundsQuestion::Output, _) | (_, PaintedInputs::Neither) => painted_inputs,+ (BoundsQuestion::Change | BoundsQuestion::ChangeUncropped, _) => PaintedInputs::Either,};match self {Self::Compose { outer, inner } => {@@ -448,7 +465,7 @@ impl Filter {input,} => match question {BoundsQuestion::Output => input_bounds(input),- BoundsQuestion::Change => {+ BoundsQuestion::Change | BoundsQuestion::ChangeUncropped => {input_bounds(input).outset(radius_x.max(0.0).ceil(), radius_y.max(0.0).ceil())}},@@ -501,7 +518,9 @@ impl Filter {match question {BoundsQuestion::Output => displaced_color,// A change to the displacement moves what is sampled where it changed.- BoundsQuestion::Change => displaced_color.united(input_bounds(displacement)),+ BoundsQuestion::Change | BoundsQuestion::ChangeUncropped => {+ displaced_color.united(input_bounds(displacement))+ }}}Self::Merge { inputs } => inputs.iter().fold(OutputBounds::EMPTY, |bounds, input| {@@ -539,6 +558,7 @@ impl Filter {}Self::Image { dest_rect, .. } => OutputBounds::Rect(*dest_rect),Self::Flood { .. } | Self::Turbulence { .. } => OutputBounds::Unbounded,+ Self::Crop { input, .. } if question == BoundsQuestion::ChangeUncropped => input_bounds(input),// Nothing outside the rect paints or changes.Self::Crop { rect, input } => input_bounds(input).intersected(OutputBounds::Rect(*rect)),}@@ -580,6 +600,8 @@ enum BoundsQuestion {Output,// Where the output can change, for a source changing within the rect.Change,+ // As `Change`, with every crop left out.+ ChangeUncropped,}impl OutputBounds {diff --git a/Libraries/LibGfx/Rust/src/geometry.rs b/Libraries/LibGfx/Rust/src/geometry.rsindex 4020801d976..e54c818b577 100644--- a/Libraries/LibGfx/Rust/src/geometry.rs+++ b/Libraries/LibGfx/Rust/src/geometry.rs@@ -259,6 +259,9 @@ impl IntRect {pub const fn inflated(self, w: i32, h: i32) -> Self {Self::new(self.x - w / 2, self.y - h / 2, self.width + w, self.height + h)}+ pub const fn translated(self, dx: i32, dy: i32) -> Self {+ Self::new(self.x + dx, self.y + dy, self.width, self.height)+ }pub const fn inflated_edges(self, top: i32, right: i32, bottom: i32, left: i32) -> Self {Self::new(self.x - left,diff --git a/Libraries/LibGfx/Rust/src/paint_enums.rs b/Libraries/LibGfx/Rust/src/paint_enums.rsindex 0562eb4d9f4..c821b280e7b 100644--- a/Libraries/LibGfx/Rust/src/paint_enums.rs+++ b/Libraries/LibGfx/Rust/src/paint_enums.rs@@ -80,6 +80,21 @@ pub enum CompositingAndBlendingOperator {}impl CompositingAndBlendingOperator {+ /// Whether drawing with the operator can lower the alpha of what is already drawn below, where it draws or around it.+ pub fn lowers_destination_alpha(self) -> bool {+ matches!(+ self,+ Self::Clear+ | Self::Copy+ | Self::SourceIn+ | Self::DestinationIn+ | Self::SourceOut+ | Self::DestinationOut+ | Self::DestinationATop+ | Self::Xor+ )+ }+pub fn from_i32(value: i32) -> Option<Self> {if (Self::Normal as i32..=Self::PlusLighter as i32).contains(&value) {// SAFETY: the enum is a dense i32 range from Normal to PlusLighter.diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex 16287770d2d..03fed6c2c6e 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -14,6 +14,9 @@#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>#include <LibWeb/WebGL/RemoteWebGLTransport.h>+// The Paint stage keeps what the compositor keeps of the display lists sent for each context.+extern "C" void paint_stage_forget_destroyed_compositor_context(u64 context_id);+namespace Web::Compositor {CompositorContextHandle::CompositorContextHandle(CompositorHost& host, Web::CompositorContextId context_id)@@ -418,6 +421,7 @@ bool CompositorHost::rasterize_last_recording(Layout::RustFFI::DocumentHost consvoid CompositorHost::destroy_context(Web::CompositorContextId context_id){+ paint_stage_forget_destroyed_compositor_context(context_id.value());if (auto* connection = compositor_connection()) {connection->destroy_context(context_id);// A connection attached the render clock, whose lanes of the context hear of it no more.diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 13a2fbad49e..baf8dadf1dd 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -3051,7 +3051,8 @@ Layout::RustFFI::FfiPaintPreparationHostCallbacks Document::paint_preparation_ho.viewport = [](void* context, Layout::RustFFI::FfiPaintPreparationViewport* viewport) {auto& document = *static_cast<Document*>(context);viewport->visual_context_tree_inputs = Painting::visual_context_tree_inputs(document);- viewport->device_viewport_size = document.page().css_to_device_rect(document.viewport_rect()).size().to_type<int>(); },+ auto navigable = document.navigable();+ viewport->device_viewport_size = navigable ? navigable->viewport_size_in_device_pixels() : Gfx::IntSize {}; },.resolve_svg_filter = [](void* context, Layout::BegunRead const* read, Compositing::RustFFI::NodeSlotId slot, void const* url_value, void* sink) { return Painting::push_svg_filter_reference(*read, *static_cast<Document*>(context), slot, url_value, sink); },.resolve_svg_paint_server = [](void* context, Layout::BegunRead const* read, Compositing::RustFFI::NodeSlotId slot, bool is_stroke, void* sink) { Painting::push_svg_paint_server_description(*read, *static_cast<Document*>(context), slot, is_stroke, sink); },.require_display_list_recording = [](void* context, bool request_frame) {diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex b295c91691d..c713ac849bc 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -4949,7 +4949,7 @@ void LocalNavigable::set_viewport_size(CSSPixelSize size, InvalidateDisplayListif (has_compositor_context()) {compositor_context().viewport_size_updated(- page().css_to_device_rect(viewport_rect()).size().to_type<int>(),+ viewport_size_in_device_pixels(),page().client().device_pixel_ratio(),Compositing::WindowResizingInProgress::Yes);}@@ -7001,7 +7001,7 @@ void LocalNavigable::repaint_after_compositor_process_reconnect()}}compositor_context().viewport_size_updated(- page().css_to_device_rect(viewport_rect()).size().to_type<int>(),+ viewport_size_in_device_pixels(),page().client().device_pixel_ratio(),Compositing::WindowResizingInProgress::No);@@ -7161,7 +7161,7 @@ bool LocalNavigable::commit_frame(PaintConfig paint_config)// NB: Only the top-level traversable fills its canvas. A local root under a remote parent is an iframe in another// process, and its canvas stays transparent like that of a same-process iframe.if (is_top_level_traversable() && !paint_config.canvas_fill_rect.has_value())- paint_config.canvas_fill_rect = Gfx::IntRect { {}, page().css_to_device_rect(viewport_rect()).size().to_type<int>() };+ paint_config.canvas_fill_rect = Gfx::IntRect { {}, viewport_size_in_device_pixels() };// A frame is left to the next rendering update while the compositor cannot be reached.if (!compositor_context().ready_for_frame())@@ -7405,7 +7405,19 @@ void LocalNavigable::paint_next_frame()Gfx::IntRect LocalNavigable::present_viewport_rect() const{- return page().css_to_device_rect(viewport_rect()).to_type<int>();+ return { page().css_to_device_rect(viewport_rect()).location().to_type<int>(), viewport_size_in_device_pixels() };+}++// A viewport size in device pixels becomes one in CSS pixels floored to a fraction of a CSS pixel, so its product with+// the scale lies just below the device size. Rounding gives the device size back, which the UI process gives the+// compositor too.+Gfx::IntSize LocalNavigable::viewport_size_in_device_pixels() const+{+ auto scale = page().client().device_pixels_per_css_pixel();+ return {+ static_cast<int>(round(m_viewport_size.width().to_double() * scale)),+ static_cast<int>(round(m_viewport_size.height().to_double() * scale)),+ };}bool LocalNavigable::paint_next_frame_if_needed(DOM::UpdateLayoutReason layout_reason, LayOutFirst lay_out_first)diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex ed1541f78c1..e99f25d419f 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -248,6 +248,8 @@ public:CSSPixelRect viewport_rect() const { return { m_viewport_scroll_offset, m_viewport_size }; }CSSPixelSize viewport_size() const { return m_viewport_size; }void set_viewport_size(CSSPixelSize, InvalidateDisplayList = InvalidateDisplayList::No);+ Gfx::IntSize viewport_size_in_device_pixels() const;+ Gfx::IntRect present_viewport_rect() const;// A size the window takes as a rendering update is in flight waits for that update to end: the update flies for// the size it began with, and a new size would make the main thread wait for the flight and lay out again.@@ -472,7 +474,6 @@ private:void commit_unrecorded_frame(Layout::BegunRead const&, DOM::Document&, Compositor::SealedPresentation);Compositor::SealedPresentation seal_presentation(Layout::BegunRead const&, DOM::Document&, PaintConfig const&, bool records_display_list);void finish_recording_in_flight(RecordingInFlight&, Layout::RustFFI::FfiRecordingLanding, bool presented_other_scroll_offsets);- Gfx::IntRect present_viewport_rect() const;Optional<CSSPixelPoint> to_local_root_viewport_position(CSSPixelPoint);diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex df505177d55..40224331c16 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -260,7 +260,8 @@ Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Documentauto description = ByteString::formatted("{} {}px {}", font.family(), font.pixel_size(), font.weight());Layout::RustFFI::layout_arena_paint_push_bytes(description_sink, reinterpret_cast<u8 const*>(description.characters()), description.length()); },};- Gfx::IntRect device_viewport_rect { {}, document.page().css_to_device_rect(document.viewport_rect()).size().to_type<int>() };+ auto navigable = document.navigable();+ Gfx::IntRect device_viewport_rect { {}, navigable ? navigable->viewport_size_in_device_pixels() : Gfx::IntSize {} };Layout::RustFFI::FfiDisplayListDumpOptions ffi_options {.owners = options.owners,.text = options.text,@@ -471,7 +472,8 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunRe{auto* host = document_host(document);auto device_pixels_per_css_pixel = document.page().client().device_pixels_per_css_pixel();- auto device_viewport_rect = document.page().css_to_device_rect(document.viewport_rect());+ auto navigable_of_document = document.navigable();+ auto device_viewport_rect = navigable_of_document ? navigable_of_document->present_viewport_rect() : Gfx::IntRect {};auto wheel_event_region_state = document.paint_state().collect_root_blocking_wheel_event_regions(document);Layout::RustFFI::FfiRecordingInputs inputs {};Vector<Layout::RustFFI::FfiTextFragmentIndicationRange> text_fragment_indications;@@ -555,7 +557,7 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunRe.text_byte_count = inspector_highlight_label_text.length(),};}- inputs.device_viewport_rect = device_viewport_rect.to_type<int>();+ inputs.device_viewport_rect = device_viewport_rect;if (auto navigable = document.navigable())inputs.css_viewport_rect = navigable->viewport_rect();inputs.should_show_line_box_borders = config.should_show_line_box_borders;@@ -623,7 +625,7 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReinputs.canvas_fill_rect = config.canvas_fill_rect;inputs.canvas_color = CSS::SystemColor::canvas(color_scheme);inputs.opaque_canvas = opaque_canvas;- Gfx::IntRect bitmap_rect { {}, device_viewport_rect.size().to_type<int>() };+ Gfx::IntRect bitmap_rect { {}, device_viewport_rect.size() };inputs.bitmap_rect = bitmap_rect;inputs.background_color = document.background_color(read);}@@ -640,7 +642,7 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReinputs.async_scrolling_metadata = {.has_document_id = true,.document_id = document.unique_id().value(),- .viewport_rect = device_viewport_rect.to_type<int>(),+ .viewport_rect = device_viewport_rect,.wheel_event_listener_state_generation = navigable->page().wheel_event_listener_state_generation(),.has_blocking_wheel_event_listeners = wheel_event_region_state.has_blocking_wheel_event_listeners,.has_blocking_wheel_event_region_covering_viewport = wheel_event_region_state.has_blocking_wheel_event_region_covering_viewport,diff --git a/Libraries/LibWeb/Rust/src/paint_stage.rs b/Libraries/LibWeb/Rust/src/paint_stage.rsindex 58933a7214d..54c0c777f95 100644--- a/Libraries/LibWeb/Rust/src/paint_stage.rs+++ b/Libraries/LibWeb/Rust/src/paint_stage.rs@@ -224,6 +224,9 @@ struct PaintStage {/// What the compositor at the other end of the poster keeps of the display lists sent for each context, which a/// new connection starts without.sent_display_list_chunks: std::collections::HashMap<CompositorContextId, SentDisplayListChunks>,+ /// A clock tick that runs as a context is destroyed can still hand the Paint thread a frame of it after it was+ /// forgotten. No context takes the id of a destroyed one, so its frames are dropped.+ destroyed_context_ids: std::collections::HashSet<CompositorContextId>,}impl PaintStage {@@ -233,8 +236,9 @@ impl PaintStage {}}+static PAINT_THREAD: OnceLock<PaintThread> = OnceLock::new();+fn the_paint_thread() -> &'static PaintThread {- static PAINT_THREAD: OnceLock<PaintThread> = OnceLock::new();PAINT_THREAD.get_or_init(|| PaintThread {thread: StageThread::spawn("Paint",@@ -285,6 +289,10 @@ impl Presenting<'_> {Some((stage.poster.as_ref()?, &mut stage.sent_display_list_chunks))}+ pub(crate) fn context_was_destroyed(&self, context_id: CompositorContextId) -> bool {+ self.stage.destroyed_context_ids.contains(&context_id)+ }+/// Drops the poster of a compositor that can no longer be reached: the connection learns of that on its own thread,/// and hands over the poster of the next one.pub(crate) fn lose_compositor(&mut self) {@@ -345,6 +353,24 @@ pub unsafe extern "C" fn paint_stage_adopt_compositor_poster(poster: FfiThreadSa});}+/// Forgets what the compositor kept of the display lists sent for the context `context_id` names, after the frames+/// handed to the Paint thread before, and drops the frames of the context handed to it after. Only the compositor host+/// calls this, as it destroys the context, which declares it. The compositor never gives a destroyed context's id to+/// another context.+#[unsafe(no_mangle)]+pub extern "C" fn paint_stage_forget_destroyed_compositor_context(context_id: u64) {+ let Some(paint_thread) = PAINT_THREAD.get() else {+ return;+ };+ paint_thread.thread.post(move || {+ Presenting::lend(|presenting| {+ let context_id = CompositorContextId(context_id);+ presenting.stage.sent_display_list_chunks.remove(&context_id);+ presenting.stage.destroyed_context_ids.insert(context_id);+ });+ });+}+/// A screenshot of what the compositor composes for a context (a `Web::Compositor::ScreenshotRequestForPaintThread`), on/// its way to the Paint thread, which asks the compositor for it after the frames handed to it before.struct ScreenshotRequest(NonNull<c_void>);diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rsindex 42d1bbfc609..9faf525c291 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs@@ -13,25 +13,22 @@ use super::dump_format::{DumpNames, DumpValue, dumped_record_field, json_corner_radii, json_fields, json_float, json_float_point,json_float_rect, json_int_rect, json_name, path_description, push_clip_radii, push_fields, push_value,};-use super::effect_clip_plan::EffectClipPlan;-use super::layers::{LayerPlan, LayerPlanInputs, build_layer_plan};+use super::layers::planning::{LayerStackInputs, PlannedLayers, plan_layer_stack};+use super::layers::{LayerIndex, VisualContextNodeNamer, WindowServerPresentationOfMedia};use super::nested_records::{NestedRecordsRole, for_each_command_including_nested, for_each_nested_record_span, span_bytes,};use super::record_fields::visit_command_fields;use super::recorder::{RecordNotes, RecordOrigin};-use super::storage::DisplayListStorage;-use super::summary::{LiveContent, summarize};+use super::storage::{ChunkIndexInList, DisplayListStorage, ListPosition};use crate::layout::LayoutNodeArena;use crate::layout::node_data::NodeSlotId;use crate::painting::dump::{push_affine_transform, push_float_rect};use crate::painting::paint_read::PaintRead;use crate::painting::vector_image_records::display_list_holding_vector_image_records;-use crate::painting::visual_context::VisualContextTree;use crate::painting::visual_context::VisualContextTreeDump;use crate::painting::visual_context::dump::{DumpedNode, SlotKind, tree_section_text};use crate::stage::MainThread;-use libcompositing_rust::host::RecordSpan;use libcompositing_rust::visual_context::CompositorScrollTable;use libgfx_rust::path::Path;use libgfx_rust::{FloatPoint, FloatRect, IntRect};@@ -243,16 +240,12 @@ pub unsafe extern "C" fn painting_dump(.expect("the dump records the document first");// The dump shows the tape as the compositor replays it, with the records of the SVG images it draws.let display_list = DisplayListStorage::recorded(- std::sync::Arc::new(display_list_holding_vector_image_records(- &recording.display_list,- &recording.resources.vector_images,- )),+ &display_list_holding_vector_image_records(&recording.display_list, &recording.resources.vector_images),recording.visual_context_tree.clone().expect("a recording was recorded against a tree"),);- let (tape, command_runs) = (display_list.bytes(), display_list.command_runs());let owners = {crate::painting::ffi::read_arena(host, read, viewport, |arena, viewport| {let mut owners = VisualContextNodeOwners::collect(arena, viewport);@@ -287,8 +280,8 @@ pub unsafe extern "C" fn painting_dump(};let record_ids = options.record_ids- .then(|| RecordIdsOfTopLevelRecords::of(tape, command_runs));- let nodes = visual_context_tree.reachable_nodes_in_print_order(command_runs, &mut names, |kind, index| {+ .then(|| RecordIdsOfTopLevelRecords::of(&display_list));+ let nodes = visual_context_tree.reachable_nodes_in_print_order(display_list.runs(), &mut names, |kind, index| {let owner = owners.owner(kind, index)?;Some(callbacks.debug_description(&main_thread, owner))});@@ -317,12 +310,26 @@ pub unsafe extern "C" fn painting_dump(visual_context_tree.compositor_scroll_table(),options.jsonl,);- let layer_plan = dump_layers_if_list_draws_canvas_video_or_nested_context(- &mut output,+ let scroll_state = host.scroll_state();+ let scroll_offsets = scroll_state.device_offsets();+ let planned_layers = plan_layer_stack(&LayerStackInputs {+ list: &display_list,+ tree: visual_context_tree,+ scroll_offsets,+ viewport_rect: device_viewport_rect,+ });+ let presentation_of_media = planned_layers.stack.window_server_presentation_of_media(&display_list,visual_context_tree,- host.scroll_state().device_offsets(),+ scroll_offsets,device_viewport_rect,+ );+ dump_layers(+ &mut output,+ &mut names,+ &display_list,+ &planned_layers,+ &presentation_of_media,record_ids.as_ref(),options.jsonl,);@@ -344,16 +351,14 @@ pub unsafe extern "C" fn painting_dump(}),font_descriptions,chunk_starts: if options.chunks {- ChunkStart::of_tape(&display_list)+ ChunkStart::of_list(&display_list)} else {- HashMap::new()+ Vec::new()},current_chunk: None,+ layer_label_of_current_top_level_record: String::new(),};- match layer_plan {- Some(layer_plan) => records.dump_top_level_commands_with_their_layers(&display_list, &layer_plan),- None => records.dump_commands(&display_list),- }+ records.dump_top_level_commands_with_their_layers(&display_list, &planned_layers);callbacks.append_text(&main_thread, &output);}@@ -595,144 +600,147 @@ fn dump_compositor_scroll_table(}}-// A list that draws no canvas, video or nested context gets no section.-fn dump_layers_if_list_draws_canvas_video_or_nested_context(+fn dump_layers(output: &mut String,+ names: &mut DumpNames,display_list: &DisplayListStorage,- tree: &VisualContextTree,- scroll_offsets: &[FloatPoint],- device_viewport_rect: IntRect,+ planned_layers: &PlannedLayers,+ presentation_of_media: &WindowServerPresentationOfMedia,record_ids: Option<&RecordIdsOfTopLevelRecords>,jsonl: bool,-) -> Option<LayerPlan> {- let (tape, command_runs) = (display_list.bytes(), display_list.command_runs());- let summary = summarize(tape, command_runs);- let draws_canvas_video_or_nested_context = summary- .live_content_records- .iter()- .any(|live_content_record| !matches!(live_content_record.content, LiveContent::ImageFrame(_)));- if !draws_canvas_video_or_nested_context {- return None;- }- let effect_clips =- EffectClipPlan::new(tree, command_runs).expect("a display list's runs name live nodes of its tree");- let layer_plan = build_layer_plan(&LayerPlanInputs {- tape,- command_runs,- summary: &summary,- effect_clips: &effect_clips,- tree,- scroll_offsets,- viewport_rect: device_viewport_rect,+) {+ let record_id_ranges_by_layer = record_ids.map(|record_ids| {+ record_ids.record_id_ranges_by_layer_joining_adjacent_ranges(planned_layers.stack.layers.len(), |position| {+ let (header, _) = display_list.record_at(position);+ layers_labelling_top_level_record(planned_layers, &header, position)+ })});- match layer_plan {- Ok(layer_plan) if jsonl => {- for (index, layer) in layer_plan.layers.iter().enumerate() {- let mut object = serde_json::Map::new();- object.insert("type".into(), serde_json::json!("layer"));- object.insert("name".into(), serde_json::json!(format!("L{index}")));- object.insert("kind".into(), serde_json::json!(layer.kind.to_string()));- object.insert("rect".into(), json_int_rect(layer.rect));- if let Some(record_ids) = record_ids {- object.insert("records".into(), record_ids.json_spans(&layer.record_spans));- }- match &layer.window_server_placement {- Some(Ok(placement)) => {- object.insert(- "shown_by_the_window_server".into(),- serde_json::json!(placement.to_string()),- );- }- Some(Err(rejection)) => {- object.insert("replayed".into(), serde_json::json!(rejection.to_string()));- }- None => {}- }- push_json_line(output, serde_json::Value::Object(object));+ let names = DumpNodeNamer(std::cell::RefCell::new(names));+ if jsonl {+ for (layer, line) in planned_layers.layer_lines(presentation_of_media, &names, |_| None) {+ let mut object = serde_json::Map::new();+ object.insert("type".into(), serde_json::json!("layer"));+ if let Some(layer) = layer {+ object.insert("name".into(), serde_json::json!(format!("L{}", layer.0)));}- Some(layer_plan)- }- Err(unlayered_reason) if jsonl => {- push_json_line(- output,- serde_json::json!({ "type": "unlayered", "reason": unlayered_reason.to_string() }),- );- None- }- Ok(layer_plan) => {- output.push_str("\nLayers:\n");- layer_plan- .write_layer_lines(output, " ", |spans| {- record_ids.map(|record_ids| record_ids.describe_spans(spans))- })- .unwrap();- Some(layer_plan)- }- Err(unlayered_reason) => {- writeln!(output, "\nLayers: none ({unlayered_reason})").unwrap();- None+ object.insert("line".into(), serde_json::json!(line));+ if let (Some(layer), Some(ranges)) = (layer, &record_id_ranges_by_layer) {+ object.insert("records".into(), json_record_id_ranges(&ranges[layer.0]));+ }+ push_json_line(output, serde_json::Value::Object(object));}+ return;+ }+ output.push_str("\nLayers:\n");+ let describe_records = |layer: LayerIndex| {+ record_id_ranges_by_layer+ .as_ref()+ .map(|ranges| describe_record_id_ranges(&ranges[layer.0]))+ };+ for (_, line) in planned_layers.layer_lines(presentation_of_media, &names, describe_records) {+ writeln!(output, " {line}").unwrap();+ }+}++struct DumpNodeNamer<'a>(std::cell::RefCell<&'a mut DumpNames>);++impl VisualContextNodeNamer for DumpNodeNamer<'_> {+ fn name_of_spatial_node(&self, index: SpatialNodeIndex) -> String {+ self.0.borrow_mut().spatial(index)+ }++ fn name_of_effect_node(&self, index: EffectNodeIndex) -> String {+ self.0.borrow_mut().effect(index)}}-/// The number of each top-level record of a tape, which counts the records nested in the ones before it too.+fn layers_labelling_top_level_record(+ planned_layers: &PlannedLayers,+ header: &DisplayListCommandHeader,+ position: ListPosition,+) -> Vec<LayerIndex> {+ let mut layers = if header.command_type.is_compositor_metadata() {+ Vec::new()+ } else {+ planned_layers.layers_of_record(position)+ };+ if layers.is_empty() {+ layers.push(planned_layers.stack.base_layer);+ }+ layers+}++/// The numbers of the records of a list, nested ones too, in paint order, by the top-level record that holds them.struct RecordIdsOfTopLevelRecords {- ids_by_offset: HashMap<u32, u32>,+ // In paint order: where each top-level record is, with the numbers of the first and the last record it holds.+ top_level_records: Vec<(ListPosition, u32, u32)>,record_count: u32,- tape_size: u32,}impl RecordIdsOfTopLevelRecords {- fn of(tape: &[u8], command_runs: &[DisplayListCommandRun]) -> Self {- let mut ids_by_offset = HashMap::new();+ fn of(display_list: &DisplayListStorage) -> Self {+ let mut top_level_records = Vec::new();let mut record_count = 0;- for run in command_runs {- let run_bytes = &tape[run.offset as usize..(run.offset + run.size) as usize];- for_each_command(run_bytes, |_, offset_in_run, payload| {- ids_by_offset.insert(run.offset + offset_in_run as u32, record_count + 1);- let record_bytes = &run_bytes[offset_in_run..offset_in_run + HEADER_SIZE + payload.len()];- for_each_command_including_nested(record_bytes, &mut |_, _, _| record_count += 1);- });+ for (chunk_index, chunk) in display_list.chunks().iter().enumerate() {+ for run in chunk.runs() {+ let run_bytes = &chunk.records()[run.offset as usize..(run.offset + run.size) as usize];+ for_each_command(run_bytes, |_, offset_in_run, payload| {+ let first_id = record_count + 1;+ let record_bytes = &run_bytes[offset_in_run..offset_in_run + HEADER_SIZE + payload.len()];+ for_each_command_including_nested(record_bytes, &mut |_, _, _| record_count += 1);+ let position =+ ListPosition::new(ChunkIndexInList(chunk_index as u32), run.offset + offset_in_run as u32);+ top_level_records.push((position, first_id, record_count));+ });+ }}Self {- ids_by_offset,+ top_level_records,record_count,- tape_size: tape.len() as u32,}}- fn id_at(&self, offset: u32) -> u32 {- if offset == self.tape_size {- return self.record_count + 1;+ fn record_id_ranges_by_layer_joining_adjacent_ranges(+ &self,+ layer_count: usize,+ layers_of_top_level_record: impl Fn(ListPosition) -> Vec<LayerIndex>,+ ) -> Vec<Vec<(u32, u32)>> {+ let mut ranges_by_layer: Vec<Vec<(u32, u32)>> = vec![Vec::new(); layer_count];+ for &(position, first_id, last_id) in &self.top_level_records {+ for layer in layers_of_top_level_record(position) {+ let ranges = &mut ranges_by_layer[layer.0];+ match ranges.last_mut() {+ Some(range) if range.1 + 1 == first_id => range.1 = last_id,+ _ => ranges.push((first_id, last_id)),+ }+ }}- self.ids_by_offset[&offset]+ ranges_by_layer}+}- fn json_spans(&self, spans: &[RecordSpan]) -> serde_json::Value {- serde_json::Value::Array(- spans- .iter()- .map(|span| serde_json::json!([self.id_at(span.begin_offset), self.id_at(span.end_offset) - 1]))- .collect(),- )- }+fn json_record_id_ranges(ranges: &[(u32, u32)]) -> serde_json::Value {+ serde_json::Value::Array(+ ranges+ .iter()+ .map(|(first, last)| serde_json::json!([first, last]))+ .collect(),+ )+}- // Spans of top-level records as the ranges of the numbers of every record they hold.- fn describe_spans(&self, spans: &[RecordSpan]) -> String {- let mut text = String::new();- for (index, span) in spans.iter().enumerate() {- if index > 0 {- text.push(',');- }- let (first, last) = (self.id_at(span.begin_offset), self.id_at(span.end_offset) - 1);- if first == last {- write!(text, "#{first}").unwrap();- } else {- write!(text, "#{first}-#{last}").unwrap();- }+fn describe_record_id_ranges(ranges: &[(u32, u32)]) -> String {+ let mut text = String::new();+ for (index, (first, last)) in ranges.iter().enumerate() {+ if index > 0 {+ text.push(',');+ }+ if first == last {+ write!(text, "#{first}").unwrap();+ } else {+ write!(text, "#{first}-#{last}").unwrap();}- text}+ text}/// What the recording noted of a record, as the dump prints it.@@ -828,12 +836,13 @@ struct RecordDump<'a> {record_notes: Option<RecordNotesInDumpOrder>,// The descriptions of the fonts the glyph runs draw with, by their ids, where the dump prints them.font_descriptions: Option<HashMap<u64, String>>,- // The chunks of the tape by the index of their first run, where the dump marks them.- chunk_starts: HashMap<usize, ChunkStart>,+ // The chunks of the list in paint order, where the dump marks them.+ chunk_starts: Vec<ChunkStart>,current_chunk: Option<String>,+ layer_label_of_current_top_level_record: String,}-/// Where a chunk of the tape starts, with what it holds.+/// Where a chunk of the list starts, with what it holds.struct ChunkStart {name: String,id: ChunkId,@@ -842,39 +851,36 @@ struct ChunkStart {}impl ChunkStart {- fn of_tape(display_list: &DisplayListStorage) -> HashMap<usize, Self> {- let (bytes, command_runs, chunks) = (display_list.bytes(), display_list.command_runs(), display_list.chunks());- (0..chunks.len())- .map(|chunk_index| {- let runs = &command_runs[chunks.runs_of(chunk_index)];+ fn of_list(display_list: &DisplayListStorage) -> Vec<Self> {+ display_list+ .chunks()+ .iter()+ .enumerate()+ .map(|(chunk_index, chunk)| {let mut record_count = 0;- for run in runs {+ for run in chunk.runs() {for_each_command_including_nested(- &bytes[run.offset as usize..(run.offset + run.size) as usize],+ &chunk.records()[run.offset as usize..(run.offset + run.size) as usize],&mut |_, _, _| record_count += 1,);}- (- chunks.runs_of(chunk_index).start,- Self {- name: format!("k{}", chunk_index + 1),- id: chunks.id(chunk_index),- record_count,- byte_count: runs.iter().map(|run| run.size).sum(),- },- )+ Self {+ name: format!("k{}", chunk_index + 1),+ id: chunk.id,+ record_count,+ byte_count: chunk.runs().iter().map(|run| run.size).sum(),+ }}).collect()}}-/// Where a record sits: how deep in other records, in which of them and as what, and in which layer.+/// Where a record sits: how deep in other records, and in which of them and as what.#[derive(Clone, Copy)]struct RecordPlace {indent: usize,depth: usize,nested_in: Option<(u32, NestedRecordsRole)>,- layer: Option<usize>,// The records of an SVG image take the origin of the record that draws the image.origin_of_enclosing_vector_image: Option<Option<RecordOrigin>>,}@@ -884,7 +890,6 @@ impl RecordPlace {indent: 0,depth: 0,nested_in: None,- layer: None,origin_of_enclosing_vector_image: None,};}@@ -901,8 +906,8 @@ fn nested_records_role_name(role: NestedRecordsRole) -> &'static str {}impl RecordDump<'_> {- fn mark_chunk_starting_at(&mut self, run_index: usize) {- let Some(chunk) = self.chunk_starts.get(&run_index) else {+ fn mark_chunk_start(&mut self, chunk_index: usize) {+ let Some(chunk) = self.chunk_starts.get(chunk_index) else {return;};if self.jsonl {@@ -931,45 +936,44 @@ impl RecordDump<'_> {self.current_chunk = Some(chunk.name.clone());}- fn dump_commands(&mut self, display_list: &DisplayListStorage) {- let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());- for (run_index, run) in command_runs.iter().enumerate() {- self.mark_chunk_starting_at(run_index);- let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];- self.dump_command_bytes(run_bytes, run.context, RecordPlace::TOP_LEVEL);- }- }-- // Each top-level command starts with the layer it draws into. The records nested in it draw into the same layer.- fn dump_top_level_commands_with_their_layers(&mut self, display_list: &DisplayListStorage, layer_plan: &LayerPlan) {- let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());- for (run_index, run) in command_runs.iter().enumerate() {- self.mark_chunk_starting_at(run_index);- let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];- for_each_command(run_bytes, |_, offset_in_run, payload| {- let layer = layer_plan.layer_of_record(run.offset + offset_in_run as u32);- let record_bytes = &run_bytes[offset_in_run..offset_in_run + HEADER_SIZE + payload.len()];- let place = RecordPlace {- layer: Some(layer),- ..RecordPlace::TOP_LEVEL- };- if self.jsonl {- self.dump_command_bytes(record_bytes, run.context, place);- return;- }- let layer_label = format!("L{layer} ");- let record_dump_start = self.output.len();- self.dump_command_bytes(record_bytes, run.context, place);- let record_dump = self.output.split_off(record_dump_start);- for (line_index, line) in record_dump.split_inclusive('\n').enumerate() {- if line_index == 0 {- self.output.push_str(&layer_label);- } else {- self.output.extend(std::iter::repeat_n(' ', layer_label.len()));+ // A top-level command can be drawn into several layers, one per tile, where a canvas, video or another space sits+ // between it and what is painted before it. Its nested records draw into the same layers.+ fn dump_top_level_commands_with_their_layers(+ &mut self,+ display_list: &DisplayListStorage,+ planned_layers: &PlannedLayers,+ ) {+ for (chunk_index, chunk) in display_list.chunks().iter().enumerate() {+ self.mark_chunk_start(chunk_index);+ for run in chunk.runs() {+ let run_bytes = &chunk.records()[run.offset as usize..(run.offset + run.size) as usize];+ for_each_command(run_bytes, |header, offset_in_run, payload| {+ let position =+ ListPosition::new(ChunkIndexInList(chunk_index as u32), run.offset + offset_in_run as u32);+ let layer_names: Vec<String> = layers_labelling_top_level_record(planned_layers, header, position)+ .iter()+ .map(|layer| format!("L{}", layer.0))+ .collect();+ self.layer_label_of_current_top_level_record = layer_names.join(",");+ let record_bytes = &run_bytes[offset_in_run..offset_in_run + HEADER_SIZE + payload.len()];+ if self.jsonl {+ self.dump_command_bytes(record_bytes, run.context, RecordPlace::TOP_LEVEL);+ return;}- self.output.push_str(line);- }- });+ let layer_label = format!("{} ", self.layer_label_of_current_top_level_record);+ let record_dump_start = self.output.len();+ self.dump_command_bytes(record_bytes, run.context, RecordPlace::TOP_LEVEL);+ let record_dump = self.output.split_off(record_dump_start);+ for (line_index, line) in record_dump.split_inclusive('\n').enumerate() {+ if line_index == 0 {+ self.output.push_str(&layer_label);+ } else {+ self.output.extend(std::iter::repeat_n(' ', layer_label.len()));+ }+ self.output.push_str(line);+ }+ });+ }}}@@ -1051,7 +1055,6 @@ impl RecordDump<'_> {indent: nested_indent,depth: place.depth + 1,nested_in: Some((record_id, role)),- layer: place.layer,origin_of_enclosing_vector_image,},);@@ -1113,9 +1116,7 @@ impl RecordDump<'_> {record.insert("parent".into(), json!(parent_id));record.insert("role".into(), json!(nested_records_role_name(role)));}- if let Some(layer) = place.layer {- record.insert("layer".into(), json!(format!("L{layer}")));- }+ record.insert("layer".into(), json!(self.layer_label_of_current_top_level_record));if let Some(chunk) = &self.current_chunk {record.insert("chunk".into(), json!(chunk));}@@ -1306,6 +1307,7 @@ mod tests {use super::*;use crate::painting::display_list::builder::DisplayListBuilder;use crate::painting::display_list::builder::{HEADER_SIZE, read_header};+ use crate::painting::visual_context::VisualContextTree;use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};#[test]@@ -1384,7 +1386,7 @@ mod tests {}#[test]- fn record_ids_count_nested_records_and_name_spans_of_top_level_records() {+ fn record_ids_count_nested_records_and_join_adjacent_records_of_a_layer() {let fill = FillRect {rect: IntRect::new(0, 0, 10, 10),color: Color::from_rgba(0, 0, 0, 255),@@ -1407,17 +1409,27 @@ mod tests {};builder.finish_group(group, &group_command, ContextRef::default());builder.append(&fill, &[], ContextRef::default());- let (tape, runs) = (builder.bytes(), builder.command_runs());- let record_ids = RecordIdsOfTopLevelRecords::of(tape, runs);- let mut top_level_offsets = Vec::new();- for_each_command(tape, |_, offset, _| top_level_offsets.push(offset as u32));- let span = |begin: usize, end: Option<usize>| RecordSpan {- begin_offset: top_level_offsets[begin],- end_offset: end.map_or(tape.len() as u32, |end| top_level_offsets[end]),- };- assert_eq!(record_ids.describe_spans(&[span(0, Some(1))]), "#1");- assert_eq!(record_ids.describe_spans(&[span(1, Some(2))]), "#2-#4");- assert_eq!(record_ids.describe_spans(&[span(0, Some(1)), span(2, None)]), "#1,#5");+ let display_list = DisplayListStorage::recorded(+ &builder.finish(),+ std::sync::Arc::new(VisualContextTree::create_identity()),+ );+ let record_ids = RecordIdsOfTopLevelRecords::of(&display_list);+ let positions: Vec<ListPosition> = record_ids+ .top_level_records+ .iter()+ .map(|&(position, _, _)| position)+ .collect();+ let ranges = record_ids.record_id_ranges_by_layer_joining_adjacent_ranges(3, |position| {+ match positions.iter().position(|&top_level| top_level == position) {+ Some(0) => vec![LayerIndex(0)],+ Some(1) => vec![LayerIndex(1), LayerIndex(2)],+ _ => vec![LayerIndex(0), LayerIndex(2)],+ }+ });+ assert_eq!(record_ids.record_count, 5);+ assert_eq!(describe_record_id_ranges(&ranges[0]), "#1,#5");+ assert_eq!(describe_record_id_ranges(&ranges[1]), "#2-#4");+ assert_eq!(describe_record_id_ranges(&ranges[2]), "#2-#5");}#[test]diff --git a/Libraries/LibWeb/Rust/src/painting/presentation.rs b/Libraries/LibWeb/Rust/src/painting/presentation.rsindex c92da1ecf4b..1a50fe46f2a 100644--- a/Libraries/LibWeb/Rust/src/painting/presentation.rs+++ b/Libraries/LibWeb/Rust/src/painting/presentation.rs@@ -14,6 +14,9 @@use crate::paint_stage::Presenting;use crate::painting::display_list::chunks::{Chunk, ChunkId, KeptChunks};use crate::painting::display_list::commands::CompositorContextId;+use crate::painting::display_list::layers::planning::InputsOfLayerPlan;+use crate::painting::display_list::layers::{LayerPlan, compositor_takes_plans_within};+use crate::painting::display_list::storage::{DisplayListStorage, ListChunk};use crate::painting::display_list_resources::DisplayListResources;use crate::painting::paint_passes::ClockTickVisualContexts;use crate::painting::record::RecordingOutput;@@ -26,7 +29,7 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{};use libcompositing_rust::ipc_types::{Compositing_AsyncScrollingMetadata, Compositing_DisplayListProperties, Compositing_KeyboardScrollState,- Compositing_ScrollRequest,+ Compositing_ScrollRequest, LayerPlanOnWire,};use libcompositing_rust::scrolling::ScrollStateSnapshot;use libgfx_rust::IntRect;@@ -557,6 +560,7 @@ impl Presentation {let mut frame = state.build_frame(&self.seal, None, &tree, &self.scroll_state);frame.scroll_requests = std::mem::take(&mut self.seal.scroll_requests);state.note_presented(&mut self.seal, &self.scroll_state);+ drop(state);presenting.post_frame(frame);}@@ -591,6 +595,7 @@ impl Presentation {self.seal.published = Some(output.clone());frame.scroll_requests = std::mem::take(&mut self.seal.scroll_requests);state.note_presented(&mut self.seal, &self.scroll_state);+ drop(state);presenting.post_frame(frame);}}@@ -606,8 +611,12 @@ fn post_resources_ahead(}impl Presenting<'_> {- /// Hands `frame` to the compositor, or drops it while the compositor cannot be reached.+ /// Hands `frame` to the compositor, or drops it while the compositor cannot be reached or where its context was+ /// destroyed.fn post_frame(&mut self, frame: CompositorFrame) {+ if self.context_was_destroyed(frame.context_id) {+ return;+ }let Some((poster, sent_display_list_chunks)) = self.poster_and_sent_display_list_chunks() else {return;};@@ -618,11 +627,38 @@ impl Presenting<'_> {}/// What the compositor keeps of the display lists sent for one context, which a display list sends the chunks it lacks-/// of, and the chunks that draw SVG images as they were sent, with the records of the images in them.+/// of, and the chunks that draw SVG images as they were sent, with the records of the images in them. Beside those, the+/// list the compositor holds and the plan of its layers, which the Paint thread plans as it sends what the plan reads.#[derive(Default)]pub(crate) struct SentDisplayListChunks {kept: KeptChunks,holding_vector_image_records: HashMap<ChunkId, Arc<Chunk>>,+ /// The chunks the compositor keeps as it replays them, with what plans of layers work out of each chunk alone,+ /// which the lists of those chunks share.+ list_chunks: HashMap<ChunkId, Arc<ListChunk>>,+ /// The display list sent last, as the compositor replays it.+ held_list: Option<DisplayListSent>,+}++struct DisplayListSent {+ display_list_id: u64,+ recorded_structural_epoch: u64,+ list: Arc<DisplayListStorage>,+ /// The plan of its layers sent last with it, a visual context tree or a scroll state, or none where it or the tree+ /// sent last went without one.+ layer_plan: Option<LayerPlanSent>,+}++/// A plan of layers sent to the compositor, and what it was made from.+struct LayerPlanSent {+ inputs: InputsOfLayerPlan,+ plan: Arc<LayerPlan>,+}++impl LayerPlanSent {+ fn on_wire(&self) -> LayerPlanOnWire {+ LayerPlanOnWire::Planned(self.plan.clone())+ }}impl SentDisplayListChunks {@@ -655,6 +691,115 @@ impl SentDisplayListChunks {self.kept.take_in(chunks_in_paint_order);let kept = &self.kept;self.holding_vector_image_records.retain(|_, sent| kept.keeps(sent.id));+ self.list_chunks.retain(|id, _| kept.keeps(*id));+ }++ /// The display list of `chunks_as_sent` as the compositor replays it: the same chunks in the same order, so that a+ /// position in it names the same record in both processes.+ fn list_as_sent(&mut self, chunks_as_sent: &[Arc<Chunk>]) -> Option<Arc<DisplayListStorage>> {+ let chunks = chunks_as_sent+ .iter()+ .map(|chunk| {+ self.list_chunks+ .entry(chunk.id)+ .or_insert_with(|| Arc::new(ListChunk::of_chunk_made_in_this_process(chunk)))+ .clone()+ })+ .collect();+ DisplayListStorage::of_chunks(chunks).ok()+ }++ fn held_layer_plan(&self) -> Option<&LayerPlanSent> {+ self.held_list.as_ref()?.layer_plan.as_ref()+ }++ /// The plan of the layers of `list`, which `display_list_id` names, under the other inputs: the plan sent last, where+ /// it was made from inputs that plan alike, and a new one otherwise.+ fn layer_plan_of(+ &self,+ display_list_id: u64,+ list: Arc<DisplayListStorage>,+ visual_context_tree: Arc<VisualContextTree>,+ scroll_state: &ScrollStateSnapshot,+ viewport_rect: IntRect,+ ) -> LayerPlanSent {+ let held_plan = self.held_layer_plan();+ let inputs = InputsOfLayerPlan::new_after(+ held_plan.map(|held| &held.inputs),+ list,+ visual_context_tree,+ scroll_state.device_offsets(),+ viewport_rect,+ );+ match held_plan {+ Some(held) if held.inputs.plan_alike_as(&inputs) => LayerPlanSent {+ plan: if held.plan.display_list_id == display_list_id {+ held.plan.clone()+ } else {+ Arc::new(LayerPlan {+ display_list_id,+ ..(*held.plan).clone()+ })+ },+ inputs,+ },+ _ => layer_plan_made_from(display_list_id, inputs),+ }+ }++ /// The plan of the layers of the display list the compositor holds under `visual_context_tree`, or none where the+ /// tree does not fit that list, which the compositor then drops.+ fn layer_plan_of_held_list_under(+ &self,+ visual_context_tree: &Arc<VisualContextTree>,+ scroll_state: &ScrollStateSnapshot,+ viewport_rect: IntRect,+ ) -> Option<LayerPlanSent> {+ let held = self.held_list.as_ref()?;+ if visual_context_tree.structural_epoch != held.recorded_structural_epoch+ || !visual_context_tree.display_list_references_only_live_nodes(held.list.runs())+ {+ return None;+ }+ Some(self.layer_plan_of(+ held.display_list_id,+ held.list.clone(),+ visual_context_tree.clone(),+ scroll_state,+ viewport_rect,+ ))+ }++ /// A new plan of the layers the compositor holds a plan of, where `scroll_state` or `viewport_rect_of_frame`, the+ /// rect the frame is presented within if it is presented, changed what that plan reads. A scroll state without a+ /// plan keeps the plan the compositor holds, and a display list or a tree without one leaves it with none. The+ /// compositor draws a frame within a viewport it takes no plan within as one layer, so such a frame gets no plan.+ fn layer_plan_for_scroll_state(+ &self,+ scroll_state: &ScrollStateSnapshot,+ viewport_rect_of_frame: Option<IntRect>,+ ) -> Option<LayerPlanSent> {+ let held = self.held_layer_plan()?;+ let viewport_rect = viewport_rect_of_frame.unwrap_or(held.inputs.viewport_rect());+ if !compositor_takes_plans_within(viewport_rect) {+ return None;+ }+ let inputs = held+ .inputs+ .with_scroll_offsets_and_viewport_rect(scroll_state.device_offsets(), viewport_rect);+ (!held.inputs.plan_alike_as(&inputs)).then(|| layer_plan_made_from(held.plan.display_list_id, inputs))+ }+}++fn layer_plan_made_from(display_list_id: u64, inputs: InputsOfLayerPlan) -> LayerPlanSent {+ let planned = inputs.plan();+ LayerPlanSent {+ plan: Arc::new(LayerPlan {+ display_list_id,+ viewport_rect: inputs.viewport_rect(),+ stack: planned.stack,+ }),+ inputs,}}@@ -674,12 +819,18 @@ fn post_frame_through(scroll_requests,present_viewport_rect,} = frame;+ // A plan is made for the rect the compositor rasters the frame within: at the origin, at the size of the viewport the+ // frame is presented in.+ let viewport_rect_of_frame =+ present_viewport_rect.map(|viewport_rect| IntRect::new(0, 0, viewport_rect.width, viewport_rect.height));+ let viewport_rect_of_layer_plans =+ viewport_rect_of_frame.filter(|viewport_rect| compositor_takes_plans_within(*viewport_rect));+ let sent = sent_display_list_chunks.entry(context_id).or_default();if let Some(update) = display_list_update {if !post_resources_ahead(poster, context_id, &update.resources) {return false;}// The compositor replays chunks with the records of the SVG images they draw in them.- let sent = sent_display_list_chunks.entry(context_id).or_default();let vector_images = &update.output.resources.vector_images;let chunks_as_sent: Vec<Arc<Chunk>> = update.output@@ -689,6 +840,8 @@ fn post_frame_through(.collect();let chunks_in_paint_order: Vec<ChunkId> = chunks_as_sent.iter().map(|chunk| chunk.id).collect();let new_chunks = sent.new_chunks(&chunks_as_sent);+ let display_list_id = update.properties.id;+ let recorded_structural_epoch = update.properties.compatible_visual_context_tree_structural_epoch;match poster.share_display_list(chunks_in_paint_order.clone(),&new_chunks,@@ -696,16 +849,36 @@ fn post_frame_through(Some(update.async_scrolling_metadata),) {Some(display_list) => {+ let list = sent.list_as_sent(&chunks_as_sent);+ let layer_plan = list+ .clone()+ .zip(viewport_rect_of_layer_plans)+ .map(|(list, viewport_rect)| {+ sent.layer_plan_of(+ display_list_id,+ list,+ update.visual_context_tree.clone(),+ &update.scroll_state,+ viewport_rect,+ )+ });let message = UpdateDisplayList {context_id,display_list,visual_context_tree: update.visual_context_tree,scroll_state: update.scroll_state,+ layer_plan: layer_plan.as_ref().map(LayerPlanSent::on_wire),};if !poster.post(message) {return false;}sent.take_in(&chunks_in_paint_order);+ sent.held_list = list.map(|list| DisplayListSent {+ display_list_id,+ recorded_structural_epoch,+ list,+ layer_plan,+ });}None => {eprintln!(@@ -719,25 +892,39 @@ fn post_frame_through(if !post_resources_ahead(poster, context_id, &update.resources) {return false;}+ let layer_plan = viewport_rect_of_layer_plans.and_then(|viewport_rect| {+ sent.layer_plan_of_held_list_under(&update.visual_context_tree, &update.scroll_state, viewport_rect)+ });let message = UpdateVisualContextTree {context_id,visual_context_tree: update.visual_context_tree,scroll_state: update.scroll_state,keyboard_scroll_state: update.keyboard_scroll_state,+ layer_plan: layer_plan.as_ref().map(LayerPlanSent::on_wire),};if !poster.post(message) {return false;}+ if let Some(held) = sent.held_list.as_mut() {+ held.layer_plan = layer_plan;+ }}if let Some(update) = scroll_state_update {+ let layer_plan = sent.layer_plan_for_scroll_state(&update.scroll_state, viewport_rect_of_frame);let message = UpdateScrollState {context_id,scroll_state: update.scroll_state,keyboard_scroll_state: update.keyboard_scroll_state,+ layer_plan: layer_plan.as_ref().map(LayerPlanSent::on_wire),};if !poster.post(message) {return false;}+ if let Some(layer_plan) = layer_plan+ && let Some(held) = sent.held_list.as_mut()+ {+ held.layer_plan = Some(layer_plan);+ }}if !scroll_requests.is_empty()&& !poster.post(ApplyScrollRequests {@@ -833,3 +1020,58 @@ pub extern "C" fn navigable_presenter_last_keyboard_scroll_state_generation(*out = generation;true}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::painting::display_list::builder::DisplayListBuilder;+ use crate::painting::display_list::commands::{ContextRef, EffectNodeIndex, FillRect};+ use libgfx_rust::{Color, CompositingAndBlendingOperator};++ // A window can be dragged larger than the viewports the compositor takes plans within.+ #[test]+ fn a_frame_presented_within_a_viewport_the_compositor_takes_no_plan_within_gets_no_plan_for_its_scroll_state() {+ let mut builder = DisplayListBuilder::new();+ builder.append(+ &FillRect {+ rect: IntRect::new(0, 0, 800, 600),+ color: Color::from_rgb(0, 128, 0),+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ },+ &[],+ ContextRef::default(),+ );+ let list = DisplayListStorage::of_chunks(vec![Arc::new(ListChunk::copied(+ builder.bytes(),+ builder.command_runs(),+ 0,+ ))])+ .unwrap();+ let tree = Arc::new(VisualContextTree::create_identity());+ let viewport_rect = IntRect::new(0, 0, 800, 600);+ let sent = SentDisplayListChunks {+ held_list: Some(DisplayListSent {+ display_list_id: 1,+ recorded_structural_epoch: tree.structural_epoch,+ list: list.clone(),+ layer_plan: Some(layer_plan_made_from(+ 1,+ InputsOfLayerPlan::new(list, tree, &[], viewport_rect),+ )),+ }),+ ..SentDisplayListChunks::default()+ };+ let scroll_state = ScrollStateSnapshot::default();+ assert!(+ sent.layer_plan_for_scroll_state(&scroll_state, Some(IntRect::new(0, 0, 800, 500)))+ .is_some()+ );+ let viewport_past_the_limit = IntRect::new(0, 0, i32::MAX, 600);+ assert!(!compositor_takes_plans_within(viewport_past_the_limit));+ assert!(+ sent.layer_plan_for_scroll_state(&scroll_state, Some(viewport_past_the_limit))+ .is_none()+ );+ }+}diff --git a/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rs b/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rsindex 7b10ea1dd20..ce94d418e29 100644--- a/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rs+++ b/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rs@@ -37,7 +37,7 @@ fn display_list_of(let tree = output.visual_context_tree.clone()?;let properties = display_list_properties_of(output);let display_list = DisplayList::new(- DisplayListStorage::recorded(output.display_list.clone(), tree.clone()),+ DisplayListStorage::recorded(&output.display_list, tree.clone()),properties.id,properties.compatible_visual_context_tree_structural_epoch,output.async_scrolling_metadata.clone(),diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rsindex 1aae999278f..c2c16a62082 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs@@ -82,9 +82,9 @@ pub trait VisualContextTreeDump {fn describe_effect_node(&self, index: EffectNodeIndex, names: &mut DumpNames) -> String;// The nodes the runs record under, each tree in first-seen order. An effect's output clip// chain counts as reachable, since replay enters it before the effect.- fn reachable_nodes_in_print_order(+ fn reachable_nodes_in_print_order<'a>(&self,- command_runs: &[DisplayListCommandRun],+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun> + Clone,names: &mut DumpNames,owner_label: impl FnMut(SlotKind, u32) -> Option<String>,) -> Vec<DumpedNode>;@@ -305,14 +305,15 @@ impl VisualContextTreeDump for VisualContextTree {text}- fn reachable_nodes_in_print_order(+ fn reachable_nodes_in_print_order<'a>(&self,- command_runs: &[DisplayListCommandRun],+ command_runs: impl IntoIterator<Item = &'a DisplayListCommandRun> + Clone,names: &mut DumpNames,mut owner_label: impl FnMut(SlotKind, u32) -> Option<String>,) -> Vec<DumpedNode> {- let effect_clips = crate::painting::display_list::effect_clip_plan::EffectClipPlan::new(self, command_runs)- .expect("dumped command runs reference live visual context nodes");+ let effect_clips =+ crate::painting::display_list::effect_clip_plan::EffectClipPlan::new(self, command_runs.clone())+ .expect("dumped command runs reference live visual context nodes");let mut visited_spatial_nodes: HashSet<u32> = HashSet::new();let mut visited_clip_nodes: HashSet<u32> = HashSet::new();let mut visited_effect_nodes: HashSet<u32> = HashSet::new();@@ -492,8 +493,8 @@ mod node_dump_tests {use crate::painting::visual_context::{AnchorScrollShift, BackdropFilterData, BackfaceVisibilityData, ClipData, ClipMode, ClipNodeData, ClipNodeIndex,EffectNodeData, EffectNodeIndex, EffectsData, MaskData, MaskLayerOrigin, PerspectiveData, ScrollData,- SpatialData, StickyData, TransformData, TransformDataRole, VISUAL_VIEWPORT_NODE_INDEX, VisualContextTree,- scroll_state::NO_SCROLL_STATE_SLOT,+ SpatialData, StickyData, TransformData, TransformDataRole, UniqueNodeId, VISUAL_VIEWPORT_NODE_INDEX,+ VisualContextTree, scroll_state::NO_SCROLL_STATE_SLOT,};use libgfx_rust::{CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect,@@ -586,6 +587,8 @@ mod node_dump_tests {inset_right: None,inset_bottom: Some(1.5),inset_left: None,+ box_node_id: UniqueNodeId(0),+ box_pseudo_element_type: 0,state_slot: NO_SCROLL_STATE_SLOT,owner_paintable: NodeSlotId::INVALID,}),diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/refresh.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/refresh.rsindex 3e9c24374a5..b45ffa3df01 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_context/refresh.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/refresh.rs@@ -5,7 +5,7 @@*/use super::scroll_state::{NO_SCROLL_STATE_SLOT, ScrollState, ScrollStateSlot};-use super::{SpatialData, StickyData, VisualContextTree};+use super::{SpatialData, StickyData, UniqueNodeId, VisualContextTree};use crate::css::computed_value_types::ComputedLengthPercentageOrAuto;use crate::css::css_pixels::{CssPixelPoint, CssPixelRect, CssPixelSize, CssPixels};use crate::layout::geometry::{Frame, Side};@@ -182,6 +182,8 @@ pub(crate) fn compute_sticky_data(if !layout_arena.paintable_row_is_populated(paintable) || !layout_arena.paintable_row_is_populated(scroller) {return data;}+ data.box_node_id = UniqueNodeId(layout_arena.unique_node_ids().id(paintable));+ data.box_pseudo_element_type = layout_arena.node_generated_for(paintable).saturating_sub(1);// NB: Only scroll containers with scrollable overflow, or that keep their scrolls, get a scroll node. When the// nearest scroll container has none, it sits inside the scroller of the scroll node, and its scrollport neverdiff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 184dee90db2..238cd20b9fe 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -51,11 +51,12 @@ endpoint CompositorWebContentServer// The fonts that a display list draws go ahead of it, in describe_display_list_fonts. The context keeps the fonts// and the image frames that its display list and its visual context tree draw. Only Rust sends and receives the- // display lists, the visual context trees and the scroll state snapshots.- [RustReceiver, RustSender] update_display_list(Web::CompositorContextId context_id, Compositing::DisplayList display_list, Compositing::VisualContextTree visual_context_tree, Compositing::ScrollStateSnapshot scroll_state) =|+ // display lists, the visual context trees, the scroll state snapshots and the plans of layers. A display list or a+ // tree without a plan leaves the context without one; a scroll state without one keeps the plan the context has.+ [RustReceiver, RustSender] update_display_list(Web::CompositorContextId context_id, Compositing::DisplayList display_list, Compositing::VisualContextTree visual_context_tree, Compositing::ScrollStateSnapshot scroll_state, Optional<Compositing::LayerPlan> layer_plan) =|describe_display_list_fonts(Web::CompositorContextId context_id, Vector<Compositing::DisplayListFontDescription> fonts) =|- [RustReceiver, RustSender] update_visual_context_tree(Web::CompositorContextId context_id, Compositing::VisualContextTree visual_context_tree, Compositing::ScrollStateSnapshot scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|- [RustReceiver, RustSender] update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|+ [RustReceiver, RustSender] update_visual_context_tree(Web::CompositorContextId context_id, Compositing::VisualContextTree visual_context_tree, Compositing::ScrollStateSnapshot scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state, Optional<Compositing::LayerPlan> layer_plan) =|+ [RustReceiver, RustSender] update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state, Optional<Compositing::LayerPlan> layer_plan) =|// Hands WebContent a range of canvas IDs it may name its own 2D contexts with, so creating one needs no round trip.reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 3c68155d36a..7af849833dd 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -128,6 +128,7 @@ struct DisplayListPlayerSkia::PainterCallbacks {.end_tile_raster = [](void* context) { PainterCallbacks::player(context).end_tile_raster(); },.begin_vector_image = [](void* context, RustFFI::VectorImagePlacement const* placement, bool requires_direct_replay) { return PainterCallbacks::player(context).begin_vector_image(*placement, requires_direct_replay); },.end_vector_image = [](void* context) { PainterCallbacks::player(context).end_vector_image(); },+ .draw_surface = [](void* context, RustFFI::SurfaceDraw const* draw) { PainterCallbacks::player(context).draw_surface(*draw); },};}};@@ -416,6 +417,19 @@ void DisplayListPlayerSkia::draw_composited_context(RustFFI::CompositedContextDrcanvas.drawImageRect(image.get(), src_rect, dst_rect, to_skia_sampling_options(command.scaling_mode), &paint, SkCanvas::kStrict_SrcRectConstraint);}+// Default sampling lands a tile's pixels unchanged where both rects have one size, as when the compositor copies them+// outside the replay.+void DisplayListPlayerSkia::draw_surface(RustFFI::SurfaceDraw const& draw)+{+ auto image = static_cast<Gfx::PaintingSurface*>(draw.surface)->sk_image_snapshot<sk_sp<SkImage>>();+ if (!image)+ return;+ SkPaint paint;+ paint.setBlendMode(SkBlendMode::kSrcOver);+ auto sampling = draw.filtered ? SkSamplingOptions { SkFilterMode::kLinear } : SkSamplingOptions {};+ surface().canvas().drawImageRect(image.get(), to_skia_rect(draw.source_rect), to_skia_rect(draw.target_rect), sampling, &paint, SkCanvas::kStrict_SrcRectConstraint);+}+void DisplayListPlayerSkia::play_command(DrawCanvas const& command){auto const* surfaces = canvas_surfaces();diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.hindex efe75f32ee1..bb4475387d0 100644--- a/Services/Compositor/DisplayListPlayerSkia.h+++ b/Services/Compositor/DisplayListPlayerSkia.h@@ -116,6 +116,7 @@ private:void end_tile_raster();Compositing::RustFFI::VectorImageReplay begin_vector_image(Compositing::RustFFI::VectorImagePlacement const&, bool requires_direct_replay);void end_vector_image();+ void draw_surface(Compositing::RustFFI::SurfaceDraw const&);void clip_path(SkPath, Gfx::WindingRule, bool anti_aliased);diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex f93c9f55f87..ad76b698c65 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -31,8 +31,6 @@ fn main() -> Result<(), Box<dyn Error>> {("RawMessage", "IPC::FfiRawMessage"),("EncodedValue", "AK::ReadonlyBytes"),("FfiRasterPainter", "Compositing::RustFFI::FfiRasterPainter"),- ("FfiReplaySelection", "Compositing::RustFFI::FfiReplaySelection"),- ("RecordSpan", "Compositing::RustFFI::RecordSpan"),("CanvasId", "Compositing::CanvasId"),("ImageFrameResourceId", "Compositing::ImageFrameResourceId"),("PaintingSurface", "Gfx::PaintingSurface"),diff --git a/Services/Compositor/Rust/src/context_scene.rs b/Services/Compositor/Rust/src/context_scene.rsindex a31fa08cd45..aca327d2ed2 100644--- a/Services/Compositor/Rust/src/context_scene.rs+++ b/Services/Compositor/Rust/src/context_scene.rs@@ -6,6 +6,9 @@//! What WebContent last sent a context to draw, and the visual context tree it is drawn with: the one WebContent sent, with the visual viewport this context has pinch-zoomed or panned since, and with its visual animations sampled.+use libcompositing_rust::display_list::commands::SpatialNodeIndex;+use libcompositing_rust::display_list::layers::{LayerStack, UnvalidatedLayerPlan};+use libcompositing_rust::display_list::placement::spatial_nodes_whose_scroll_offset_placement_leaves_out;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, DisplayList, ScrollStateSnapshot, TransformWithOrigin,animated_content_may_affect_viewport,@@ -15,10 +18,26 @@ use libgfx_rust::{FloatMatrix4x4, IntRect, IntSize};use std::io::Write;use std::rc::Rc;+/// A plan of the layers of the display list a scene holds under the tree WebContent published, as WebContent sent it,+/// once it passed the checks against the two.+#[derive(Clone)]+pub struct ReceivedLayerPlan {+ /// The viewport, in device pixels, the plan was made within.+ pub viewport_rect: IntRect,+ pub stack: Rc<LayerStack>,+ /// The spatial nodes whose scroll offset the plan reads. It holds wherever the compositor scrolls or moves the+ /// other nodes to, which include the anchors of its spaces. Empty for a plan of one layer.+ pub nodes_whose_scroll_offset_plan_reads: Rc<[u32]>,+}+#[derive(Default)]pub struct ContextScene {display_list: Option<Rc<DisplayList>>,visual_context_tree: Option<AccumulatedVisualContextTree>,+ layer_plan: Option<ReceivedLayerPlan>,+ /// Whether the scene holds the display list and the tree of the update WebContent sent last, which the plans it+ /// sends with scroll states are of.+ holds_list_and_tree_sent_last: bool,async_visual_viewport_transform: Option<TransformWithOrigin>,visual_context_tree_for_compositing: Option<AccumulatedVisualContextTree>,sampled_visual_context_tree: Option<AccumulatedVisualContextTree>,@@ -50,9 +69,10 @@ impl ContextScene {visual_context_tree: AccumulatedVisualContextTree,now: MonotonicTime,) {- self.invalidate_visual_context_tree_for_compositing();self.display_list = Some(display_list);- self.visual_context_tree = Some(visual_context_tree);+ self.layer_plan = None;+ self.animated_content_may_affect_viewport = None;+ self.take_visual_context_tree_unless_content_is_unchanged(visual_context_tree);update_visual_animation_sampling_state(self.visual_context_tree.as_ref().unwrap(),&mut self.visual_animation_sample_time_ns,@@ -61,7 +81,24 @@ impl ContextScene {);}- // Returns false, leaving everything as it was, for a tree that does not fit the installed display list.+ // Keeping the held tree keeps what frames cached under the number of its copy, and the main thread publishes most+ // lists with the content of the tree before.+ fn take_visual_context_tree_unless_content_is_unchanged(+ &mut self,+ visual_context_tree: AccumulatedVisualContextTree,+ ) {+ if self+ .visual_context_tree+ .as_ref()+ .is_some_and(|held| held.as_arc().has_same_content_as(visual_context_tree.as_arc()))+ {+ return;+ }+ self.invalidate_visual_context_tree_for_compositing();+ self.visual_context_tree = Some(visual_context_tree);+ }++ /// Returns false, leaving everything as it was, for a tree that does not fit the installed display list.pub fn replace_visual_context_tree(&mut self,visual_context_tree: AccumulatedVisualContextTree,@@ -91,8 +128,19 @@ impl ContextScene {);return false;}- self.invalidate_visual_context_tree_for_compositing();- self.visual_context_tree = Some(visual_context_tree);+ if self.display_list.as_ref().is_some_and(|list| {+ !list+ .storage()+ .effect_clip_plan_holds_under(visual_context_tree.as_arc())+ }) {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Dropping visual context tree update that nests the effects of the display list otherwise"+ );+ return false;+ }+ self.layer_plan = None;+ self.take_visual_context_tree_unless_content_is_unchanged(visual_context_tree);update_visual_animation_sampling_state(self.visual_context_tree.as_ref().unwrap(),&mut self.visual_animation_sample_time_ns,@@ -102,6 +150,80 @@ impl ContextScene {true}+ // NB: WebContent sends a plan with each display list and tree it can plan for, and with a scroll state only where+ // the viewport rect or a scroll offset that the plan it sent last reads changed. So a list or a tree that comes+ // without a plan leaves the scene without one, and a scroll state that comes without one keeps the plan the+ // scene holds. After a list or a tree that the compositor refuses, WebContent plans for what the scene does not+ // hold: a plan that comes with a scroll state is then dropped, until a list or a tree is installed.++ /// Forgets the plan of layers, ahead of a display list or a tree that WebContent sent, which the compositor may+ /// refuse.+ pub fn forget_layer_plan(&mut self) {+ self.layer_plan = None;+ self.holds_list_and_tree_sent_last = false;+ }++ /// Takes the plan of layers that came with the display list or the tree the scene just installed. Fails for a plan+ /// that does not pass the checks against them.+ pub fn take_layer_plan_of_installed_update(+ &mut self,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ self.holds_list_and_tree_sent_last = true;+ self.take_layer_plan(layer_plan)+ }++ /// Takes the plan of layers that came with a scroll state, if any. Fails for a plan that does not pass the checks+ /// against the display list and the tree it is of.+ pub fn take_layer_plan_of_scroll_state(+ &mut self,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ match layer_plan {+ Some(layer_plan) if self.holds_list_and_tree_sent_last => self.take_layer_plan(Some(layer_plan)),+ _ => Ok(()),+ }+ }++ fn take_layer_plan(&mut self, layer_plan: Option<UnvalidatedLayerPlan>) -> Result<(), &'static str> {+ self.layer_plan = None;+ let (Some(layer_plan), Some(display_list), Some(tree)) =+ (layer_plan, &self.display_list, &self.visual_context_tree)+ else {+ return Ok(());+ };+ // A plan of another list is of one the compositor refused for a reason WebContent does not learn.+ if layer_plan.display_list_id != display_list.id() {+ return Ok(());+ }+ let layer_plan = layer_plan.validated(display_list.storage(), tree.as_arc())?;+ // The spaces of a plan of more than one layer are at the anchors that plans take for the tree. A plan of one+ // layer replays the whole display list, and no frame reads which scroll offsets it leaves out.+ let nodes_whose_scroll_offset_plan_reads = if layer_plan.stack.replays_whole_list() {+ Rc::default()+ } else {+ let anchors_of_spaces: Vec<SpatialNodeIndex> = layer_plan+ .stack+ .spaces+ .iter()+ .skip(1)+ .map(|space| space.anchor)+ .collect();+ spatial_nodes_whose_scroll_offset_placement_leaves_out(tree.as_arc(), &anchors_of_spaces)+ .into_iter()+ .enumerate()+ .filter(|&(_, leaves_out)| !leaves_out)+ .map(|(node_index, _)| node_index as u32)+ .collect()+ };+ self.layer_plan = Some(ReceivedLayerPlan {+ viewport_rect: layer_plan.viewport_rect,+ stack: Rc::new(layer_plan.stack),+ nodes_whose_scroll_offset_plan_reads,+ });+ Ok(())+ }+pub fn display_list(&self) -> &Option<Rc<DisplayList>> {&self.display_list}@@ -138,6 +260,20 @@ impl ContextScene {self.sampled_visual_context_tree.as_ref().unwrap()}+ /// The plan of layers of the display list and the tree as WebContent published it, unless frames draw the tree+ /// through a visual viewport transform other than its own.+ pub fn layer_plan_unless_visual_viewport_differs(&self) -> Option<&ReceivedLayerPlan> {+ let layer_plan = self.layer_plan.as_ref()?;+ let tree = self.visual_context_tree.as_ref()?;+ if let Some(transform) = self.async_visual_viewport_transform {+ let published_transform = tree.visual_viewport_transform();+ if transform.matrix != published_transform.matrix || transform.origin != published_transform.origin {+ return None;+ }+ }+ Some(layer_plan)+ }+pub fn visual_viewport_transform(&self) -> TransformWithOrigin {if let Some(transform) = self.async_visual_viewport_transform {return transform;@@ -159,8 +295,8 @@ impl ContextScene {Some(tree.visual_viewport_transform().matrix.elements[0][0])}- // How many screen pixels a zoomed visual viewport shows one pixel of the layout viewport with. Scrollers scroll and- // stretch in the pixels of the layout viewport.+ /// How many screen pixels a zoomed visual viewport shows one pixel of the layout viewport with. Scrollers scroll+ /// and stretch in the pixels of the layout viewport.pub fn visual_viewport_magnification(&self) -> f32 {let scale = self.visual_viewport_scale().unwrap_or(1.0);if scale < 1.0 { 1.0 } else { scale }@@ -240,3 +376,136 @@ impl ContextScene {self.visual_context_tree_for_compositing = None;}}++#[cfg(test)]+mod tests {+ use super::*;+ use libcompositing_rust::display_list::builder::DisplayListBuilder;+ use libcompositing_rust::display_list::commands::{ContextRef, EffectNodeIndex, FillRect};+ use libcompositing_rust::display_list::layers::LayerPlan;+ use libcompositing_rust::display_list::layers::planning::InputsOfLayerPlan;+ use libcompositing_rust::display_list::storage::{ChunkIndexInList, DisplayListStorage, ListPosition, ListSpan};+ use libcompositing_rust::ipc_types::LayerPlanOnWire;+ use libcompositing_rust::visual_context::VisualContextTree;+ use libgfx_rust::{Color, CompositingAndBlendingOperator};+ use libipc_rust::wire::{Decoder, Encoder};+ use std::sync::Arc;++ const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);+ const DISPLAY_LIST_ID: u64 = 7;++ fn scene_with_one_rect() -> (ContextScene, Arc<DisplayListStorage>, Arc<VisualContextTree>) {+ let tree = Arc::new(VisualContextTree::create_identity());+ let mut builder = DisplayListBuilder::new();+ builder.append(+ &FillRect {+ rect: IntRect::new(10, 10, 100, 100),+ color: Color::from_rgb(0, 128, 0),+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ },+ &[],+ ContextRef::default(),+ );+ let list = DisplayListStorage::recorded(&builder.finish(), tree.clone());+ let display_list = DisplayList::new(+ list.clone(),+ DISPLAY_LIST_ID,+ tree.structural_epoch,+ None,+ None,+ Default::default(),+ );+ let mut scene = ContextScene::default();+ scene.install(+ Rc::new(display_list),+ AccumulatedVisualContextTree::from_arc(tree.clone()),+ MonotonicTime::default(),+ );+ (scene, list, tree)+ }++ // A plan as the compositor receives it from WebContent.+ fn received(display_list_id: u64, stack: LayerStack) -> UnvalidatedLayerPlan {+ let mut encoder = Encoder::new();+ encoder+ .encode(&LayerPlanOnWire::Planned(Arc::new(LayerPlan {+ display_list_id,+ viewport_rect: VIEWPORT,+ stack,+ })))+ .unwrap();+ let (bytes, _) = encoder.finish();+ Decoder::new(&bytes, [])+ .decode::<LayerPlanOnWire>()+ .unwrap()+ .into_received()+ }++ fn stack_of_plan(scene: &ContextScene) -> Option<LayerStack> {+ scene+ .layer_plan_unless_visual_viewport_differs()+ .map(|layer_plan| (*layer_plan.stack).clone())+ }++ #[test]+ fn a_plan_is_taken_with_the_list_it_is_of_and_one_that_does_not_fit_it_is_refused() {+ let (mut scene, list, tree) = scene_with_one_rect();+ let planned = InputsOfLayerPlan::new(list.clone(), tree, &[], VIEWPORT).plan().stack;+ assert_eq!(planned.why_list_is_one_layer, None);+ let span_past_end_of_list = ListSpan {+ begin: ListPosition::default(),+ end: ListPosition::new(ChunkIndexInList(0), list.whole_span().end.offset + 8),+ };+ let stack_not_fitting_list = || {+ let mut stack = planned.clone();+ stack.bands[0].record_spans = vec![span_past_end_of_list];+ stack+ };++ scene.forget_layer_plan();+ assert_eq!(+ scene.take_layer_plan_of_installed_update(Some(received(DISPLAY_LIST_ID, planned.clone()))),+ Ok(())+ );+ assert_eq!(stack_of_plan(&scene), Some(planned.clone()));+ // A scroll state without a plan keeps the plan.+ assert_eq!(scene.take_layer_plan_of_scroll_state(None), Ok(()));+ assert_eq!(stack_of_plan(&scene), Some(planned.clone()));++ // The stub of the message answers WebContent with misbehavior for a plan that does not pass the checks.+ assert!(+ scene+ .take_layer_plan_of_scroll_state(Some(received(DISPLAY_LIST_ID, stack_not_fitting_list())))+ .is_err()+ );+ assert_eq!(stack_of_plan(&scene), None);+ assert!(+ scene+ .take_layer_plan_of_installed_update(Some(received(DISPLAY_LIST_ID, stack_not_fitting_list())))+ .is_err()+ );++ // A plan of another list is of one the compositor refused, and goes unchecked.+ assert_eq!(+ scene.take_layer_plan_of_installed_update(Some(received(DISPLAY_LIST_ID + 1, stack_not_fitting_list()))),+ Ok(())+ );+ assert_eq!(stack_of_plan(&scene), None);++ // After a list or a tree the compositor may refuse, a plan with a scroll state is not of what the scene holds+ // until a plan comes with a list or a tree the scene installs.+ scene.forget_layer_plan();+ assert_eq!(+ scene.take_layer_plan_of_scroll_state(Some(received(DISPLAY_LIST_ID, stack_not_fitting_list()))),+ Ok(())+ );+ assert_eq!(stack_of_plan(&scene), None);+ assert_eq!(scene.take_layer_plan_of_installed_update(None), Ok(()));+ assert_eq!(+ scene.take_layer_plan_of_scroll_state(Some(received(DISPLAY_LIST_ID, planned.clone()))),+ Ok(())+ );+ assert_eq!(stack_of_plan(&scene), Some(planned));+ }+}diff --git a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rsindex d75ed59e5bc..9c0601aeafe 100644--- a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs+++ b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs@@ -104,7 +104,7 @@ impl ContextState {Some(self.async_scrolling_viewport_rect)}- // Where the first step of a wheel gesture at the position, by the delta in CSS pixels, would go.+ /// Where the first step of a wheel gesture at the position, by the delta in CSS pixels, would go.pub fn route_first_wheel_step_for_testing(&mut self,position: FloatPoint,@@ -145,7 +145,7 @@ impl ContextState {}}- // The installed scrolling state, its routing admission, and how far the given scroller is stretched, as JSON.+ /// The installed scrolling state, its routing admission, and how far the given scroller is stretched, as JSON.pub fn scroll_state_for_testing(&self, scroller: AsyncScrollNodeStableID) -> String {let mut scroll_state = JsonWriter(async_scrolling_state_to_json(self.async_scroll_tree.state()));scroll_state.0.pop();@@ -212,9 +212,9 @@ impl ContextState {);}- // Returns whether the overlays have to repaint all of the viewport. The page's next frame repaints all of it when its- // size changes, but the paused debugger's page does not paint again, and a new pixel ratio alone need not repaint- // the page.+ /// Returns whether the overlays have to repaint all of the viewport. The page's next frame repaints all of it when+ /// its size changes, but the paused debugger's page does not paint again, and a new pixel ratio alone need not+ /// repaint the page.pub fn viewport_size_updated(&mut self, viewport_size: IntSize, device_pixel_ratio: f64) -> bool {let only_the_pixel_ratio_changed =viewport_size == self.viewport_size && device_pixel_ratio != self.device_pixel_ratio;@@ -229,7 +229,7 @@ impl ContextState {|| (only_the_pixel_ratio_changed && ui_overlays.picture_in_picture_controls.is_some())}- // Returns false, changing nothing, for the overlays already shown.+ /// Returns false, changing nothing, for the overlays already shown.pub fn set_ui_overlays(&mut self, ui_overlays: UIOverlays, now: MonotonicTime) -> bool {let shows_paused_debugger = ui_overlays.paused_debugger.is_some();if !self.overlays.set_ui_overlays(ui_overlays, now) {@@ -241,7 +241,7 @@ impl ContextState {true}- // What the fades of the overlays repaint of the viewport as they advance to the frame.+ /// What the fades of the overlays repaint of the viewport as they advance to the frame.pub fn advance_overlay_fades(&mut self, frame_time: MonotonicTime) -> Option<IntRect> {self.overlays.advance_fades(frame_time, self.viewport_size, self.device_pixel_ratio)@@ -263,7 +263,7 @@ impl ContextState {true}- // Where the compositor has scrolled each scroll node to.+ /// Where the compositor has scrolled each scroll node to.pub fn scroll_offsets(&self) -> Vec<CompositorScrollOffset> {let scroll_nodes = self.async_scroll_tree.scroll_nodes();let mut scroll_offsets = Vec::with_capacity(scroll_nodes.len());@@ -293,9 +293,9 @@ impl ContextState {);FrameInputs {visual_context_tree: self.scene.visual_context_tree_for_compositing().clone(),+ layer_plan: self.scene.layer_plan_unless_visual_viewport_differs().cloned(),presented_scroll_state_snapshot,scrollbars,- viewport_scroll_node_index: self.async_scroll_tree.viewport_scroll_node_index(),painted_at: now,overlays,}@@ -356,8 +356,8 @@ impl ContextState {damage_rect}- // Each frame shows the scrollbars as of when it is painted, so this updates which of them are shown. Empty until a- // display list is installed.+ /// Each frame shows the scrollbars as of when it is painted, so this updates which of them are shown. Empty until a+ /// display list is installed.pub fn frame_inputs(&mut self, now: MonotonicTime) -> Option<FrameInputs> {self.update_scrollbar_visibility(now);self.scene.display_list().as_ref()?;@@ -464,8 +464,8 @@ impl ContextState {})}- // Pans the visual viewport of a zoomed page by as much of a delta in screen pixels as it has room for, and returns- // that part of the delta.+ /// Pans the visual viewport of a zoomed page by as much of a delta in screen pixels as it has room for, and returns+ /// that part of the delta.pub(super) fn pan_visual_viewport_by(&mut self, delta_in_screen_pixels: FloatPoint) -> FloatPoint {let Some(delta) = self.apply_visual_viewport_scroll_delta(delta_in_screen_pixels) else {return Default::default();@@ -488,9 +488,9 @@ impl ContextState {scroll_offsets}- // The main thread asks for every scroll of its own, so the offsets a snapshot of its scroll state has for the boxes- // this context already scrolls are what it last heard of them. Only a box new to this context takes its offset from- // the snapshot.+ /// The main thread asks for every scroll of its own, so the offsets a snapshot of its scroll state has for the+ /// boxes this context already scrolls are what it last heard of them. Only a box new to this context takes its+ /// offset from the snapshot.pub(super) fn keep_scroll_offsets_of_known_nodes(&mut self,scroll_offsets_of_known_nodes: &HashMap<AsyncScrollNodeStableID, FloatPoint>,diff --git a/Services/Compositor/Rust/src/context_state/gestures_and_scrollbars.rs b/Services/Compositor/Rust/src/context_state/gestures_and_scrollbars.rsindex 01cc0b6ca01..9dc5e7dd4ba 100644--- a/Services/Compositor/Rust/src/context_state/gestures_and_scrollbars.rs+++ b/Services/Compositor/Rust/src/context_state/gestures_and_scrollbars.rs@@ -22,8 +22,8 @@ impl ContextState {)}- // The scroller the first step of a gesture goes to, as the hit test at the position finds it, or as it is found- // from the innermost of the scrollers the page found around the target that this context knows.+ /// The scroller the first step of a gesture goes to, as the hit test at the position finds it, or as it is found+ /// from the innermost of the scrollers the page found around the target that this context knows.pub(super) fn route_first_wheel_step(&mut self,position: FloatPoint,@@ -59,7 +59,7 @@ impl ContextState {)}- // The scroller the first step of a wheel gesture is routed to, which the gesture is latched to.+ /// The scroller the first step of a wheel gesture is routed to, which the gesture is latched to.#[allow(clippy::too_many_arguments)]pub(super) fn route_and_latch_wheel_gesture(&mut self,@@ -239,8 +239,8 @@ impl ContextState {);}- // A gesture whose steps this context chains ends once they stop arriving, which is reported to WebContent so- // that it settles the gesture then rather than on a clock of its own.+ /// A gesture whose steps this context chains ends once they stop arriving, which is reported to WebContent so+ /// that it settles the gesture then rather than on a clock of its own.pub(super) fn end_scroll_step_gestures_whose_input_ran_out(&mut self, now: MonotonicTime) {let ended_boxes = self.scroll_snap_controller.end_gestures_whose_input_ran_out(now);if !ended_boxes.is_empty() {@@ -272,7 +272,7 @@ impl ContextState {),started_at: now,is_user_scroll: true,- heads_to_an_extent: false,+ heads_to_end_of_scroll_range: false,});self.report_started_user_scroll(operation_id,@@ -300,8 +300,8 @@ impl ContextState {)}- // Pages the scroller of the captured scrollbar once toward the pointer, from where a page scroll in flight goes, unless- // the thumb has reached the pointer there.+ /// Pages the scroller of the captured scrollbar once toward the pointer, from where a page scroll in flight goes,+ /// unless the thumb has reached the pointer there.pub(super) fn page_captured_scrollbar(&mut self, now: MonotonicTime) -> Option<PendingFrame> {let scrollbar_index = self.scrollbar_controller.captured_scrollbar_index();if scrollbar_index.is_none() || self.scrollbar_paging.is_none_or(|paging| paging.direction == 0) {@@ -319,7 +319,7 @@ impl ContextState {let (Some(node), Some(old_scroll_offset)) = (node, old_scroll_offset) else {return None;};- let running_animation = self.running_scrollbar_press_scroll();+ let running_animation = self.index_of_running_scrollbar_press_scroll();let step_start = running_animation.map_or(old_scroll_offset, |index| {self.smooth_scroll_animations[index].animation.destination_offset()});@@ -368,8 +368,7 @@ impl ContextState {self.start_scrollbar_press_scroll(&node, old_scroll_offset, destination, false, now)}- // The smooth scroll that a press beside the thumb started, while it lasts.- fn running_scrollbar_press_scroll(&mut self) -> Option<usize> {+ fn index_of_running_scrollbar_press_scroll(&mut self) -> Option<usize> {let operation_id = self.scrollbar_press_scroll_operation?;let animation = self.smooth_scroll_animations@@ -408,7 +407,7 @@ impl ContextState {.clamped_scroll_offset_for_node(scroll_node_index, dragged_to.scroll_offset);// A press beside the thumb scrolls there smoothly, as a page step does. Dragging on before that scroll has ended// moves where it goes.- if let Some(index) = self.running_scrollbar_press_scroll() {+ if let Some(index) = self.index_of_running_scrollbar_press_scroll() {if self.smooth_scroll_animations[index].animation.destination_offset() == destination {return None;}diff --git a/Services/Compositor/Rust/src/context_state/keys_and_pointer.rs b/Services/Compositor/Rust/src/context_state/keys_and_pointer.rsindex 4d550ff4da4..e5b2fb01c22 100644--- a/Services/Compositor/Rust/src/context_state/keys_and_pointer.rs+++ b/Services/Compositor/Rust/src/context_state/keys_and_pointer.rs@@ -199,7 +199,7 @@ impl ContextState {continue;}self.retarget_user_scroll(index, destination, now);- self.smooth_scroll_animations[index].heads_to_an_extent = scrolls_to_extent;+ self.smooth_scroll_animations[index].heads_to_end_of_scroll_range = scrolls_to_extent;let operation_id = self.smooth_scroll_animations[index].operation_id;self.report_started_user_scroll(operation_id,@@ -224,7 +224,7 @@ impl ContextState {),started_at: now,is_user_scroll: true,- heads_to_an_extent: scrolls_to_extent,+ heads_to_end_of_scroll_range: scrolls_to_extent,});self.report_started_user_scroll(operation_id,@@ -284,7 +284,7 @@ impl ContextState {self.handle_mouse_event_at(event, position, now)}- // A mouse event that the context this one is nested in hands to it, at a position in this context's device pixels.+ /// A mouse event that the context this one is nested in hands to it, at a position in this context's device pixels.pub fn handle_mouse_event_from_containing_context(&mut self,event: &MouseEvent,@@ -299,8 +299,8 @@ impl ContextState {self.handle_mouse_event_at(event, position, now)}- // Where the pointer is in this context's device pixels, as the mouse event the context takes or hands on says, or- // nowhere, as the pointer leaves it.+ /// Where the pointer is in this context's device pixels, as the mouse event the context takes or hands on says, or+ /// nowhere, as the pointer leaves it.pub fn note_pointer_position(&mut self, position: Option<FloatPoint>) {self.pointer_position = position;}@@ -313,7 +313,7 @@ impl ContextState {Some(PendingFrame::repainting_everything(self.async_scrolling_viewport_rect))}- // The pointer left the scrollbar it was over here for a context nested in this one, or for the one around it.+ /// The pointer left the scrollbar it was over here for a context nested in this one, or for the one around it.pub fn clear_scrollbar_hover(&mut self) -> Option<PendingFrame> {if !self.scrollbar_controller.set_hovered_scrollbar(None) {return None;diff --git a/Services/Compositor/Rust/src/context_state/mod.rs b/Services/Compositor/Rust/src/context_state/mod.rsindex 99155b45cfc..bba4d68e76a 100644--- a/Services/Compositor/Rust/src/context_state/mod.rs+++ b/Services/Compositor/Rust/src/context_state/mod.rs@@ -25,6 +25,7 @@ use crate::scroll_fling_controller::ScrollFlingController;use crate::scroll_snap_controller::{ScrollSnapController, SnapScrollStart, StepDecision};use crate::scrollbar_controller::{Drag, ScrollbarController};use crate::wheel_gesture_routing::{ResolvedLatch, WheelGestureIdAllocator, WheelGestureRouting};+use libcompositing_rust::display_list::layers::UnvalidatedLayerPlan;use libcompositing_rust::ipc_types::{Compositing_AsyncScrollOperationTracking as AsyncScrollOperationTracking,Compositing_ContextVisibility as ContextVisibility, Compositing_RequestedRelativeScroll as RequestedRelativeScroll,@@ -43,7 +44,7 @@ use std::rc::Rc;pub struct AsyncScrollEnqueueResult {pub accepted: bool,pub operation_id: Option<AsyncScrollOperationID>,- // Why the compositor took or turned away a wheel step, and the scroller it routed the step to.+ /// Why the compositor took or turned away a wheel step, and the scroller it routed the step to.pub routing_decision: Option<InputRoutingDecision>,pub routed_scroller: Option<AsyncScrollNodeStableID>,}@@ -66,15 +67,15 @@ impl AsyncScrollResult {}}-// A wheel step that goes to a context nested in this one: the first step of a gesture over the content of the-// nested context, or a step of a gesture latched to a context nested here.+/// A wheel step that goes to a context nested in this one: the first step of a gesture over the content of the+/// nested context, or a step of a gesture latched to a context nested here.pub struct NestedContextWheelStep {pub context_id: CompositorContextId,- // Where the first step lands in the content of the nested context.+ /// Where the first step lands in the content of the nested context.pub hit: Option<NestedContextHit>,}-// An operation that a wheel step asked to follow, whose end the scroll updates of the context report.+/// An operation that a wheel step asked to follow, whose end the scroll updates of the context report.pub struct TrackedScrollOperation {pub context_id: CompositorContextId,pub operation_id: AsyncScrollOperationID,@@ -85,18 +86,18 @@ pub struct ContextUpdateResult {pub accepted: bool,pub frame_to_present: Option<PendingFrame>,pub should_request_rendering_update: bool,- // Whether a key event found nothing to scroll by the compositor's scroll range, which may lag behind the page's.+ /// Whether a key event found nothing to scroll by the compositor's scroll range, which may lag behind the page's.pub key_found_nothing_to_scroll: bool,pub scrollbar_dragged_by_compositor: Option<ScrollbarDraggedByCompositor>,- // Why a wheel or mouse event was taken or turned away, and the scroller it was routed to.+ /// Why a wheel or mouse event was taken or turned away, and the scroller it was routed to.pub routing_decision: Option<InputRoutingDecision>,pub routed_scroller: Option<AsyncScrollNodeStableID>,- // How the first step of a wheel gesture went by a nested context, ahead of `routing_decision`.+ /// How the first step of a wheel gesture went by a nested context, ahead of `routing_decision`.pub nested_context_hand_off: Option<InputRoutingDecision>,- // Set instead of everything else for a wheel step that a nested context is to take.+ /// Set instead of everything else for a wheel step that a nested context is to take.pub nested_context_wheel_step: Option<NestedContextWheelStep>,- // Set, with at most the frame of the scrollbar the pointer left here, for a mouse event that the nested context- // under the pointer is to take.+ /// Set, with at most the frame of the scrollbar the pointer left here, for a mouse event that the nested context+ /// under the pointer is to take.pub nested_context_mouse_hit: Option<NestedContextHit>,pub tracked_scroll_operation: Option<TrackedScrollOperation>,}@@ -110,43 +111,43 @@ impl ContextUpdateResult {}}-// A step of a wheel gesture at a position in this context's device pixels. The delta is in CSS pixels, with the axes-// already swapped for Shift.+/// A step of a wheel gesture at a position in this context's device pixels. The delta is in CSS pixels, with the axes+/// already swapped for Shift.pub struct WheelStep {pub position: FloatPoint,pub delta_in_css_pixels: FloatPoint,pub wheel_delta_precision: WheelDeltaPrecision,pub scroll_gesture_phase: ScrollGesturePhase,- // The gesture the step is in, which the latch a context takes for the step is for. A context nested in another- // one takes it for the gesture of the containing context.+ /// The gesture the step is in, which the latch a context takes for the step is for. A context nested in another+ /// one takes it for the gesture of the containing context.pub gesture_id: Option<u64>,pub operation_tracking: AsyncScrollOperationTracking,}-// What the wheel event listeners of the page that dispatches a gesture's wheel events let through without waiting-// for the page. That page may be the page of a context nested in this one.+/// What the wheel event listeners of the page that dispatches a gesture's wheel events let through without waiting+/// for the page. That page may be the page of a context nested in this one.#[derive(Default)]pub struct WheelEventListenerGate {- // The page dispatched a step of the gesture and did not cancel it, and the listeners are as they were then.+ /// The page dispatched a step of the gesture and did not cancel it, and the listeners are as they were then.pub page_let_the_gesture_through: bool,- // Why the listeners hold the steps of a latched gesture back for the page, if they do.+ /// Why the listeners hold the steps of a latched gesture back for the page, if they do.pub reason_to_hold_latched_steps_back: Option<InputRoutingDecision>,}-// What may hold a step back for the page before this context scrolls by it.+/// What may hold a step back for the page before this context scrolls by it.#[derive(Clone, Copy, PartialEq, Eq)]pub enum WheelStepAdmission {- // The wheel event listeners of this context's page see the step, which waits for the page if they may cancel it.+ /// The wheel event listeners of this context's page see the step, which waits for the page if they may cancel it.ByThisPage,- // A context nested in this one passed the step on. Only the page of that context sees the step.+ /// A context nested in this one passed the step on. Only the page of that context sees the step.PassedOnByNestedContext,- // The page let the gesture through. Nothing holds the step back, and a step that finds nothing to scroll is done- // with all the same, so that the page is not asked about the gesture again.+ /// The page let the gesture through. Nothing holds the step back, and a step that finds nothing to scroll is done+ /// with all the same, so that the page is not asked about the gesture again.LetThroughByThePage,}-// Where the first step of a gesture that the containing context hands in goes in this context. A nested context-// passes a step on to the document around it unless one of its scrollers takes or keeps it.+/// Where the first step of a gesture that the containing context hands in goes in this context. A nested context+/// passes a step on to the document around it unless one of its scrollers takes or keeps it.pub struct FirstWheelStepRoute {pub kind: FirstWheelStepRouteKind,pub decision: InputRoutingDecision,@@ -164,25 +165,25 @@ pub enum FirstWheelStepRouteKind {PassedOn,}-// What a presenting context keeps of the contexts nested in it that the pointer is in, with positions in the device-// pixels of those contexts.+/// What a presenting context keeps of the contexts nested in it that the pointer is in, with positions in the device+/// pixels of those contexts.#[derive(Default)]pub struct PointerInNestedContexts {- // The context whose scrollbar the pointer is dragging, which takes the pointer wherever it goes until the drag- // ends.+ /// The context whose scrollbar the pointer is dragging, which takes the pointer wherever it goes until the drag+ /// ends.pub context_with_captured_scrollbar: Option<CompositorContextId>,pub last_position_in_context_with_captured_scrollbar: FloatPoint,pub context_under_pointer: Option<CompositorContextId>,}-// What this context noted of a wheel event as the event arrived.+/// What this context noted of a wheel event as the event arrived.pub struct NotedWheelEvent {pub wheel_gesture_mark: WheelGestureMark,- // Only the first step of a gesture that moves anything goes to a nested context.+ /// Only the first step of a gesture that moves anything goes to a nested context.pub is_first_wheel_event_with_delta: bool,}-// What the presentation a context is shown through makes of the user's scrolling.+/// What the presentation a context is shown through makes of the user's scrolling.pub struct ScrollCapabilities {pub synthesizes_scroll_momentum: bool,pub scrolls_elastically: bool,@@ -203,7 +204,7 @@ impl Default for ScrollCapabilities {pub struct ScreenshotInputs {pub frame_inputs: FrameInputs,- // The scrollbar fade damage that the screenshot does not present on screen.+ /// The scrollbar fade damage that the screenshot does not present on screen.pub scrollbar_fade_damage_rect: IntRect,}@@ -213,8 +214,7 @@ struct ActiveSmoothScrollAnimation {animation: SmoothScrollAnimation,started_at: MonotonicTime,is_user_scroll: bool,- // Whether the scroll goes to an end of the scroll range, as the Home and End keys scroll.- heads_to_an_extent: bool,+ heads_to_end_of_scroll_range: bool,}struct VisualViewportScrollDelta {@@ -257,14 +257,13 @@ struct WheelGestureLatchAttempt {latched_scroll_node_index: Option<SpatialNodeIndex>,}-// A press beside the thumb that pages toward the pointer for as long as it is held.#[derive(Clone, Copy, Default)]struct ScrollbarPaging {direction: i32,primary_position: f32,}-// Collects the routing decisions of input events while a test asks for them.+/// Collects the routing decisions of input events while a test asks for them.#[derive(Default)]pub struct InputTraceRecorder {records: Option<Vec<InputTraceRecord>>,@@ -284,7 +283,7 @@ impl InputTraceRecorder {};records.push(record);}- // Returns what was recorded since the trace began, and stops recording.+ /// Returns what was recorded since the trace began, and stops recording.pub fn take(&mut self) -> Vec<InputTraceRecord> {self.records.take().unwrap_or_default()}@@ -319,7 +318,6 @@ pub struct ContextState {context_user_input_scroll_count: u64,// The boxes the last frame brought, whose offsets came from that frame's snapshot.scroll_nodes_seeded_by_last_frame: HashSet<AsyncScrollNodeStableID>,- // Whether this context has scrolled boxes to offsets that WebContent's last frame does not have them at.scroll_offsets_differ_from_last_frame: bool,// The document whose visual viewport this context zoomed or panned, which it presents as it left it from then on.visual_viewport_document_id: Option<UniqueNodeId>,@@ -620,7 +618,6 @@ impl ContextState {ContextTimer::ScrollStepGestureInput => self.end_scroll_step_gestures_whose_input_ran_out(now),ContextTimer::ScrollbarPaging => {self.scrollbar_paging_timer_is_armed = false;- // Paging ends with the press, and with the scrollbar the press holds.if self.scrollbar_paging.is_none() || !self.scrollbar_controller.has_captured_scrollbar() {self.stop_scrollbar_paging();return None;@@ -647,7 +644,9 @@ impl ContextState {// The core handles the timers of presenting.ContextTimer::BackingStoreShrink| ContextTimer::SurplusStoreRetirement- | ContextTimer::HiddenStoreRetirement => {}+ | ContextTimer::HiddenStoreRetirement+ | ContextTimer::SpareTileEviction+ | ContextTimer::TileRasterScratchSurfaceRelease => {}}None}@@ -722,7 +721,7 @@ impl ContextState {}}- // Whether the scroll offsets here moved past those of the last frame WebContent presented.+ /// Whether the scroll offsets here moved past those of the last frame WebContent presented.pub fn scrolled_since_last_frame(&self) -> bool {self.has_pending_async_scroll_updates()|| self.scroll_offsets_differ_from_last_frame@@ -763,7 +762,7 @@ impl ContextState {self.parent_context_id = parent_context_id;}- // Returns false, leaving everything as it was, for scrolling state with numbers no scroll can be calculated with.+ /// Returns false, leaving everything as it was, for scrolling state with numbers no scroll can be calculated with.pub fn install_display_list_update(&mut self,display_list: Rc<DisplayList>,@@ -836,7 +835,6 @@ impl ContextState {self.has_async_scrolling_state = true;}- // Repaints the blinking caret of a display list each time its blink cycle turns it on or off.fn restart_caret_blink_for(&mut self, display_list: &DisplayList, now: MonotonicTime) {let mut blink_cycle_start_time_ns = None;display_list.for_each_caret(|_, _, caret| {@@ -904,8 +902,26 @@ impl ContextState {damage_rect}- // Returns false for a tree that does not fit the installed display list, which keeps the tree it has and takes only- // the scroll state that pairs with the new one.+ pub fn forget_layer_plan(&mut self) {+ self.scene.forget_layer_plan();+ }++ pub fn take_layer_plan_of_installed_update(+ &mut self,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ self.scene.take_layer_plan_of_installed_update(layer_plan)+ }++ pub fn take_layer_plan_of_scroll_state(+ &mut self,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ self.scene.take_layer_plan_of_scroll_state(layer_plan)+ }++ /// Returns false for a tree that does not fit the installed display list, which keeps the tree it has and takes+ /// only the scroll state that pairs with the new one.pub fn update_visual_context_tree(&mut self,visual_context_tree: AccumulatedVisualContextTree,diff --git a/Services/Compositor/Rust/src/context_state/scrolling.rs b/Services/Compositor/Rust/src/context_state/scrolling.rsindex e88cc8d6b31..b3137a8548f 100644--- a/Services/Compositor/Rust/src/context_state/scrolling.rs+++ b/Services/Compositor/Rust/src/context_state/scrolling.rs@@ -125,7 +125,7 @@ impl ContextState {),started_at: now,is_user_scroll: true,- heads_to_an_extent: false,+ heads_to_end_of_scroll_range: false,});self.scroll_snap_controller.did_start_snap_scroll(stable_node_id, operation_id, destination);@@ -145,7 +145,8 @@ impl ContextState {operation_id}- // The end of a gesture snaps the boxes it panned; the first snap scroll it starts is the operation a caller follows.+ /// The end of a gesture snaps the boxes it panned; the first snap scroll it starts is the operation a caller+ /// follows.pub(super) fn snap_at_gesture_end(&mut self, now: MonotonicTime) -> Option<AsyncScrollOperationID> {let mut operation_id = None;for snap in self@@ -160,7 +161,6 @@ impl ContextState {operation_id}- // The viewport rect a wheel scroll presents, moved along with the viewport when the scroll moved it.fn note_async_scrolling_viewport_rect(&mut self,mut viewport_rect: IntRect,@@ -179,9 +179,9 @@ impl ContextState {viewport_rect}- // A step of a wheel gesture that is latched to the node. A stretch of the node is relaxed before the visual- // viewport is panned, the node only scrolls by what both leave of the step, and what the node cannot scroll by- // either is what pulls it past its edge.+ /// A step of a wheel gesture that is latched to the node. A stretch of the node is relaxed before the visual+ /// viewport is panned, the node only scrolls by what both leave of the step, and what the node cannot scroll by+ /// either is what pulls it past its edge.#[allow(clippy::too_many_arguments)]pub(super) fn perform_wheel_scroll_of_node(&mut self,@@ -685,7 +685,7 @@ impl ContextState {if shifts_running_animation {let animation = &mut self.smooth_scroll_animations[running_animation.unwrap()];// A step that goes to an end of the scroll range still goes there.- if !animation.heads_to_an_extent {+ if !animation.heads_to_end_of_scroll_range {animation.animation.shift_by(instant_scroll_delta);let destination_offset = animation.animation.destination_offset();let clamped_destination_offset = self@@ -746,7 +746,7 @@ impl ContextState {animation,started_at: now,is_user_scroll: smooth_scroll.initiator == SmoothScrollInitiator::UserInput,- heads_to_an_extent: false,+ heads_to_end_of_scroll_range: false,});}}@@ -835,7 +835,6 @@ impl ContextState {});}- // Returns whether the request moved the visual viewport.fn apply_visual_viewport_scroll_request(&mut self,scroll_request: &ScrollRequest,@@ -950,7 +949,7 @@ impl ContextState {),started_at: now,is_user_scroll: true,- heads_to_an_extent: false,+ heads_to_end_of_scroll_range: false,});self.report_started_user_scroll(operation_id,diff --git a/Services/Compositor/Rust/src/context_state/wheel.rs b/Services/Compositor/Rust/src/context_state/wheel.rsindex 7bf92301fe4..de80183ae3b 100644--- a/Services/Compositor/Rust/src/context_state/wheel.rs+++ b/Services/Compositor/Rust/src/context_state/wheel.rs@@ -36,7 +36,7 @@ impl WheelStep {}impl ContextState {- // The UI's wheel deltas are in CSS pixels; this scales them for the scroll tree, which works in device pixels.+ /// The UI's wheel deltas are in CSS pixels; this scales them for the scroll tree, which works in device pixels.pub fn handle_wheel_event(&mut self,event: &MouseEvent,@@ -58,7 +58,7 @@ impl ContextState {)}- // Routes the event like one from the UI, also in a context that is nested in another one.+ /// Routes the event like one from the UI, also in a context that is nested in another one.pub fn scroll_for_wheel_event_from_main_thread(&mut self,event: &MouseEvent,@@ -104,8 +104,8 @@ impl ContextState {}}- // A wheel event of the UI that this context did not scroll by is left to its page, which then answers whether it let- // the event through.+ /// A wheel event of the UI that this context did not scroll by is left to its page, which then answers whether it+ /// let the event through.pub fn note_wheel_event_left_to_the_page(&mut self, event: &MouseEvent) {self.wheel_gesture_routing.note_delta_left_to_the_page(WheelStep::for_wheel_event(event, None, AsyncScrollOperationTracking::No).delta_in_css_pixels,@@ -134,8 +134,8 @@ impl ContextState {}}- // Takes note of a wheel event from the UI as it arrives, ahead of anything that may turn it away or leave it to- // the page.+ /// Takes note of a wheel event from the UI as it arrives, ahead of anything that may turn it away or leave it to+ /// the page.pub fn note_wheel_event_from_ui(&mut self, event: &MouseEvent, now: MonotonicTime) -> NotedWheelEvent {let phase = event.scroll_gesture_phase;let noted = self.note_wheel_event(event, now);@@ -159,19 +159,19 @@ impl ContextState {noted}- // Takes note of a wheel event that the main thread has and the UI did not send here, as the UI's events are noted.- // Such an event adds nothing to the velocity of a flick or of a stretch release.+ /// Takes note of a wheel event that the main thread has and the UI did not send here, as the UI's events are noted.+ /// Such an event adds nothing to the velocity of a flick or of a stretch release.pub fn note_wheel_event_from_main_thread(&mut self, event: &MouseEvent, now: MonotonicTime) -> NotedWheelEvent {self.note_wheel_event(event, now)}- // Starts a fling if the gesture that the event ends was a flick. Use only on platforms that send no momentum- // scroll events.+ /// Starts a fling if the gesture that the event ends was a flick. Use only on platforms that send no momentum+ /// scroll events.pub fn start_scroll_fling_if_flicked(&mut self, gesture_end_event: &MouseEvent, now: MonotonicTime) -> bool {self.scroll_fling_controller.start_if_flicked(gesture_end_event, now)}- // Ends the fling before a wheel event from a new gesture or other input.+ /// Ends the fling before a wheel event from a new gesture or other input.pub fn interrupt_scroll_fling(&mut self, event: &MouseEvent, now: MonotonicTime) -> Option<MouseEvent> {self.scroll_fling_controller.interrupt(event, now)}@@ -192,8 +192,8 @@ impl ContextState {Some(gesture_end)}- // Ends the fling, or the gesture whose momentum the platform is reporting, if it scrolls the box, so that the rest of- // its momentum scrolls nothing. Returns the end of the gesture to send on to WebContent.+ /// Ends the fling, or the gesture whose momentum the platform is reporting, if it scrolls the box, so that the rest+ /// of its momentum scrolls nothing. Returns the end of the gesture to send on to WebContent.pub fn end_momentum_scrolling(&mut self, stable_node_id: AsyncScrollNodeStableID) -> Option<MouseEvent> {if self.wheel_gesture_routing.latched_scroller() != Some(stable_node_id) {return None;@@ -217,7 +217,7 @@ impl ContextState {self.reported_scroll_momentum_was_interrupted = false;}- // Whether the wheel event from the UI is momentum, or the end, of a gesture whose momentum was interrupted.+ /// Whether the wheel event from the UI is momentum, or the end, of a gesture whose momentum was interrupted.pub fn absorbs_wheel_event_of_interrupted_momentum(&mut self, event: &MouseEvent) -> bool {if !self.reported_scroll_momentum_was_interrupted {return false;@@ -232,7 +232,7 @@ impl ContextState {false}- // The wheel event of the next step of the fling, which is scrolled by like a wheel event from the UI.+ /// The wheel event of the next step of the fling, which is scrolled by like a wheel event from the UI.pub fn take_scroll_fling_step(&mut self, frame_time: MonotonicTime) -> Option<MouseEvent> {self.scroll_fling_controller.take_step(frame_time)}@@ -347,8 +347,8 @@ impl ContextState {)}- // The first step of a gesture that the page let through, routed from the scrollers the page found around its target,- // innermost first, if this context knows one, and by a hit test otherwise.+ /// The first step of a gesture that the page let through, routed from the scrollers the page found around its+ /// target, innermost first, if this context knows one, and by a hit test otherwise.pub fn scroll_for_first_wheel_step_the_page_let_through(&mut self,step: &WheelStep,@@ -365,8 +365,8 @@ impl ContextState {)}- // A step of a gesture that the page let through and that is latched to a scroller of this context. Empty once the- // scroller is gone.+ /// A step of a gesture that the page let through and that is latched to a scroller of this context. Empty once the+ /// scroller is gone.pub fn scroll_for_latched_wheel_step_the_page_let_through(&mut self,step: &WheelStep,@@ -384,8 +384,8 @@ impl ContextState {))}- // A step of a gesture that this context has moved past scrolls once along its route, latching and stretching- // nothing.+ /// A step of a gesture that this context has moved past scrolls once along its route, latching and stretching+ /// nothing.pub fn scroll_for_overtaken_wheel_step(&mut self,step: &WheelStep,@@ -611,7 +611,7 @@ impl ContextState {self.has_async_scrolling_state && self.scene.visual_viewport_scale().unwrap_or(1.0) == 1.0}- // Whether this context's page may cancel the ctrl+wheel event of a pinch at the position, or has yet to tell.+ /// Whether this context's page may cancel the ctrl+wheel event of a pinch at the position, or has yet to tell.pub fn page_may_cancel_pinch_at(&mut self, position: FloatPoint) -> bool {if !self.has_async_scrolling_state || !self.wheel_gesture_routing.admits_async_pinch() {return true;@@ -646,7 +646,7 @@ impl ContextState {);}- // Where a position in the viewport of a context nested in this one lies in this context's viewport.+ /// Where a position in the viewport of a context nested in this one lies in this context's viewport.pub fn position_of_nested_context_position(&mut self,nested_context_id: CompositorContextId,@@ -667,8 +667,8 @@ impl ContextState {)}- // The scrollers the page found around the target of a step that it let through, innermost first, go before a hit- // test at the position of the step.+ /// The scrollers the page found around the target of a step that it let through, innermost first, go before a hit+ /// test at the position of the step.pub fn route_first_wheel_step_from_containing_context(&mut self,position: FloatPoint,@@ -786,7 +786,7 @@ impl ContextState {)}- // Latches the gesture to the scroller the route found, or to the one that keeps the step, and scrolls by the step.+ /// Latches the gesture to the scroller the route found, or to the one that keeps the step, and scrolls by the step.pub fn take_first_wheel_step_from_containing_context(&mut self,route: &FirstWheelStepRoute,diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex f68409f5bbd..e89973de7ba 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -35,7 +35,8 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind,Compositing_WheelEventAnswer as WheelEventAnswer, Compositing_WheelStepLetThrough as WheelStepLetThrough,- SharedDisplayList, compositor_control_server, compositor_presentation_server, compositor_web_content_server,+ LayerPlanOnWire, SharedDisplayList, compositor_control_server, compositor_presentation_server,+ compositor_web_content_server,};use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, DisplayList};@@ -60,6 +61,14 @@ fn display_list_timing_enabled() -> bool {const DISPLAY_LIST_WITH_UNUSABLE_SCROLLING_STATE: &str ="WebContent published a display list with scrolling state the compositor cannot use";+fn misbehavior_of_layer_plan(why_plan_fails_checks: &'static str) -> Misbehavior {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Rejecting plan of layers from WebContent: {why_plan_fails_checks}"+ );+ Misbehavior("WebContent sent a plan of layers that does not fit its display list and visual context tree")+}+// The main thread allocates the ids of the scrolls it requests from here up, so that they never meet the ids the// compositor allocates for scrolls of its own.const FIRST_OPERATION_ID_THE_MAIN_THREAD_REQUESTS: AsyncScrollOperationID = 1 << 63;@@ -231,7 +240,7 @@ impl MessagesFromWebContent<'_> {let storage = match raster.receive_display_list_chunks(packed_chunks, &packed_chunk_sizes).and_then(|sent| chunks_of_list_sent_whole(sent, &chunks_in_paint_order))- .and_then(|chunks| DisplayListStorage::of_received_chunks(&chunks))+ .and_then(DisplayListStorage::of_chunks){Ok(storage) => storage,Err(error) => {@@ -247,7 +256,7 @@ impl MessagesFromWebContent<'_> {};let tree = message.visual_context_tree;if properties.compatible_visual_context_tree_structural_epoch != tree.structural_epoch- || !tree.display_list_references_only_live_nodes(storage.command_runs())+ || !tree.display_list_references_only_live_nodes(storage.runs()){return not_rasterized("Display list does not match its visual context tree");}@@ -262,9 +271,7 @@ impl MessagesFromWebContent<'_> {let frame = ReplayFrame::unscrolled(time_ns);replay_display_list(&tree,- storage.bytes(),- storage.command_runs(),- storage.effect_clip_plan(&tree),+ &storage,properties.root_group_color,&frame,ReplaySelection::default(),@@ -314,7 +321,8 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {Ok(None) => return Ok(()),Err(error) => return Err(Misbehavior(error)),};- let storage = match DisplayListStorage::of_received_chunks(&chunks) {+ let chunk_count = chunks.len();+ let storage = match DisplayListStorage::of_chunks(chunks) {Ok(storage) => storage,Err(error) => {let _ = writeln!(@@ -329,6 +337,7 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {if !self.context_is_owned_by_sender(message.context_id)? {return Ok(());}+ self.core.forget_layer_plan(message.context_id);if properties.compatible_visual_context_tree_structural_epoch != tree.structural_epoch {let _ = writeln!(std::io::stderr(),@@ -338,7 +347,7 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {);return Ok(());}- if !tree.display_list_references_only_live_nodes(storage.command_runs()) {+ if !tree.display_list_references_only_live_nodes(storage.runs()) {let _ = writeln!(std::io::stderr(),"Compositor: Dropping display list update that names nodes its visual context tree does not hold"@@ -380,7 +389,7 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {window => window.flatten(),};let scroll_state_snapshot = message.scroll_state;- let storage_size = storage.bytes().len();+ let storage_size = storage.byte_size();let display_list = DisplayList::new(storage,properties.id,@@ -399,13 +408,19 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {) {return Err(Misbehavior(DISPLAY_LIST_WITH_UNUSABLE_SCROLLING_STATE));}+ self.core+ .take_layer_plan_of_installed_update(+ message.context_id,+ message.layer_plan.map(LayerPlanOnWire::into_received),+ )+ .map_err(misbehavior_of_layer_plan)?;self.core.keep_only_drawn_resources(message.context_id);if display_list_timing_enabled() {let _ = writeln!(std::io::stderr(),"DISPLAY_LIST_RECEIVE bytes={} chunks={} sent={sent_chunk_count} adopt={} µs install={} µs",storage_size,- chunks.len(),+ chunk_count,adopt_time.as_micros(),(started_at.elapsed() - adopt_time).as_micros());@@ -424,6 +439,7 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {if !self.context_is_owned_by_sender(message.context_id)? {return Ok(());}+ self.core.forget_layer_plan(message.context_id);let mut image_frame_ids = Vec::new();tree.for_each_effects_filter_image_frame_id(&mut |id| image_frame_ids.push(id));if !self@@ -445,6 +461,12 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {self.now,);if tree_was_replaced {+ self.core+ .take_layer_plan_of_installed_update(+ message.context_id,+ message.layer_plan.map(LayerPlanOnWire::into_received),+ )+ .map_err(misbehavior_of_layer_plan)?;self.core.keep_only_drawn_resources(message.context_id);}Ok(())@@ -467,6 +489,12 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {if self.context_is_owned_by_sender(message.context_id)? {self.core.update_scroll_state(message.context_id, scroll_state_snapshot, message.keyboard_scroll_state);+ self.core+ .take_layer_plan_of_scroll_state(+ message.context_id,+ message.layer_plan.map(LayerPlanOnWire::into_received),+ )+ .map_err(misbehavior_of_layer_plan)?;}Ok(())}diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex b32a2016f01..672f76ba9c9 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -24,6 +24,7 @@ use crate::raster_host::RasterHost;use crate::remote_layers::RemoteLayers;use crate::surfaces::painting_surface::PaintingSurface;use crate::wheel_gesture_routing::WheelGestureIdAllocator;+use libcompositing_rust::display_list::layers::UnvalidatedLayerPlan;use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, CompositorContextId, DisplayList, KeyboardScrollState, ScrollStateSnapshot,@@ -133,10 +134,9 @@ impl CompositorCore {&self,client: WebContentClientId,context_id: CompositorContextId,- sent: Vec<libcompositing_rust::display_list::storage::ReceivedChunk>,+ sent: Vec<libcompositing_rust::display_list::storage::ListChunk>,chunks_in_paint_order: &[libcompositing_rust::display_list::chunks::ChunkId],- ) -> Result<Option<Vec<std::sync::Arc<libcompositing_rust::display_list::storage::ReceivedChunk>>>, &'static str>- {+ ) -> Result<Option<Vec<std::sync::Arc<libcompositing_rust::display_list::storage::ListChunk>>>, &'static str> {self.display_list_chunk_stores.borrow_mut().take_in(client, context_id, sent, chunks_in_paint_order)@@ -731,6 +731,41 @@ impl CompositorCore {installed}+ /// Forgets the plan of layers of the context, ahead of a display list or a visual context tree from WebContent that+ /// the context may not install.+ pub fn forget_layer_plan(&self, context_id: CompositorContextId) {+ let _entered = self.enter();++ let context = self.context_if_present(context_id).expect("context exists");+ context.borrow_mut().forget_layer_plan();+ }++ /// Takes the plan of layers that came with the display list or the visual context tree the context just installed.+ /// Fails for a plan that does not pass the checks against them.+ pub fn take_layer_plan_of_installed_update(+ &self,+ context_id: CompositorContextId,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ let _entered = self.enter();++ let context = self.context_if_present(context_id).expect("context exists");+ context.borrow_mut().take_layer_plan_of_installed_update(layer_plan)+ }++ /// Takes the plan of layers that came with a scroll state, if any. Fails for a plan that does not pass the checks+ /// against the display list and the visual context tree it is of.+ pub fn take_layer_plan_of_scroll_state(+ &self,+ context_id: CompositorContextId,+ layer_plan: Option<UnvalidatedLayerPlan>,+ ) -> Result<(), &'static str> {+ let _entered = self.enter();++ let context = self.context_if_present(context_id).expect("context exists");+ context.borrow_mut().take_layer_plan_of_scroll_state(layer_plan)+ }+/// Tells the host which fonts, image frames, video sinks and SVG images the context draws, now that it took a/// display list or a visual context tree. The host keeps those for it, and lets go of the others.pub fn keep_only_drawn_resources(&self, context_id: CompositorContextId) {@@ -832,6 +867,23 @@ impl CompositorCore {}ContextTimer::SurplusStoreRetirement => self.retire_idle_surplus_backing_stores(context_id),ContextTimer::HiddenStoreRetirement => self.retire_backing_stores_of_hidden_context(context_id),+ ContextTimer::SpareTileEviction => {+ if let Some(presenting) = self.presenting_of(context_id) {+ let environment = self.environment(+ context_id,+ now,+ &libcompositing_rust::display_list::replay::NoCompositedContexts,+ );+ presenting.borrow_mut().spare_tile_eviction_timer_fired(&environment);+ }+ }+ ContextTimer::TileRasterScratchSurfaceRelease => {+ if let Some(presenting) = self.presenting_of(context_id) {+ presenting+ .borrow_mut()+ .tile_raster_scratch_surface_release_timer_fired();+ }+ }_ => {let caret_damage_rect = context.borrow_mut().timer_fired(timer, now);if let Some(caret_damage_rect) = caret_damage_rect {diff --git a/Services/Compositor/Rust/src/display_list_chunk_stores.rs b/Services/Compositor/Rust/src/display_list_chunk_stores.rsindex 02cc35df80a..75f1e0b82b4 100644--- a/Services/Compositor/Rust/src/display_list_chunk_stores.rs+++ b/Services/Compositor/Rust/src/display_list_chunk_stores.rs@@ -11,14 +11,14 @@use crate::host::WebContentClientId;use libcompositing_rust::display_list::chunks::{ChunkId, KeptChunks};use libcompositing_rust::display_list::commands::CompositorContextId;-use libcompositing_rust::display_list::storage::ReceivedChunk;+use libcompositing_rust::display_list::storage::ListChunk;use std::collections::{HashMap, HashSet};use std::sync::Arc;#[derive(Default)]struct ContextChunks {kept: KeptChunks,- chunks: HashMap<ChunkId, Arc<ReceivedChunk>>,+ chunks: HashMap<ChunkId, Arc<ListChunk>>,}#[derive(Default)]@@ -36,9 +36,9 @@ impl DisplayListChunkStores {&mut self,client: WebContentClientId,context: CompositorContextId,- sent: Vec<ReceivedChunk>,+ sent: Vec<ListChunk>,chunks_in_paint_order: &[ChunkId],- ) -> Result<Option<Vec<Arc<ReceivedChunk>>>, &'static str> {+ ) -> Result<Option<Vec<Arc<ListChunk>>>, &'static str> {if self.destroyed_contexts.contains(&context) {return Ok(None);}@@ -73,11 +73,10 @@ impl DisplayListChunkStores {/// The chunks a display list sent whole names in paint order, or an error where it names one it did not send.pub fn chunks_of_list_sent_whole(- sent: Vec<ReceivedChunk>,+ sent: Vec<ListChunk>,chunks_in_paint_order: &[ChunkId],-) -> Result<Vec<Arc<ReceivedChunk>>, &'static str> {- let sent: HashMap<ChunkId, Arc<ReceivedChunk>> =- sent.into_iter().map(|chunk| (chunk.id, Arc::new(chunk))).collect();+) -> Result<Vec<Arc<ListChunk>>, &'static str> {+ let sent: HashMap<ChunkId, Arc<ListChunk>> = sent.into_iter().map(|chunk| (chunk.id, Arc::new(chunk))).collect();chunks_in_paint_order.iter().map(|id| sent.get(id).cloned())@@ -111,7 +110,7 @@ mod tests {builder.take_chunk()}- fn sent(chunks: &[&Chunk]) -> Vec<ReceivedChunk> {+ fn sent(chunks: &[&Chunk]) -> Vec<ListChunk> {let mut packed = vec![0; packed_size_of_chunks(chunks)];write_packed_chunks(chunks, &mut packed);let sizes: Vec<PackedChunkSize> = chunks.iter().map(|chunk| PackedChunkSize::of(chunk)).collect();diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rsindex 3c0d76640ea..41d631df8fe 100644--- a/Services/Compositor/Rust/src/frame_inputs.rs+++ b/Services/Compositor/Rust/src/frame_inputs.rs@@ -6,12 +6,9 @@//! What a frame is painted with besides the display list and its resources.+use crate::context_scene::ReceivedLayerPlan;use crate::overlays::OverlayPicture;-use libcompositing_rust::display_list::damage::{- DisplayListDamage, DisplayListFrame, LayerPlans, LiveContentChanges, compute_display_list_damage,-};use libcompositing_rust::display_list::replay::ScrollbarShownByFrame;-use libcompositing_rust::display_list::storage::DisplayListStorage;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot, SpatialNodeIndex};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{Color, FloatRect, IntRect};@@ -52,21 +49,23 @@ impl Default for ScrollbarOfFrame {pub use libcompositing_rust::display_list::replay::thumb_rect_kept_inside_track;-// What a frame is painted with besides the display list and its resources.pub struct FrameInputs {pub visual_context_tree: AccumulatedVisualContextTree,+ /// The plan of layers WebContent sent for the display list and the tree it published. None where it sent none, or+ /// where the frame draws the page through a visual viewport transform other than that of the published tree, as the+ /// plan does not hold for the frame then.+ pub layer_plan: Option<ReceivedLayerPlan>,pub presented_scroll_state_snapshot: ScrollStateSnapshot,pub scrollbars: Vec<ScrollbarOfFrame>,- pub viewport_scroll_node_index: Option<SpatialNodeIndex>,- // When the frame is painted, which is the time a blinking caret shows as of.+ /// When the frame is painted, which is the time a blinking caret shows as of.pub painted_at: MonotonicTime,- // What the compositor draws over the page in the frame.+ /// What the compositor draws over the page in the frame.pub overlays: OverlayPicture,}impl FrameInputs {- // The scrollbars of the page that the frame presents, which replace the geometry the display list recorded for- // them.+ /// The scrollbars of the page that the frame presents, which replace the geometry the display list recorded for+ /// them.pub fn scrollbars_shown_for_the_page(&self) -> Vec<ScrollbarShownByFrame> {self.scrollbars.iter()@@ -82,60 +81,25 @@ impl FrameInputs {.collect()}- // What a frame painted with these inputs repaints of the frame `last_frame_inputs` painted `last_display_list`- // with, none where that has no bounds, and given the frames' layer plans, what it repaints of each layer.- pub fn damage_since(- &self,- display_list: &DisplayListStorage,- last_frame_inputs: &FrameInputs,- last_display_list: &DisplayListStorage,- viewport_rect: IntRect,- mut live_content_changes: LiveContentChanges<'_>,- layer_plans: Option<LayerPlans<'_>>,- ) -> DisplayListDamage {- let scroll_offset_changed = |index: SpatialNodeIndex| {- last_frame_inputs- .presented_scroll_state_snapshot- .device_offset_for_index(index)- != self.presented_scroll_state_snapshot.device_offset_for_index(index)- };- if self.viewport_scroll_node_index.is_some_and(scroll_offset_changed) {- return DisplayListDamage::unbounded(layer_plans.map_or(0, |plans| plans.new.layers.len()));- }- for scrollbar in &self.scrollbars {- if scrollbar.is_painted_by_compositor && scroll_offset_changed(scrollbar.scroll_node_index) {- live_content_changes.forced_damage_rect = live_content_changes- .forced_damage_rect- .united(scrollbar.thin_and_expanded_gutter_rect);- }- }- compute_display_list_damage(- last_frame_inputs.frame_of(last_display_list),- self.frame_of(display_list),- viewport_rect,- live_content_changes,- layer_plans,- )+ fn scroll_offset_changed_since(&self, last_frame_inputs: &FrameInputs, index: SpatialNodeIndex) -> bool {+ last_frame_inputs+ .presented_scroll_state_snapshot+ .device_offset_for_index(index)+ != self.presented_scroll_state_snapshot.device_offset_for_index(index)}- // Whether a frame painted with these inputs places content where one painted with `other` does: the same tree,- // scrolled the same.- pub fn places_content_like(&self, other: &FrameInputs) -> bool {- std::sync::Arc::ptr_eq(self.visual_context_tree.as_arc(), other.visual_context_tree.as_arc())- && self.presented_scroll_state_snapshot.device_offsets()- == other.presented_scroll_state_snapshot.device_offsets()- }-- fn frame_of<'a>(&'a self, display_list: &'a DisplayListStorage) -> DisplayListFrame<'a> {- let tree = self.visual_context_tree.as_arc();- DisplayListFrame {- command_bytes: display_list.bytes(),- command_runs: display_list.command_runs(),- chunks: display_list.chunks(),- effect_clip_plan: display_list.effect_clip_plan(tree),- summary: display_list.summary(),- visual_context_tree: tree,- scroll_offsets: self.presented_scroll_state_snapshot.device_offsets(),- }+ pub fn gutters_of_compositor_painted_scrollbars_that_scrolled_since(+ &self,+ last_frame_inputs: &FrameInputs,+ ) -> IntRect {+ self.scrollbars+ .iter()+ .filter(|scrollbar| {+ scrollbar.is_painted_by_compositor+ && self.scroll_offset_changed_since(last_frame_inputs, scrollbar.scroll_node_index)+ })+ .fold(IntRect::default(), |damage, scrollbar| {+ damage.united(scrollbar.thin_and_expanded_gutter_rect)+ })}}diff --git a/Services/Compositor/Rust/src/host.rs b/Services/Compositor/Rust/src/host.rsindex 7dd719cf960..923a1c4b76b 100644--- a/Services/Compositor/Rust/src/host.rs+++ b/Services/Compositor/Rust/src/host.rs@@ -32,6 +32,8 @@ pub enum ContextTimer {BackingStoreShrink,SurplusStoreRetirement,HiddenStoreRetirement,+ SpareTileEviction,+ TileRasterScratchSurfaceRelease,}/// A timer of the compositor, which fires once after the delay it is set to, until it is set again.diff --git a/Services/Compositor/Rust/src/overlays.rs b/Services/Compositor/Rust/src/overlays.rsindex b0b217cd885..33b4283f15c 100644--- a/Services/Compositor/Rust/src/overlays.rs+++ b/Services/Compositor/Rust/src/overlays.rs@@ -49,14 +49,14 @@ pub struct PausedDebuggerOverlayState {pub hovered_action: Option<PausedDebuggerOverlayAction>,}-// The controls stay present while they are hidden, so that they fade out.+/// The controls stay present while they are hidden, so that they fade out.#[derive(Clone, Copy, Debug, Default, PartialEq)]pub struct PictureInPictureControlsState {pub shown: bool,pub hovered_control: Option<PictureInPictureControl>,}-// What the browser draws over a context's page, with each overlay the view has present.+/// What the browser draws over a context's page, with each overlay the view has present.#[derive(Clone, Debug, Default, PartialEq)]pub struct UIOverlays {pub paused_debugger: Option<PausedDebuggerOverlayState>,@@ -71,10 +71,11 @@ pub struct OverlayLabel {pub glyph_ids: Vec<u32>,pub glyph_x_positions: Vec<f32>,pub width: f32,- // Of the font at the size the label is shaped at: the ascent above the baseline, which is negative, and the descent.+ /// Of the font at the size the label is shaped at: the ascent above the baseline, which is negative, and the+ /// descent.pub ascent: f32,pub descent: f32,- // The ascent the painter places glyphs below, at the font's own size.+ /// The ascent the painter places glyphs below, at the font's own size.pub font_ascent: f32,}@@ -278,6 +279,19 @@ thread_local! {});}+fn replay_overlay_records(records: &AlignedRecords, painter: &mut impl ReplayPainter) {+ OVERLAY_TREE.with(|tree| {+ let list = ListReplay::new(tree);+ let frame = ReplayFrame::unscrolled(0);+ let context = RecordsContext {+ list_replay: &list,+ frame: &frame,+ to_root_matrix_of_inline_clip_space: &|_| None,+ };+ replay_records(records.as_bytes(), &context, painter);+ });+}+impl OverlayPicture {/// Paints the overlays over a frame: the scrollbars the compositor paints, and unless they are left out, the/// overlays of the browser.@@ -288,35 +302,26 @@ impl OverlayPicture {if !paints_ui_overlays {return;}- OVERLAY_TREE.with(|tree| {- let list = ListReplay::new(tree);- let frame = ReplayFrame::unscrolled(0);- let context = RecordsContext {- list: &list,- frame: &frame,- clip_space_matrix: &|_| None,- };- replay_records(self.ui_overlay_records.as_bytes(), &context, painter);- if let Some(controls) = &self.picture_in_picture_controls {- painter.push_layer(&ReplayLayer {- can_draw_directly_for_lcd_text: false,- opacity: controls.opacity,- blend_mode: CompositingAndBlendingOperator::Normal,- filter_bytes: std::ptr::null(),- filter_bytes_size: 0,- backdrop_filter_bytes: std::ptr::null(),- backdrop_filter_bytes_size: 0,- backdrop_region: IntRect::default(),- backdrop_corner_radii: Default::default(),- backdrop_base_color: Color::TRANSPARENT,- backdrop_blur_edge: OptionalFloatRect::none(),- filter_cache_key: 0,- content_bounds: OptionalFloatRect::from(Some(controls.bounds.to_float())),- });- replay_records(controls.records.as_bytes(), &context, painter);- painter.pop();- }- });+ replay_overlay_records(&self.ui_overlay_records, painter);+ if let Some(controls) = &self.picture_in_picture_controls {+ painter.push_layer(&ReplayLayer {+ can_draw_directly_for_lcd_text: false,+ opacity: controls.opacity,+ blend_mode: CompositingAndBlendingOperator::Normal,+ filter_bytes: std::ptr::null(),+ filter_bytes_size: 0,+ backdrop_filter_bytes: std::ptr::null(),+ backdrop_filter_bytes_size: 0,+ backdrop_region: IntRect::default(),+ backdrop_corner_radii: Default::default(),+ backdrop_base_color: Color::TRANSPARENT,+ backdrop_blur_edge: OptionalFloatRect::none(),+ filter_cache_key: 0,+ content_bounds: OptionalFloatRect::from(Some(controls.bounds.to_float())),+ });+ replay_overlay_records(&controls.records, painter);+ painter.pop();+ }}}@@ -332,7 +337,7 @@ fn presented_compositor_scrollbar(scrollbar: &ScrollbarOfFrame) -> PresentedScro)}-// The records of one overlay, with the payload of each command laid out after the command as the painter reads it.+/// The records of one overlay, with the payload of each command laid out after the command as the painter reads it.struct OverlayRecorder<'a> {builder: &'a mut DisplayListBuilder,}diff --git a/Services/Compositor/Rust/src/presenting/damage.rs b/Services/Compositor/Rust/src/presenting/damage.rsindex ef83486b360..d69dc7a90d6 100644--- a/Services/Compositor/Rust/src/presenting/damage.rs+++ b/Services/Compositor/Rust/src/presenting/damage.rs@@ -6,26 +6,23 @@//! What a frame repaints of the frame painted before it, and of what each backing store holds.-use super::layers::LayerUpdate;+use super::layers::{LayerUpdate, PaintedLayers};use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, rect_of_size};use crate::frame_inputs::FrameInputs;use crate::host::PendingFrame;use crate::raster_host::LiveContent;-use libcompositing_rust::display_list::commands::{- CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkHandle,-};-use libcompositing_rust::display_list::damage::{DisplayListDamage, LayerPlans, LiveContentChanges};-use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;+use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::scrolling::DisplayList;use libgfx_rust::{IntRect, IntSize};use std::collections::{HashMap, HashSet};use std::rc::Rc;-/// The frame painted last: its display list and inputs, and the version of each live content it drew, which comparing-/// lists cannot see change.+/// The frame painted last: its display list and inputs, what it did with its layers, and the version of each live+/// content it drew, which comparing lists cannot see change.pub struct PaintedFrame {pub display_list: Rc<DisplayList>,pub frame_inputs: FrameInputs,+ pub layers: PaintedLayers,pub viewport_size: IntSize,allows_lcd_text: bool,canvas_content_generations: HashMap<u64, u64>,@@ -45,8 +42,7 @@ impl PaintedFrame {/// again, and a store that is forgotten is painted in full.#[derive(Default)]pub struct StoreDamage {- // The store painted into last is last.- accumulated: Vec<(i32, IntRect)>,+ missed_damage_by_store_least_recently_painted_first: Vec<(i32, IntRect)>,}// Twice as many as a context ever has at once.@@ -54,32 +50,34 @@ const MAXIMUM_REMEMBERED_STORE_COUNT: usize = 16;impl StoreDamage {pub fn forget_every_store(&mut self) {- self.accumulated.clear();+ self.missed_damage_by_store_least_recently_painted_first.clear();}/// What painting a frame into the store repaints: the frame's damage, and what the store missed since it was last/// painted, all of it for a store never painted into.pub fn take(&mut self, bitmap_id: i32, frame_damage: IntRect, store_rect: IntRect) -> IntRect {let mut repaint_rect = store_rect;- for (id, accumulated) in &mut self.accumulated {- if *id == bitmap_id {- repaint_rect = accumulated.united(frame_damage);+ for (store_bitmap_id, missed_damage) in &mut self.missed_damage_by_store_least_recently_painted_first {+ if *store_bitmap_id == bitmap_id {+ repaint_rect = missed_damage.united(frame_damage);}- *accumulated = accumulated.united(frame_damage);+ *missed_damage = missed_damage.united(frame_damage);}- self.accumulated.retain(|(id, _)| *id != bitmap_id);- self.accumulated.push((bitmap_id, IntRect::default()));- if self.accumulated.len() > MAXIMUM_REMEMBERED_STORE_COUNT {- self.accumulated.remove(0);+ self.missed_damage_by_store_least_recently_painted_first+ .retain(|(store_bitmap_id, _)| *store_bitmap_id != bitmap_id);+ self.missed_damage_by_store_least_recently_painted_first+ .push((bitmap_id, IntRect::default()));+ if self.missed_damage_by_store_least_recently_painted_first.len() > MAXIMUM_REMEMBERED_STORE_COUNT {+ self.missed_damage_by_store_least_recently_painted_first.remove(0);}repaint_rect}/// Damage discovered while painting the current store is still owed to the other stores.pub fn add_damage_to_other_stores(&mut self, bitmap_id: i32, damage: IntRect) {- for (id, accumulated) in &mut self.accumulated {- if *id != bitmap_id {- *accumulated = accumulated.united(damage);+ for (store_bitmap_id, missed_damage) in &mut self.missed_damage_by_store_least_recently_painted_first {+ if *store_bitmap_id != bitmap_id {+ *missed_damage = missed_damage.united(damage);}}}@@ -105,29 +103,14 @@ mod tests {}}-// The canvases, video sinks, image frames and nested contexts whose pixels changed since the frame painted last.#[derive(Default)]pub struct LiveContentChangesSinceLastPaint {- pub canvases: Vec<CanvasId>,- pub video_sinks: Vec<VideoSinkHandle>,- pub image_frames: Vec<ImageFrameResourceId>,- pub nested_contexts: Vec<CompositorContextId>,+ pub canvas_or_video_changed: bool,pub repaints_everything: bool,}-impl LiveContentChangesSinceLastPaint {- pub fn changed(&self, content: LiveMedia) -> bool {- match content {- LiveMedia::Canvas(id) => self.canvases.contains(&id),- LiveMedia::VideoFrame(id) => self.video_sinks.contains(&id),- LiveMedia::ImageFrame(id) => self.image_frames.contains(&id),- LiveMedia::CompositedContext(id) => self.nested_contexts.contains(&id),- }- }-}-pub struct FrameDamage {- pub rect: IntRect,+ pub rect_in_raster_device_pixels: IntRect,pub layers: LayerUpdate,pub live_media_changed: bool,}@@ -148,6 +131,7 @@ impl ContextPresenting {env.raster.live_content(env.context_id, &canvas_ids)}+ /// Remembers a frame that is painted, or that shows nothing new: what it draws, and what it did with its layers.pub(super) fn remember_painted_frame(&mut self,env: &PresentingEnvironment<'_>,@@ -155,7 +139,10 @@ impl ContextPresenting {display_list: &Rc<DisplayList>,frame_inputs: FrameInputs,live_content: &LiveContent,+ layer_update: LayerUpdate,) {+ let allows_lcd_text = layer_update.frame_allows_lcd_text;+ let layers = self.commit_layer_update(env, layer_update);let canvas_generation = |id: u64| {live_content.canvases@@ -180,10 +167,10 @@ impl ContextPresenting {.iter().map(|&id| (id, env.nested_contexts.frame_generation_of(CompositorContextId(id)))).collect();- let allows_lcd_text = self.allows_lcd_text(display_list, &frame_inputs);self.painted_frame = Some(PaintedFrame {display_list: display_list.clone(),frame_inputs,+ layers,viewport_size: IntSize {width: viewport_rect.width,height: viewport_rect.height,@@ -201,7 +188,7 @@ impl ContextPresenting {env: &PresentingEnvironment<'_>,viewport_size: IntSize,display_list: &DisplayList,- frame_inputs: &FrameInputs,+ allows_lcd_text: bool,live_content: &LiveContent,) -> LiveContentChangesSinceLastPaint {let mut changes = LiveContentChangesSinceLastPaint::default();@@ -211,11 +198,13 @@ impl ContextPresenting {};if painted_frame.viewport_size != viewport_size|| painted_frame.display_list.surface_clear_color() != display_list.surface_clear_color()- || painted_frame.allows_lcd_text != self.allows_lcd_text(display_list, frame_inputs)+ || painted_frame.allows_lcd_text != allows_lcd_text{changes.repaints_everything = true;}+ // Live content that no command of this list draws, such as an image that a filter of the visual context tree+ // draws, has no command in this list to damage.let canvas_ids_of_list: HashSet<u64> = display_list.storage().summary().canvas_ids.iter().copied().collect();for (canvas_id, content_generation) in &painted_frame.canvas_content_generations {let current_content_generation = live_content@@ -225,11 +214,10 @@ impl ContextPresenting {if current_content_generation == *content_generation {continue;}- // A canvas that no command of this list draws has no command in this list to damage.if !canvas_ids_of_list.contains(canvas_id) {changes.repaints_everything = true;}- changes.canvases.push(CanvasId(*canvas_id));+ changes.canvas_or_video_changed = true;}let summary = display_list.storage().summary();let image_frame_ids_of_list: HashSet<u64> = summary.image_frame_ids.iter().copied().collect();@@ -242,22 +230,18 @@ impl ContextPresenting {if current_frame_id == *frame_id {continue;}- // A video that no command of this list draws has no command in this list to damage.if !video_sink_handles_of_list.contains(video_sink_handle) {changes.repaints_everything = true;}- changes.video_sinks.push(VideoSinkHandle(*video_sink_handle));+ changes.canvas_or_video_changed = true;}for (&image_frame_id, &pixel_generation) in &live_content.image_frames {if painted_frame.image_frame_pixel_generations.get(&image_frame_id) == Some(&pixel_generation) {continue;}- // An image that no command of this list draws, such as one that a filter of the visual context tree- // draws, has no command in this list to damage.if !image_frame_ids_of_list.contains(&image_frame_id) {changes.repaints_everything = true;}- changes.image_frames.push(ImageFrameResourceId(image_frame_id));}let nested_context_ids_of_list: HashSet<u64> = summary.composited_context_ids.iter().copied().collect();for (&nested_context_id, &frame_generation) in &painted_frame.nested_context_frame_generations {@@ -268,7 +252,6 @@ impl ContextPresenting {if !nested_context_ids_of_list.contains(&nested_context_id) {changes.repaints_everything = true;}- changes.nested_contexts.push(nested_context);}changes}@@ -285,148 +268,46 @@ impl ContextPresenting {height: pending_frame.viewport_rect.height,};let viewport_rect = rect_of_size(viewport_size);+ let raster_rect = self.raster_rect();let forced_damage_rect = pending_frame.forced_damage_rect.intersected(viewport_rect);+ let allows_lcd_text = self.allows_lcd_text(frame.display_list, frame.frame_inputs);let changes = self.live_content_changes_since_last_paint(env,viewport_size,frame.display_list,- frame.frame_inputs,+ allows_lcd_text,live_content,);+ let invalidates_every_tile = changes.repaints_everything;+ let (layer_update, stale_rect) = self.layer_update_for(+ env,+ frame,+ raster_rect,+ live_content,+ invalidates_every_tile,+ allows_lcd_text,+ );+ let live_media_changed = changes.canvas_or_video_changed;- let mut layers = self.layer_update_for(frame, viewport_rect);- let shown_by_window_server = match layers.plan(&self.layers) {- Some(plan) => self.window_server_can_show_media_layers_of(env, plan, live_content),- None => false,- };- layers.shown_by_window_server = shown_by_window_server;- let layers_hold_last_frame = self.layers.has_plan() && self.painted_frame.is_some();- let keeps_layer_rasters = match (layers.plan(&self.layers), self.layers.plan()) {- (Some(plan), Some(last_plan)) => layers_hold_last_frame && plan.has_same_layers_as(last_plan),- _ => false,- };- let repaints_everything = changes.repaints_everything || forced_damage_rect.contains_rect(viewport_rect);- let damage = if repaints_everything {- DisplayListDamage {- rect: None,- layer_rects: Vec::new(),- }- } else {- self.damage_since_last_paint(- viewport_rect,- frame,- forced_damage_rect,- &changes,- &layers,- keeps_layer_rasters,- )- };- layers.painted_damage = damage.rect.unwrap_or(viewport_rect).intersected(viewport_rect);-- let layer_count = layers.plan(&self.layers).map(|plan| plan.layers.len());- match layer_count {- None => layers.repaints_everything = layers_hold_last_frame,- Some(_) if !keeps_layer_rasters => {- layers.fully_repainted_layer_bits = u32::MAX;- layers.repaints_everything = true;- }- Some(layer_count) => {- for index in 0..layer_count {- let layer_damage = if damage.layer_rects.is_empty() {- Some(layers.painted_damage)- } else {- damage.layer_rects[index]- };- if layer_damage.is_none() {- layers.fully_repainted_layer_bits |= 1 << index;- }- layers- .damage_of_layers- .push(layer_damage.unwrap_or(viewport_rect).intersected(viewport_rect));- }- }- }-- // A frame holds the canvases and videos only while the window server does not show them, so a switch either- // way repaints all of it.- if self.painted_frame.is_some() && layers.shown_by_window_server != self.layers.window_server_shows_media() {- layers.repaints_everything = true;- layers.fully_repainted_layer_bits = u32::MAX;- }-- let live_media_changed = !changes.canvases.is_empty() || !changes.video_sinks.is_empty();- if layers.repaints_everything {- return FrameDamage {- rect: viewport_rect,- layers,- live_media_changed,- };- }- let mut damage_rect = layers.painted_damage;- if let Some(plan) = layers.plan(&self.layers)- && !layers.shown_by_window_server- {- damage_rect = damage_rect- .united(super::layers::rect_of_media_layers_showing_changes(plan, &changes).intersected(viewport_rect));- }+ let scrolled_compositor_scrollbars = self.painted_frame.as_ref().map_or(IntRect::default(), |painted_frame| {+ frame+ .frame_inputs+ .gutters_of_compositor_painted_scrollbars_that_scrolled_since(&painted_frame.frame_inputs)+ });+ let forced_damage_rect =+ self.raster_rect_of(forced_damage_rect.united(scrolled_compositor_scrollbars.intersected(viewport_rect)));+ let damage_of_layers_moved_by_animated_transforms =+ self.damage_of_layers_moved_by_animated_transforms(&layer_update, raster_rect);+ let repaints_everything = invalidates_every_tile || damage_of_layers_moved_by_animated_transforms.is_none();+ let stale_rect = stale_rect.united(damage_of_layers_moved_by_animated_transforms.unwrap_or_default());FrameDamage {- rect: damage_rect,- layers,- live_media_changed,- }- }-- fn damage_since_last_paint(- &self,- viewport_rect: IntRect,- frame: &FrameToPaint<'_>,- forced_damage_rect: IntRect,- changes: &LiveContentChangesSinceLastPaint,- layers: &LayerUpdate,- keeps_layer_rasters: bool,- ) -> DisplayListDamage {- let painted_frame = self- .painted_frame- .as_ref()- .expect("a frame that does not repaint everything has a frame painted before it");- let plan = layers.plan(&self.layers);- let media_record_offsets: Vec<u32> = plan.map_or_else(Vec::new, |plan| plan.media_record_offsets().collect());- let layer_plans = match (plan, self.layers.plan()) {- (Some(plan), Some(last_plan)) if keeps_layer_rasters => Some(LayerPlans {- old: last_plan,- new: plan,- }),- _ => None,- };- let mut damage = frame.frame_inputs.damage_since(- frame.display_list.storage(),- &painted_frame.frame_inputs,- painted_frame.display_list.storage(),- viewport_rect,- LiveContentChanges {- canvases: &changes.canvases,- video_sinks: &changes.video_sinks,- image_frames: &changes.image_frames,- composited_contexts: &changes.nested_contexts,- forced_damage_rect,- offsets_of_records_composited_as_media_layers: &media_record_offsets,+ rect_in_raster_device_pixels: if repaints_everything {+ raster_rect+ } else {+ layer_update.damage_grown_over_what_composited_effects_read(forced_damage_rect.united(stale_rect))},- layer_plans,- );- if let Some(rect) = damage.rect {- damage.rect = Some(rect.intersected(viewport_rect));+ layers: layer_update,+ live_media_changed,}- damage- }-- pub(super) fn layers_keep_plan_for(&self, frame: &FrameToPaint<'_>, viewport_rect: IntRect) -> bool {- let Some(painted_frame) = &self.painted_frame else {- return false;- };- self.layers.has_plan()- && Rc::ptr_eq(&painted_frame.display_list, frame.display_list)- && painted_frame.viewport_size.width == viewport_rect.width- && painted_frame.viewport_size.height == viewport_rect.height- && frame.frame_inputs.places_content_like(&painted_frame.frame_inputs)}}diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rsindex 7125b42689e..c299e7fb4d6 100644--- a/Services/Compositor/Rust/src/presenting/layers.rs+++ b/Services/Compositor/Rust/src/presenting/layers.rs@@ -4,620 +4,1911 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The layers a frame is painted in while it draws canvases, videos or nested contexts, and what of them the window-//! server shows above the frame by itself.+//! The layers a frame is painted in, each cached as tiles from one frame and one list to the next, and what of them the+//! window server shows above the frame by itself.-use super::damage::LiveContentChangesSinceLastPaint;+use super::tiles::{LayerTiles, LayerToRaster, TileDraw, TileShownInFrame, joined_rects_of_grid_given_row_by_row};+use super::window_server::WindowServerLayers;use super::{- ContextPresenting, FrameToPaint, PresentingEnvironment, paint_overlays, rect_of_size, replay_into, replaying_only,-};-use crate::raster_host::{- FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, SublayerContentKind, SurfaceBlend,+ ContextPresenting, FrameToPaint, NestedContexts, PresentingEnvironment, apply_raster_transform,+ composite_inside_effects_of_frame, inflated, paint_overlays, rect_of_size, replay_into, replay_with_scroll_offsets,+ size_of,};+use crate::context_scene::ReceivedLayerPlan;+use crate::raster_host::LiveContent;use crate::surfaces::painting_surface::PaintingSurface;-use crate::surfaces::presentable_surface::{PresentableSurface, PresentableSurfacePool};-use libcompositing_rust::display_list::layers::{LayerKind, LayerPlan, LayerPlanInputs, build_layer_plan};-use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;-use libcompositing_rust::display_list::window_server_placement::WindowServerPlacement;-use libgfx_rust::{Color, IntRect, IntSize, ScalingMode};-use std::collections::HashMap;-use std::rc::Rc;--// Sublayers keep their identity from one frame to the next by what they show.-const CANVAS_SUBLAYER_IDENTITY_TAG: u64 = 1 << 60;-const VIDEO_SUBLAYER_IDENTITY_TAG: u64 = 2 << 60;-const PAINTED_LAYER_SUBLAYER_IDENTITY_TAG: u64 = 3 << 60;-const COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY: u64 = 4 << 60;-// Canvas and video IDs count up from 1, and stay far below this.-const MEDIA_DRAWING_INDEX_SHIFT: u32 = 44;+use libcompositing_rust::display_list::commands::{+ CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkHandle,+};+use libcompositing_rust::display_list::effect_geometry::{+ backdrop_filter_read_reach, composited_filter_read_reach_in_device_pixels, spreading_filter_of,+};+use libcompositing_rust::display_list::layers::{+ BandIndex, LayerContent, LayerIdentity, LayerIndex, LayerStack, LayeringObstacles, PlacementNodeIdentity,+ RasterSpaceIndex, SpaceToFrame, StackLayer, WhyListIsOneLayer, WindowServerPlacementsOfMedia,+};+use libcompositing_rust::display_list::placement::{+ RasterSpaceGeometry, RasterSpaces, WhatEverySpaceOfTreeShares, raster_scroll_offsets,+};+use libcompositing_rust::display_list::reach::Reach;+use libcompositing_rust::display_list::replay::{CompositeClipsOfRaster, ReplaySelection};+use libcompositing_rust::display_list::tile_keys::{+ BandTileKeys, ContentHash, FrameStateReadByReplay, LayerRasterSettings, LiveContentVersions, TileKeyingOfList,+ TileKeyingOfRasterSpace,+};+use libcompositing_rust::display_list::tiles::TILE_SIZE_IN_DEVICE_PIXELS;+use libcompositing_rust::scrolling::DisplayList;+use libcompositing_rust::visual_context::{VisualContextTree, WorldTransforms};+use libgfx_rust::{Color, CornerRadii, FloatMatrix4x4, FloatPoint, IntPoint, IntRect};+use std::borrow::Cow;+use std::cell::OnceCell;+use std::collections::{HashMap, HashSet};+use std::rc::{Rc, Weak};-#[derive(Default)]-struct LayerSurface {- surface: Option<Rc<PaintingSurface>>,- rect: IntRect,- // Changes whenever anything is drawn into the surface.- content_version: u64,+// A frame drawn with a plan may show tiles, of one color or not, of as many pixels as this many layers that each show+// every cell a rect of the viewport's size can touch, which a viewport smaller than a cell needs whole. The layers of a+// page show two or three viewports of tiles. A frame whose plan shows more is drawn as one layer, which shows no more+// than one such layer.+const MAXIMUM_LAYERS_OF_TILES_A_PLAN_SHOWS: u64 = 16;+// Each shown tile costs work whatever part of its cell it shows, so a frame drawn with a plan may show at most this many+// tiles per cell that one such layer can touch. The pages of the tests show at most about twenty.+const MAXIMUM_TILES_A_PLAN_SHOWS_PER_CELL_ONE_LAYER_SHOWS: u64 = 64;++// Growing damage over what composited effects read takes a pass over them for each one it newly reaches. Past this many+// passes, the damage grows over all they read, which holds what more passes would add.+const MAXIMUM_PASSES_GROWING_DAMAGE_OVER_WHAT_COMPOSITED_EFFECTS_READ: usize = 8;+// A tile below is tested against the opaque rects of the layers above, and against at most this many parts of it left+// uncovered. Past either bound, tiles are not hidden but drawn, which is right, only slower.+const MAXIMUM_OPAQUE_RECTS_HIDING_TILES_BELOW: usize = 128;+const MAXIMUM_UNCOVERED_PARTS_OF_TILE: usize = 64;+const MAXIMUM_COMPOSITED_EFFECT_READS_TESTED_ONE_BY_ONE: usize = 64;++#[derive(Clone, Copy, PartialEq, Eq)]+struct MediaRecordsReplayedInFrame {+ content_hash: ContentHash,+ reach_in_frame: IntRect,}-// The surface that the window server shows a painted layer from.-#[derive(Default)]-struct PaintedLayerPresentation {- surface_pool: PresentableSurfacePool,- latest_surface: Option<Rc<PresentableSurface>>,- rect: IntRect,- content_version: u64,+struct LiveContentVersionsOfFrame<'a> {+ live_content: &'a LiveContent,+ nested_contexts: &'a dyn NestedContexts,}-/// The layers of the frames of a context, and what of them the window server shows.-#[derive(Default)]-pub struct ContextLayers {- plan: Option<LayerPlan>,- surfaces: Vec<LayerSurface>,- last_content_version: u64,- // Whether the window server shows the canvases and videos of the latest frame above it.- window_server_shows_media: bool,- painted_layer_presentations: Vec<PaintedLayerPresentation>,- // The surfaces the overlays are shown from, apart from those of the painted layers.- overlay_surface_pool: PresentableSurfacePool,- latest_overlay_surface: Option<Rc<PresentableSurface>>,- overlay_rect: IntRect,+impl LiveContentVersions for LiveContentVersionsOfFrame<'_> {+ fn canvas_content_generation(&self, canvas: CanvasId) -> u64 {+ self.live_content+ .canvases+ .get(&canvas.0)+ .map_or(0, |canvas| canvas.content_generation)+ }++ fn video_frame_id(&self, video_sink: VideoSinkHandle) -> Option<u64> {+ self.live_content+ .video_sinks+ .get(&video_sink.0)+ .and_then(|sink| sink.has_frame.then_some(sink.frame_id))+ }++ fn image_frame_pixel_generation(&self, image_frame: ImageFrameResourceId) -> Option<u64> {+ self.live_content.image_frames.get(&image_frame.0).copied()+ }++ fn nested_context_frame_generation(&self, nested_context: CompositorContextId) -> Option<u64> {+ self.nested_contexts.frame_generation_of(nested_context)+ }}-impl ContextLayers {- pub fn has_plan(&self) -> bool {- self.plan.is_some()+/// Where a frame composites a layer: offset by the scroll offsets of its space's anchors, within its composite clip+/// and the rounded composite clips inside it, and whether the frame holds it or the window server shows it above the+/// frame.+#[derive(Clone, Debug)]+pub struct LayerCompositingInFrame {+ /// Where the layer is in the stack the frame draws with.+ pub(super) layer_index: LayerIndex,+ pub(super) identity: LayerIdentity,+ pub(super) space_to_frame: SpaceToFrame,+ pub(super) composite_clip: Option<IntRect>,+ pub(super) rounded_composite_clips: Vec<(IntRect, CornerRadii)>,+ pub(super) shown_by_window_server: bool,+}++// Two frames composite a layer alike wherever their stacks hold it.+impl PartialEq for LayerCompositingInFrame {+ fn eq(&self, other: &Self) -> bool {+ let Self {+ layer_index: _,+ identity,+ space_to_frame,+ composite_clip,+ rounded_composite_clips,+ shown_by_window_server,+ } = self;+ *identity == other.identity+ && *space_to_frame == other.space_to_frame+ && *composite_clip == other.composite_clip+ && *rounded_composite_clips == other.rounded_composite_clips+ && *shown_by_window_server == other.shown_by_window_server}+}- pub fn plan(&self) -> Option<&LayerPlan> {- self.plan.as_ref()+impl LayerCompositingInFrame {+ pub(super) fn rect_in_frame(&self, rect_in_layer_space: IntRect, within: IntRect) -> IntRect {+ rect_in_frame_of_space(rect_in_layer_space, self.space_to_frame, self.composite_clip, within)}- pub fn window_server_shows_media(&self) -> bool {- self.window_server_shows_media+ pub(super) fn rect_shown_in_layer_space(+ &self,+ viewport_rect: IntRect,+ composited_filter_read_reach: i32,+ ) -> IntRect {+ let shown_in_viewport = match self.composite_clip {+ Some(composite_clip) => viewport_rect.intersected(composite_clip),+ None => viewport_rect,+ };+ inflated(+ self.space_to_frame.rect_in_space(shown_in_viewport),+ composited_filter_read_reach,+ )}- pub fn drop_layers(&mut self) {- self.plan = None;- self.surfaces.clear();- self.painted_layer_presentations.clear();+ /// The layer composited, in the stack the frame worked out its compositing with.+ pub(super) fn layer_in<'a>(&self, stack: &'a LayerStack) -> &'a StackLayer {+ let layer = &stack.layers[self.layer_index.0];+ debug_assert!(layer.identity == self.identity);+ layer}}-/// The layers a frame is painted in, and what of each it repaints.-#[derive(Default)]+/// The tile keys of a band of the stack of frames, and the geometry they were bound with besides the list of the stack.+struct BandTileKeysOfFrame {+ geometry: Rc<RasterSpaceGeometry>,+ tile_keys: BandTileKeys,+}++/// What a frame paints of its layers: where it composites them, the tiles it shows of each, and the media and composited+/// effects it draws.pub struct LayerUpdate {- pub new_plan: Option<LayerPlan>,- pub keeps_plan: bool,- pub painted_damage: IntRect,- pub damage_of_layers: Vec<IntRect>,- pub fully_repainted_layer_bits: u32,- pub repaints_everything: bool,- pub shown_by_window_server: bool,+ layers: PaintedLayers,+ /// What each composited effect that reads past each of its pixels reads and draws as the frame places it.+ read_reaches_of_composited_effects_in_frame: Vec<IntRect>,+ // Per layer of the stack.+ shown_tiles_by_layer: Vec<Vec<TileShownInFrame>>,+ composited_filter_read_reach_by_layer: Vec<i32>,+ pub(super) frame_allows_lcd_text: bool,}impl LayerUpdate {- pub fn has_plan(&self) -> bool {- self.new_plan.is_some() || self.keeps_plan+ fn shown_tiles_of_layer(&self, layer_index: LayerIndex) -> &[TileShownInFrame] {+ &self.shown_tiles_by_layer[layer_index.0]}- pub fn plan<'a>(&'a self, layers: &'a ContextLayers) -> Option<&'a LayerPlan> {- if self.keeps_plan {- layers.plan.as_ref()- } else {- self.new_plan.as_ref()+ pub fn shown_by_window_server(&self) -> bool {+ self.layers.shown_by_window_server()+ }++ /// The damage grown over all that a composited effect reads wherever it reaches that, as compositing the effect+ /// reads what is composited below it, which the frame painted before holds only under what it composited above.+ pub fn damage_grown_over_what_composited_effects_read(&self, mut damage: IntRect) -> IntRect {+ for _ in 0..MAXIMUM_PASSES_GROWING_DAMAGE_OVER_WHAT_COMPOSITED_EFFECTS_READ {+ let mut grew = false;+ for &read_reach in &self.read_reaches_of_composited_effects_in_frame {+ if !read_reach.intersected(damage).is_empty() && !damage.contains_rect(read_reach) {+ damage = damage.united(read_reach);+ grew = true;+ }+ }+ if !grew {+ return damage;+ }}+ self.read_reaches_of_composited_effects_in_frame+ .iter()+ .fold(damage, |damage, &read_reach| damage.united(read_reach))}}-pub fn rect_of_media_layers_showing_changes(plan: &LayerPlan, changes: &LiveContentChangesSinceLastPaint) -> IntRect {- let mut rect = IntRect::default();- for layer in &plan.layers {- if let LayerKind::Media { content } = layer.kind- && changes.changed(content)+struct CachedRasterSpaceGeometry {+ tree_copy_number: u64,+ tree_copy_without_animation_samples: u64,+ geometry: Rc<RasterSpaceGeometry>,+}++/// The stack that frames draw with, and what they keep of it from one frame to the next while they draw with the same+/// plan, whose trees hold the same nodes and differ only in their values.+struct StackOfFrames {+ /// The plan WebContent sent, or none for one layer that replays the whole list, for a frame that is not drawn as a+ /// plan was made for. One plan stands for one list, one tree without the samples of the compositor's animations,+ /// one viewport, and the scroll offsets the plan reads.+ layer_plan: Option<ReceivedLayerPlan>,+ stack: Rc<LayerStack>,+ // Keeps the address of the list the frames draw from being taken by another list.+ display_list: Weak<DisplayList>,+ viewport_to_raster_transform: FloatMatrix4x4,+ raster_spaces: Option<RasterSpaces>,+ geometry_by_space: Vec<Option<CachedRasterSpaceGeometry>>,+ /// With the copy of the tree without the samples of the compositor's animations it was worked out of, as it reads+ /// no sample.+ what_every_space_of_tree_shares: Option<(u64, Rc<WhatEverySpaceOfTreeShares>)>,+ /// By band index, the tile keys of the bands as the latest frame drawn with the stack keyed its tiles, painted or not,+ /// or none for a band no frame has bound yet.+ band_tile_keys: Vec<Option<BandTileKeysOfFrame>>,+}++impl StackOfFrames {+ /// Keeps the geometries of the spaces of the stack the latest frame drew with where the spaces are at the same+ /// anchors under the same raster transform, as the geometry of a space does not depend on the viewport. Every band+ /// starts with no tile keys.+ fn new(+ layer_plan: Option<ReceivedLayerPlan>,+ stack: Rc<LayerStack>,+ display_list: &Rc<DisplayList>,+ viewport_to_raster_transform: FloatMatrix4x4,+ latest: Option<StackOfFrames>,+ ) -> Self {+ let geometry_by_space = match latest {+ Some(latest)+ if latest.viewport_to_raster_transform == viewport_to_raster_transform+ && latest+ .stack+ .spaces+ .iter()+ .map(|space| space.anchor)+ .eq(stack.spaces.iter().map(|space| space.anchor)) =>+ {+ latest.geometry_by_space+ }+ _ => (0..stack.spaces.len()).map(|_| None).collect(),+ };+ Self {+ layer_plan,+ band_tile_keys: (0..stack.bands.len()).map(|_| None).collect(),+ stack,+ display_list: Rc::downgrade(display_list),+ viewport_to_raster_transform,+ raster_spaces: None,+ geometry_by_space,+ what_every_space_of_tree_shares: None,+ }+ }++ /// Per raster space, its geometry under the tree and the scroll offsets of the frame.+ fn geometries_of_spaces(+ &mut self,+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ ) -> Vec<Rc<RasterSpaceGeometry>> {+ let stack = &self.stack;+ let mut geometries = Vec::with_capacity(stack.spaces.len());+ for (space_index, cached_geometry) in self.geometry_by_space.iter_mut().enumerate() {+ let raster_space_index = RasterSpaceIndex(space_index);+ // What reads the geometry of a space of a plan that holds nothing that moves within it reads no value the+ // compositor animates, and of the scroll offsets only those the plan reads. The plan leaves out the offsets+ // of the anchors of the spaces, which are the only ones a geometry's raster scroll offsets change.+ let nodes_whose_scroll_offset_geometry_readers_read = self+ .layer_plan+ .as_ref()+ .filter(|_| !stack.space_holds_content_that_moves_within_it(raster_space_index))+ .map(|layer_plan| &*layer_plan.nodes_whose_scroll_offset_plan_reads);+ let offset_of_node = |scroll_offsets: &[FloatPoint], node_index: u32| {+ scroll_offsets.get(node_index as usize).copied().unwrap_or_default()+ };+ if let Some(cached) = cached_geometry+ && (cached.tree_copy_number == tree.copy.number()+ || (nodes_whose_scroll_offset_geometry_readers_read.is_some()+ && cached.tree_copy_without_animation_samples == tree.copy_without_animation_samples()))+ && match nodes_whose_scroll_offset_geometry_readers_read {+ Some(nodes) => nodes.iter().all(|&node_index| {+ offset_of_node(&cached.geometry.raster_scroll_offsets, node_index)+ == offset_of_node(scroll_offsets, node_index)+ }),+ None => {+ cached.geometry.raster_scroll_offsets+ == raster_scroll_offsets(&stack.spaces, raster_space_index, scroll_offsets)+ }+ }+ {+ geometries.push(cached.geometry.clone());+ continue;+ }+ let raster_spaces = self+ .raster_spaces+ .get_or_insert_with(|| RasterSpaces::of_spaces(tree, stack.spaces.clone()));+ let tree_copy_without_animation_samples = tree.copy_without_animation_samples();+ let what_every_space_of_tree_shares = match &self.what_every_space_of_tree_shares {+ Some((tree_copy, shares)) if *tree_copy == tree_copy_without_animation_samples => shares,+ _ => {+ &self+ .what_every_space_of_tree_shares+ .insert((+ tree_copy_without_animation_samples,+ WhatEverySpaceOfTreeShares::of(tree),+ ))+ .1+ }+ };+ let geometry = Rc::new(RasterSpaceGeometry::new(+ tree,+ raster_spaces,+ raster_space_index,+ scroll_offsets,+ self.viewport_to_raster_transform,+ what_every_space_of_tree_shares,+ ));+ *cached_geometry = Some(CachedRasterSpaceGeometry {+ tree_copy_number: tree.copy.number(),+ tree_copy_without_animation_samples: tree.copy_without_animation_samples(),+ geometry: geometry.clone(),+ });+ geometries.push(geometry);+ }+ geometries+ }+}++/// What of a list and a tree keeps the tiles of a stack of one layer from replaying only the records that reach them,+/// worked out once for both.+struct LayeringObstaclesOfListAndTree {+ // Keeps the address of the list from being taken by another list.+ display_list: Weak<DisplayList>,+ tree_copy_number: u64,+ obstacles: LayeringObstacles,+}++/// What a frame does with its layers. Those of the latest frame that was painted, or that showed nothing new, are what a+/// snapshot of the frame on screen and what the window server shows above it are composited with until another frame is+/// painted.+pub struct PaintedLayers {+ /// The stack the frame draws with.+ pub(super) stack: Rc<LayerStack>,+ /// From the base layer up, the layers that can hold something, and where the frame composites each.+ pub(super) compositing_of_layers: Vec<LayerCompositingInFrame>,+ pub(super) window_server_placements_of_media: WindowServerPlacementsOfMedia,+ content_hash_by_composited_node: HashMap<PlacementNodeIdentity, ContentHash>,+ media_replayed_by_identity: HashMap<LayerIdentity, MediaRecordsReplayedInFrame>,+}++impl PaintedLayers {+ /// Whether the window server shows layers above the base layer of the frame.+ pub fn shown_by_window_server(&self) -> bool {+ self.compositing_of_layers+ .iter()+ .any(|compositing| compositing.shown_by_window_server)+ }+}++/// The layers of the frames of a context, their tiles, and what of them the window server shows.+#[derive(Default)]+pub struct ContextLayers {+ /// The stack the latest frame was drawn with, painted or not, and what frames keep of it.+ stack_of_frames: Option<StackOfFrames>,+ layering_obstacles_of_frames_not_drawn_as_planned: Option<LayeringObstaclesOfListAndTree>,+ pub(super) tiles: LayerTiles,+ pub(super) window_server: WindowServerLayers,+ /// The plan whose frames show more tiles than a frame may, which frames draw as one layer until another plan comes.+ /// The address of its stack is kept from being taken by the stack of another plan.+ plan_showing_too_many_tiles: Option<Weak<LayerStack>>,+}++impl ContextLayers {+ pub fn spare_tile_eviction_timer_fired(&mut self, env: &PresentingEnvironment<'_>) {+ self.tiles.evict_spare_tiles(env);+ }++ /// Whether frames draw `layer_plan` as one layer, as a frame drawn with it showed more tiles than a frame may.+ fn plan_shows_too_many_tiles(&self, layer_plan: &ReceivedLayerPlan) -> bool {+ self.plan_showing_too_many_tiles+ .as_ref()+ .is_some_and(|stack| std::ptr::eq(stack.as_ptr(), Rc::as_ptr(&layer_plan.stack)))+ }++ /// Has later frames draw the plan of the stack the frame took as one layer, as the frame showed more tiles than a+ /// frame may.+ fn draw_plan_of_frames_as_one_layer(&mut self) {+ let layer_plan = self+ .stack_of_frames+ .as_ref()+ .and_then(|stack_of_frames| stack_of_frames.layer_plan.as_ref())+ .expect("only a frame drawn with a plan has a budget of tiles");+ self.plan_showing_too_many_tiles = Some(Rc::downgrade(&layer_plan.stack));+ }++ /// The stack of one layer that replays the whole list, for a frame that is not drawn as a plan was made for, with+ /// what of the list and the tree keeps its tiles from replaying only the records that reach them, as a plan of one+ /// layer has.+ fn one_layer_stack_of_frame(+ &mut self,+ display_list: &Rc<DisplayList>,+ tree: &VisualContextTree,+ viewport_rect: IntRect,+ why_list_is_one_layer: WhyListIsOneLayer,+ ) -> LayerStack {+ let obstacles = match &self.layering_obstacles_of_frames_not_drawn_as_planned {+ Some(of_list_and_tree)+ if of_list_and_tree.tree_copy_number == tree.copy.number()+ && std::ptr::eq(of_list_and_tree.display_list.as_ptr(), Rc::as_ptr(display_list)) =>+ {+ of_list_and_tree.obstacles+ }+ _ => {+ let obstacles = LayeringObstacles::of(display_list.storage(), tree);+ self.layering_obstacles_of_frames_not_drawn_as_planned = Some(LayeringObstaclesOfListAndTree {+ display_list: Rc::downgrade(display_list),+ tree_copy_number: tree.copy.number(),+ obstacles,+ });+ obstacles+ }+ };+ LayerStack::one_layer_replaying_whole_list(+ viewport_rect,+ display_list.storage().whole_span(),+ Some(why_list_is_one_layer),+ obstacles,+ )+ }++ /// Takes the stack a frame draws with: the plan WebContent sent, or for a frame that is not drawn as a plan was+ /// made for, one layer that replays the whole list. Keeps what frames kept of the stack where the frame before drew+ /// with the same plan, or with the same one layer of the same list under the same raster transform, and answers+ /// whether the frame took another stack.+ fn take_stack_of_frame(+ &mut self,+ layer_plan: Option<&ReceivedLayerPlan>,+ display_list: &Rc<DisplayList>,+ one_layer: impl FnOnce(&mut Self) -> LayerStack,+ viewport_to_raster_transform: FloatMatrix4x4,+ ) -> bool {+ let latest_plan = self+ .stack_of_frames+ .as_ref()+ .and_then(|stack_of_frames| stack_of_frames.layer_plan.as_ref());+ if let Some(layer_plan) = layer_plan+ && latest_plan.is_some_and(|latest_plan| Rc::ptr_eq(&latest_plan.stack, &layer_plan.stack)){- rect = rect.united(layer.rect);+ return false;+ }+ let stack = match layer_plan {+ Some(layer_plan) => layer_plan.stack.clone(),+ None => {+ let one_layer = one_layer(self);+ let latest_drew_same_one_layer = self.stack_of_frames.as_ref().is_some_and(|latest| {+ latest.layer_plan.is_none()+ && latest.viewport_to_raster_transform == viewport_to_raster_transform+ && std::ptr::eq(latest.display_list.as_ptr(), Rc::as_ptr(display_list))+ && *latest.stack == one_layer+ });+ if latest_drew_same_one_layer {+ return false;+ }+ Rc::new(one_layer)+ }+ };+ self.stack_of_frames = Some(StackOfFrames::new(+ layer_plan.cloned(),+ stack,+ display_list,+ viewport_to_raster_transform,+ self.stack_of_frames.take(),+ ));+ true+ }++ pub fn tile_raster_scratch_surface_release_timer_fired(&mut self) {+ self.tiles.release_raster_scratch_surface();+ }+}++fn rect_in_frame_of_space(+ rect_in_space: IntRect,+ space_to_frame: SpaceToFrame,+ composite_clip: Option<IntRect>,+ within: IntRect,+) -> IntRect {+ let rect_in_frame = space_to_frame.rect_in_frame(rect_in_space).intersected(within);+ composite_clip.map_or(rect_in_frame, |composite_clip| {+ rect_in_frame.intersected(composite_clip)+ })+}++fn frame_rect_in_space_unless_viewport_or_transformed(+ raster_space_index: RasterSpaceIndex,+ space_to_frame: SpaceToFrame,+ viewport_rect: IntRect,+) -> Option<IntRect> {+ match space_to_frame {+ SpaceToFrame::Offset(offset) if raster_space_index != RasterSpaceIndex::VIEWPORT => {+ Some(viewport_rect.translated(-offset.x, -offset.y))}+ _ => None,}- rect}-fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacement {- let rounded_clip = placement.rounded_clip;- FfiSublayerPlacement {- content_rect: placement.content_rect,- content_to_frame: placement.content_to_viewport.values,- clip_rect: placement.clip_rect,- has_rounded_clip: rounded_clip.is_some(),- rounded_clip_rect: rounded_clip.map(|clip| clip.rect).unwrap_or_default(),- rounded_clip_radius: rounded_clip.map_or(0.0, |clip| clip.radius),- rounds_top_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_left),- rounds_top_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_right),- rounds_bottom_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_right),- rounds_bottom_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_left),- scaling_mode: placement.scaling_mode,+fn rect_of_kept_tiles(+ raster_space_index: RasterSpaceIndex,+ rect_shown: IntRect,+ viewport_rect: IntRect,+ composited_filter_read_reach: i32,+) -> IntRect {+ if raster_space_index == RasterSpaceIndex::VIEWPORT {+ return inflated(viewport_rect, composited_filter_read_reach);}+ if rect_shown.is_empty() {+ return IntRect::default();+ }+ let (margin_x_kept_for_scrolling_back, margin_y_kept_for_scrolling_back) =+ (viewport_rect.width / 2, viewport_rect.height / 2);+ rect_shown.inflated_edges(+ margin_y_kept_for_scrolling_back,+ margin_x_kept_for_scrolling_back,+ margin_y_kept_for_scrolling_back,+ margin_x_kept_for_scrolling_back,+ )+}++fn composited_filter_read_reach_by_layer(+ stack: &LayerStack,+ tree: &VisualContextTree,+ geometries: &[Rc<RasterSpaceGeometry>],+) -> Vec<i32> {+ stack.summed_read_reach_of_composited_filters_by_layer(|node_index, effect| {+ let effect_node = &tree.effect_nodes[effect.0 as usize];+ spreading_filter_of(effect_node).map_or(0, |filter| {+ composited_filter_read_reach_in_device_pixels(+ filter,+ &geometries[stack.nodes[node_index.0].raster_space_index.0]+ .world+ .draw_matrix(effect_node.spatial),+ )+ })+ })+}++/// How many cells a rect of the size of `viewport_rect` can touch.+fn cells_one_layer_shows_at_most(viewport_rect: IntRect) -> u64 {+ let tile_size = TILE_SIZE_IN_DEVICE_PIXELS as u64;+ let most_cells_along = |length: i32| (length.max(1) as u64 - 1).div_ceil(tile_size) + 1;+ most_cells_along(viewport_rect.width) * most_cells_along(viewport_rect.height)}-// A sublayer that shows a surface at its own rect, unclipped and untransformed.-fn surface_sublayer(identity: u64, surface: &Rc<PresentableSurface>, rect: IntRect) -> FfiSublayer {- FfiSublayer {- identity,- content_kind: SublayerContentKind::PresentableSurface,- media_id: 0,- presentable_surface: surface.as_ffi(),- placement: FfiSublayerPlacement {- content_rect: rect,- content_to_frame: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],- clip_rect: rect.to_float(),- scaling_mode: ScalingMode::NearestNeighbor,- ..Default::default()- },+/// The tiles a frame drawn with a plan shows so far, which it counts as it keys them, against how many it may show.+struct TileBudgetOfFrame {+ most_tiles: u64,+ most_tile_pixels: u64,+ tiles: u64,+ tile_pixels: u64,+}++impl TileBudgetOfFrame {+ fn within(viewport_rect: IntRect) -> Self {+ let cells = cells_one_layer_shows_at_most(viewport_rect);+ let cell_pixels = (TILE_SIZE_IN_DEVICE_PIXELS as u64).pow(2);+ Self {+ most_tiles: MAXIMUM_TILES_A_PLAN_SHOWS_PER_CELL_ONE_LAYER_SHOWS * cells,+ most_tile_pixels: MAXIMUM_LAYERS_OF_TILES_A_PLAN_SHOWS * cells * cell_pixels,+ tiles: 0,+ tile_pixels: 0,+ }+ }++ /// Counts a tile that shows `part_of_cell_needed`, and answers whether the frame still shows no more than it may.+ fn takes_tile(&mut self, part_of_cell_needed: IntRect) -> bool {+ self.tiles += 1;+ self.tile_pixels += part_of_cell_needed.width.max(0) as u64 * part_of_cell_needed.height.max(0) as u64;+ self.tiles <= self.most_tiles && self.tile_pixels <= self.most_tile_pixels}}-impl ContextPresenting {- pub(super) fn layer_update_for(&self, frame: &FrameToPaint<'_>, viewport_rect: IntRect) -> LayerUpdate {- let mut layers = LayerUpdate::default();- let draws_media = frame- .display_list- .storage()- .summary()- .live_content_records+fn rect_is_covered_by_union_of(rect: IntRect, covering_rects: &[IntRect]) -> bool {+ if covering_rects.iter().any(|cover| cover.contains_rect(rect)) {+ return true;+ }+ if covering_rects.iter().all(|cover| cover.intersected(rect).is_empty()) {+ return false;+ }+ let mut uncovered_parts = vec![rect];+ for &cover in covering_rects {+ if cover.intersected(rect).is_empty() {+ continue;+ }+ uncovered_parts = uncovered_parts+ .into_iter()+ .flat_map(|part| {+ let overlap = part.intersected(cover);+ if overlap.is_empty() {+ return vec![part];+ }+ let above_overlap = IntRect::new(part.x, part.y, part.width, overlap.y - part.y);+ let below_overlap =+ IntRect::new(part.x, overlap.bottom(), part.width, part.bottom() - overlap.bottom());+ let left_of_overlap = IntRect::new(part.x, overlap.y, overlap.x - part.x, overlap.height);+ let right_of_overlap = IntRect::new(+ overlap.right(),+ overlap.y,+ part.right() - overlap.right(),+ overlap.height,+ );+ [above_overlap, below_overlap, left_of_overlap, right_of_overlap]+ .into_iter()+ .filter(|piece| !piece.is_empty())+ .collect()+ })+ .collect();+ if uncovered_parts.is_empty() {+ return true;+ }+ if uncovered_parts.len() > MAXIMUM_UNCOVERED_PARTS_OF_TILE {+ return false;+ }+ }+ uncovered_parts.is_empty()+}++// A tile below is tested against what at most `MAXIMUM_COMPOSITED_EFFECT_READS_TESTED_ONE_BY_ONE` composited effects+// read, one by one. Past that, it is tested against the bounds of all they read, which hides fewer tiles.+fn composited_effect_reads_tiles_are_tested_against(read_reaches_in_frame: &[IntRect]) -> Cow<'_, [IntRect]> {+ if read_reaches_in_frame.len() <= MAXIMUM_COMPOSITED_EFFECT_READS_TESTED_ONE_BY_ONE {+ return Cow::Borrowed(read_reaches_in_frame);+ }+ Cow::Owned(vec![+ read_reaches_in_frame.iter()- .any(|live_content_record| !matches!(live_content_record.content, LiveMedia::ImageFrame(_)));- if !draws_media {- return layers;+ .fold(IntRect::default(), |bounds, &read_reach| bounds.united(read_reach)),+ ])+}++// A backdrop filter that reads past its tile by an unknown reach reads its layer's tiles wherever they are, so none of+// them may be hidden.+fn hide_tiles_covered_by_opaque_tiles_above(+ stack: &LayerStack,+ shown_tiles_by_layer: &mut [Vec<TileShownInFrame>],+ compositing_of_layers: &[LayerCompositingInFrame],+ read_reaches_of_composited_effects_in_frame: &[IntRect],+ viewport_rect: IntRect,+) {+ let composited_effect_reads_tested_against_tiles =+ composited_effect_reads_tiles_are_tested_against(read_reaches_of_composited_effects_in_frame);+ let mut opaque_rects_in_frame_above: Vec<IntRect> = Vec::new();+ for compositing in compositing_of_layers.iter().rev() {+ if opaque_rects_in_frame_above.len() > MAXIMUM_OPAQUE_RECTS_HIDING_TILES_BELOW {+ break;}- if self.layers_keep_plan_for(frame, viewport_rect) {- layers.keeps_plan = true;- return layers;+ let layer_index = compositing.layer_index;+ let layer = &stack.layers[layer_index.0];+ if !matches!(layer.content, LayerContent::Painted) {+ continue;}- let storage = frame.display_list.storage();+ let shown = &mut shown_tiles_by_layer[layer_index.0];+ let every_backdrop_read_reach_is_known = shown.iter().all(|tile| tile.raster_margin_in_device_pixels.is_some());+ if !opaque_rects_in_frame_above.is_empty() && every_backdrop_read_reach_is_known {+ shown.retain(|tile| {+ let needed_rect_in_frame = compositing.rect_in_frame(tile.part_of_cell_needed, viewport_rect);+ let is_read_by_composited_effect = composited_effect_reads_tested_against_tiles+ .iter()+ .any(|read_reach| !read_reach.intersected(needed_rect_in_frame).is_empty());+ needed_rect_in_frame.is_empty()+ || is_read_by_composited_effect+ || !rect_is_covered_by_union_of(needed_rect_in_frame, &opaque_rects_in_frame_above)+ });+ }+ let frame_holds_layer = !compositing.shown_by_window_server;+ let is_inside_composited_effects = stack.layer_is_inside_composited_effects(layer_index);+ let covers_layers_below = frame_holds_layer+ && !is_inside_composited_effects+ && compositing.rounded_composite_clips.is_empty()+ && matches!(compositing.space_to_frame, SpaceToFrame::Offset(_));+ if covers_layers_below {+ let opaque_rects_in_frame = shown+ .iter()+ .filter(|tile| tile.coverage.is_opaque())+ .map(|tile| (compositing.rect_in_frame(tile.part_of_cell_needed, viewport_rect), ()));+ opaque_rects_in_frame_above.extend(+ joined_rects_of_grid_given_row_by_row(opaque_rects_in_frame)+ .into_iter()+ .map(|(rect, _)| rect),+ );+ }+ }+}++fn layer_allows_lcd_text(stack: &LayerStack, layer_index: LayerIndex, frame_allows_lcd_text: bool) -> bool {+ frame_allows_lcd_text && layer_index == stack.base_layer && !stack.layer_is_inside_composited_effects(layer_index)+}++fn clear_color_of_layer(stack: &LayerStack, layer_index: LayerIndex, surface_clear_color: Color) -> Color {+ if layer_index == stack.base_layer {+ surface_clear_color+ } else {+ Color::TRANSPARENT+ }+}++/// Where a frame that composites its layers as the frame before did, except through other transforms of spaces whose+/// anchors the compositor animates, needs painting: where those layers were in the frame before, as the tiles that frame+/// held of them and their reach tell, and where they are now. None for a frame that composites anything else+/// differently.+fn damage_of_layers_moved_by_animated_transforms(+ compositing_of_latest_frame: &[LayerCompositingInFrame],+ bounds_of_tiles_held_by: impl Fn(&LayerIdentity) -> IntRect,+ layer_update: &LayerUpdate,+ viewport_rect: IntRect,+) -> Option<IntRect> {+ if compositing_of_latest_frame.len() != layer_update.layers.compositing_of_layers.len() {+ return None;+ }+ let mut damage = IntRect::default();+ for (latest, current) in compositing_of_latest_frame+ .iter()+ .zip(&layer_update.layers.compositing_of_layers)+ {+ if latest == current {+ continue;+ }+ let moved_by_animated_transform = matches!(+ (latest.space_to_frame, current.space_to_frame),+ (SpaceToFrame::Transform(_), SpaceToFrame::Transform(_))+ ) && LayerCompositingInFrame {+ space_to_frame: current.space_to_frame,+ ..latest.clone()+ } == *current;+ if !moved_by_animated_transform {+ return None;+ }+ let composited_filter_read_reach = layer_update.composited_filter_read_reach_by_layer[current.layer_index.0];+ let reach_in_layer_space = layer_update.layers.stack.layers[current.layer_index.0].reach;+ // A new list can shrink the reach of the layer, and the frame before showed every tile it held of the layer.+ let held_in_latest_frame = bounds_of_tiles_held_by(&latest.identity);+ damage = damage+ .united(latest.rect_in_frame(+ inflated(+ reach_in_layer_space.united(held_in_latest_frame),+ composited_filter_read_reach,+ ),+ viewport_rect,+ ))+ .united(current.rect_in_frame(+ inflated(reach_in_layer_space, composited_filter_read_reach),+ viewport_rect,+ ));+ }+ Some(damage)+}++struct CompositedEffectsOfFrame {+ stale_rect: IntRect,+ read_reaches_in_frame: Vec<IntRect>,+ content_hash_by_composited_node: HashMap<PlacementNodeIdentity, ContentHash>,+}++#[allow(clippy::too_many_arguments)]+fn composited_effects_of_frame(+ stack: &LayerStack,+ tree: &VisualContextTree,+ geometries: &[Rc<RasterSpaceGeometry>],+ tile_keying_by_raster_space: &[TileKeyingOfRasterSpace<'_>],+ composite_offsets: &[IntPoint],+ spaces_to_frame: &[SpaceToFrame],+ viewport_rect: IntRect,+ content_hash_by_composited_node_of_painted_frame: Option<&HashMap<PlacementNodeIdentity, ContentHash>>,+) -> CompositedEffectsOfFrame {+ let mut effects = CompositedEffectsOfFrame {+ stale_rect: IntRect::default(),+ read_reaches_in_frame: Vec::new(),+ content_hash_by_composited_node: HashMap::new(),+ };+ for composited in &stack.composited_effects {+ let node = &stack.nodes[composited.placement_node_index.0];+ let space_to_frame = spaces_to_frame[node.raster_space_index.0];+ let composite_clip =+ stack.composite_clip_of_node_in_viewport(composited.placement_node_index, composite_offsets);+ let rect_in_frame_of_reach = |reach: Reach<IntRect>, rect_if_anywhere: IntRect| match reach {+ Reach::Within(rect) => rect_in_frame_of_space(rect, space_to_frame, composite_clip, viewport_rect),+ Reach::Nothing => IntRect::default(),+ Reach::Anywhere => rect_if_anywhere,+ };+ let viewport_rect_within_composite_clip = composite_clip.map_or(viewport_rect, |composite_clip| {+ viewport_rect.intersected(composite_clip)+ });+ let node_reach_in_frame =+ rect_in_frame_of_reach(node.reach_in_parent_node, viewport_rect_within_composite_clip);+ let content_hash =+ tile_keying_by_raster_space[node.raster_space_index.0].content_hash_of_composited_effect(composited.effect);+ if content_hash_by_composited_node_of_painted_frame+ .and_then(|content_hashes| content_hashes.get(&node.identity))+ != Some(&content_hash)+ {+ effects.stale_rect = effects.stale_rect.united(node_reach_in_frame);+ }+ effects+ .content_hash_by_composited_node+ .insert(node.identity, content_hash);+ if composited.filter_spreads_what_it_composites {+ effects.read_reaches_in_frame.push(node_reach_in_frame);+ } else if composited.reads_what_is_composited_below_it {+ let backdrop_read_reach =+ backdrop_filter_read_reach(tree, &geometries[node.raster_space_index.0], composited.effect);+ effects+ .read_reaches_in_frame+ .push(rect_in_frame_of_reach(backdrop_read_reach, node_reach_in_frame));+ }+ }+ effects+}++fn compositing_of_layer(+ stack: &LayerStack,+ layer_index: LayerIndex,+ composite_offsets: &[IntPoint],+ spaces_to_frame: &[SpaceToFrame],+) -> LayerCompositingInFrame {+ LayerCompositingInFrame {+ layer_index,+ identity: stack.layers[layer_index.0].identity,+ space_to_frame: spaces_to_frame[stack.space_of_layer(layer_index).0],+ composite_clip: stack.composite_clip_of_layer_in_viewport(layer_index, composite_offsets),+ rounded_composite_clips: stack.rounded_composite_clips_of_node_in_viewport(+ stack.layers[layer_index.0].placement_node_index,+ composite_offsets,+ ),+ shown_by_window_server: false,+ }+}++impl ContextPresenting {+ /// Works out the layers of the frame within `viewport_rect`, in the device pixels of the raster: those of the plan+ /// WebContent sent where the frame is drawn as the plan was made for, and one layer that replays the whole list+ /// otherwise. A frame drawn with a plan that shows more tiles than a frame may is drawn as one layer instead.+ ///+ /// Keys the tiles the frame shows of each layer, and answers too the rect of the viewport that the tiles to raster+ /// again, the tiles that go, and the media replayed anew cover. `invalidates_every_tile` makes every tile stale+ /// whatever its content hash, as when the frame draws content that the list does not name. What a frame is made to+ /// repaint otherwise leaves the tiles as they are: it is either drawn over the layers by the compositor, as its+ /// scroll bars are, or told by the content hashes of the tiles that hold it, as a caret's blink is.+ pub(super) fn layer_update_for(+ &mut self,+ env: &PresentingEnvironment<'_>,+ frame: &FrameToPaint<'_>,+ viewport_rect: IntRect,+ live_content: &LiveContent,+ invalidates_every_tile: bool,+ frame_allows_lcd_text: bool,+ ) -> (LayerUpdate, IntRect) {+ if invalidates_every_tile {+ self.layers.tiles.invalidate_every_tile();+ }+ let raster_transform = self.raster_transform();let tree = frame.frame_inputs.visual_context_tree.as_arc();- layers.new_plan = build_layer_plan(&LayerPlanInputs {- tape: storage.bytes(),- command_runs: storage.command_runs(),- summary: storage.summary(),- effect_clips: storage.effect_clip_plan(tree),- tree,- scroll_offsets: frame.frame_inputs.presented_scroll_state_snapshot.device_offsets(),- viewport_rect,- })- .ok();- layers+ // A plan places spaces that scroll at whole device pixels of the viewport it was made within, which a raster+ // that scales them or shifts them by a fraction lacks, as does a viewport of another size. So only a stack of+ // one layer, in the viewport's space, is drawn under a raster transform other than identity, and what+ // composites the spaces and effects of a plan does not apply the raster transform.+ let plan_drawn_as_made_for = frame.frame_inputs.layer_plan.as_ref().filter(|layer_plan| {+ raster_transform == FloatMatrix4x4::identity() && layer_plan.viewport_rect == viewport_rect+ });+ let layer_plan = plan_drawn_as_made_for.filter(|layer_plan| !self.layers.plan_shows_too_many_tiles(layer_plan));+ let why_list_is_one_layer = if plan_drawn_as_made_for.is_some() {+ WhyListIsOneLayer::PlanShowsTooManyTiles+ } else {+ WhyListIsOneLayer::FrameIsNotDrawnAsPlanned+ };+ let one_layer = |layers: &mut ContextLayers| {+ layers.one_layer_stack_of_frame(frame.display_list, tree, viewport_rect, why_list_is_one_layer)+ };+ self.layers+ .take_stack_of_frame(layer_plan, frame.display_list, one_layer, raster_transform);+ let layer_update = self.layer_update_of_stack(env, frame, viewport_rect, live_content, frame_allows_lcd_text);+ let Some((layer_update, stale_rect)) = layer_update else {+ // Frames draw the plan as one layer from now on. The budget does not hold a frame of one layer, so the frame+ // is worked out once more at most.+ self.layers.draw_plan_of_frames_as_one_layer();+ return self.layer_update_for(+ env,+ frame,+ viewport_rect,+ live_content,+ invalidates_every_tile,+ frame_allows_lcd_text,+ );+ };+ (layer_update, stale_rect)}- pub(super) fn window_server_can_show_media_layers_of(+ /// Where a frame that composites its layers as the last painted one did, except through other transforms of spaces+ /// whose anchors the compositor animates, needs painting: where those layers were and are. None for a frame that+ /// composites anything else differently.+ pub(super) fn damage_of_layers_moved_by_animated_transforms(&self,+ layer_update: &LayerUpdate,+ viewport_rect: IntRect,+ ) -> Option<IntRect> {+ damage_of_layers_moved_by_animated_transforms(+ &self.painted_frame.as_ref()?.layers.compositing_of_layers,+ |identity| self.layers.tiles.bounds_held_by(identity),+ layer_update,+ viewport_rect,+ )+ }++ fn layer_update_of_stack(+ &mut self,env: &PresentingEnvironment<'_>,- plan: &LayerPlan,+ frame: &FrameToPaint<'_>,+ viewport_rect: IntRect,live_content: &LiveContent,- ) -> bool {- if !self.remote_layer_may_show_media(env.has_gpu) {- return false;- }- for layer in &plan.layers {- let LayerKind::Media { content } = layer.kind else {+ frame_allows_lcd_text: bool,+ ) -> Option<(LayerUpdate, IntRect)> {+ let storage = frame.display_list.storage();+ let tree = frame.frame_inputs.visual_context_tree.as_arc();+ let scroll_offsets = frame.frame_inputs.presented_scroll_state_snapshot.device_offsets();+ let raster_transform = self.raster_transform();+ let stack_of_frames = self+ .layers+ .stack_of_frames+ .as_mut()+ .expect("a frame with layers has a stack");+ let geometries = stack_of_frames.geometries_of_spaces(tree, scroll_offsets);+ let stack_the_frame_draws_with = stack_of_frames.stack.clone();+ let mut tile_budget = stack_of_frames+ .layer_plan+ .is_some()+ .then(|| TileBudgetOfFrame::within(viewport_rect));+ let stack = stack_the_frame_draws_with.as_ref();+ // Built at the first question, as only media the window server may show and spaces whose anchors the+ // compositor animates ask for it.+ let world_transforms_of_frame = OnceCell::new();+ let world_of_frame = || {+ world_transforms_of_frame+ .get_or_init(|| WorldTransforms::new(tree, scroll_offsets, Some(FloatMatrix4x4::identity())))+ };+ let window_server_may_show_media = self.why_window_server_shows_no_media_of_this_context(env).is_none();+ let window_server_placements_of_media = if window_server_may_show_media {+ stack.window_server_placements_of_media(storage, tree, world_of_frame, viewport_rect)+ } else {+ WindowServerPlacementsOfMedia::default()+ };+ let composite_offsets = stack.composite_offsets(scroll_offsets);+ let spaces_to_frame = stack.spaces_to_frame(&composite_offsets, |anchor| world_of_frame().draw_matrix(anchor));+ let shown_by_window_server_by_layer = if window_server_may_show_media {+ stack.layers_the_window_server_shows(&composite_offsets, |layer_index| {+ self.why_window_server_does_not_show_media_layer(+ env,+ &window_server_placements_of_media,+ layer_index,+ &stack.layers[layer_index.0],+ live_content,+ )+ .is_none()+ })+ } else {+ vec![false; stack.layers.len()]+ };+ let compositing_of_layers: Vec<LayerCompositingInFrame> = (stack.base_layer.0..stack.layers.len())+ .map(LayerIndex)+ .filter(|&layer_index| layer_index == stack.base_layer || stack.layers[layer_index.0].may_hold_content)+ .map(|layer_index| LayerCompositingInFrame {+ shown_by_window_server: shown_by_window_server_by_layer[layer_index.0],+ ..compositing_of_layer(stack, layer_index, &composite_offsets, &spaces_to_frame)+ })+ .collect();+ let scrollbars = frame.frame_inputs.scrollbars_shown_for_the_page();+ let live_content_versions = LiveContentVersionsOfFrame {+ live_content,+ nested_contexts: env.nested_contexts,+ };+ let tile_keying_of_list = TileKeyingOfList::new(+ storage,+ tree,+ stack,+ FrameStateReadByReplay {+ scrollbars: &scrollbars,+ time_ns: frame.frame_inputs.painted_at.nanoseconds(),+ live_content: &live_content_versions,+ },+ );+ let tile_keying_by_raster_space: Vec<TileKeyingOfRasterSpace<'_>> = geometries+ .iter()+ .map(|geometry| TileKeyingOfRasterSpace::new(&tile_keying_of_list, geometry))+ .collect();+ let surface_clear_color = frame.surface_clear_color();+ let root_group_color = frame.display_list.root_group_color();+ let raster_settings_hash_by_layer: Vec<ContentHash> = (0..stack.layers.len())+ .map(LayerIndex)+ .map(|layer_index| {+ LayerRasterSettings {+ raster_space_identity: stack.spaces[stack.space_of_layer(layer_index).0].identity,+ clear_color: clear_color_of_layer(stack, layer_index, surface_clear_color),+ root_group_color,+ viewport_to_raster_transform: raster_transform,+ allows_lcd_text: layer_allows_lcd_text(stack, layer_index, frame_allows_lcd_text),+ }+ .content_hash()+ })+ .collect();++ let composited_filter_read_reach_by_layer = composited_filter_read_reach_by_layer(stack, tree, &geometries);+ let mut shown_tiles_by_layer: Vec<Vec<TileShownInFrame>> =+ (0..stack.layers.len()).map(|_| Vec::new()).collect();+ let mut frame_shows_too_many_tiles = false;+ let band_tile_keys_by_band = &mut self+ .layers+ .stack_of_frames+ .as_mut()+ .expect("a frame with layers has a stack")+ .band_tile_keys;+ for (band_position, band) in stack.bands.iter().enumerate() {+ let band_index = BandIndex(band_position);+ if !stack.band_has_layer_at_or_above_base_layer(band_index) {continue;+ }+ let raster_space_index = stack.nodes[band.placement_node_index.0].raster_space_index;+ let tile_keying = &tile_keying_by_raster_space[raster_space_index.0];+ let compositing_of_layer_below_all_cuts =+ compositing_of_layer(stack, band.layer_below_all_cuts, &composite_offsets, &spaces_to_frame);+ let composited_filter_read_reach = composited_filter_read_reach_by_layer[band.layer_below_all_cuts.0];+ let shown_rect = compositing_of_layer_below_all_cuts+ .rect_shown_in_layer_space(viewport_rect, composited_filter_read_reach);+ // Frames drawn with one stack draw one list, so the tile keys of the band are bound to the list and the band+ // of the frame.+ let geometry = &geometries[raster_space_index.0];+ let band_tile_keys_slot = &mut band_tile_keys_by_band[band_position];+ let band_tile_keys = match band_tile_keys_slot {+ Some(band_tile_keys) if Rc::ptr_eq(&band_tile_keys.geometry, geometry) => band_tile_keys,+ _ => band_tile_keys_slot.insert(BandTileKeysOfFrame {+ geometry: geometry.clone(),+ tile_keys: tile_keying.bind_band(stack, band_index),+ }),};- let Some(Ok(placement)) = &layer.window_server_placement else {- return false;- };- let (kind, id) = match content {- LiveMedia::Canvas(id) => {- let has_presentable_surface = live_content- .canvases- .get(&id.0)- .is_some_and(|canvas| canvas.has_presentable_surface);- if !has_presentable_surface {- return false;- }- (MediaKind::Canvas, id.0)+ tile_keying.key_shown_tiles(+ &mut band_tile_keys.tile_keys,+ stack,+ band_index,+ &raster_settings_hash_by_layer,+ shown_rect,+ rect_of_kept_tiles(+ raster_space_index,+ shown_rect,+ viewport_rect,+ composited_filter_read_reach,+ ),+ frame_rect_in_space_unless_viewport_or_transformed(+ raster_space_index,+ compositing_of_layer_below_all_cuts.space_to_frame,+ viewport_rect,+ ),+ );+ for tile in band_tile_keys+ .tile_keys+ .tiles_within(shown_rect)+ .filter(|tile| tile.layer_index >= stack.base_layer)+ {+ let mut part_of_cell_needed = if tile.layer_index == stack.base_layer {+ tile.coord.cell_rect()+ } else {+ tile.content_bounds+ };+ if raster_space_index == RasterSpaceIndex::VIEWPORT {+ part_of_cell_needed =+ part_of_cell_needed.intersected(inflated(viewport_rect, composited_filter_read_reach));}- LiveMedia::VideoFrame(id) => {- let Some(sink) = live_content.video_sinks.get(&id.0).filter(|sink| sink.has_frame) else {- return false;- };- if !env.window_server_may_show_high_dynamic_range && sink.frame_holds_high_dynamic_range {- return false;- }- (MediaKind::Video, id.0)+ if part_of_cell_needed.is_empty() {+ continue;}- LiveMedia::ImageFrame(_) | LiveMedia::CompositedContext(_) => return false,- };- let Some(remote_layer) = &env.remote_layer else {- return false;- };- if !env.raster.remote_layer_can_show(- &remote_layer.layer,- env.context_id,- kind,- id,- &sublayer_placement_of(placement),- self.device_pixel_ratio,- ) {- return false;+ if let Some(tile_budget) = &mut tile_budget+ && !tile_budget.takes_tile(part_of_cell_needed)+ {+ frame_shows_too_many_tiles = true;+ break;+ }+ let coverage = self+ .layers+ .tiles+ .current_coverage(tile.content_hash, part_of_cell_needed)+ .unwrap_or_else(|| {+ tile_keying.coverage_of_tile(+ &band_tile_keys.tile_keys,+ tile,+ part_of_cell_needed,+ clear_color_of_layer(stack, tile.layer_index, surface_clear_color),+ )+ });+ shown_tiles_by_layer[tile.layer_index.0].push(TileShownInFrame {+ coord: tile.coord,+ content_hash: tile.content_hash,+ part_of_cell_needed,+ cuts: tile.cuts.clone(),+ raster_margin_in_device_pixels: tile.raster_margin_in_device_pixels,+ coverage,+ });+ }+ if frame_shows_too_many_tiles {+ break;}}- true+ if frame_shows_too_many_tiles {+ return None;+ }++ let painted = self.painted_frame.as_ref().map(|painted_frame| &painted_frame.layers);+ let composited_effects = composited_effects_of_frame(+ stack,+ tree,+ &geometries,+ &tile_keying_by_raster_space,+ &composite_offsets,+ &spaces_to_frame,+ viewport_rect,+ painted.map(|painted| &painted.content_hash_by_composited_node),+ );+ let mut stale_rect = composited_effects.stale_rect;+ hide_tiles_covered_by_opaque_tiles_above(+ stack,+ &mut shown_tiles_by_layer,+ &compositing_of_layers,+ &composited_effects.read_reaches_in_frame,+ viewport_rect,+ );+ let mut media_replayed_by_identity = HashMap::new();+ for compositing in &compositing_of_layers {+ let layer_index = compositing.layer_index;+ let layer = &stack.layers[layer_index.0];+ if let LayerContent::Media { record_span } = &layer.content {+ let raster_space_index = stack.space_of_layer(layer_index);+ let media_replayed = MediaRecordsReplayedInFrame {+ content_hash: tile_keying_by_raster_space[raster_space_index.0]+ .content_hash_of_records_within(*record_span),+ reach_in_frame: compositing.rect_in_frame(layer.reach, viewport_rect),+ };+ let media_replayed_in_latest_frame =+ painted.and_then(|painted| painted.media_replayed_by_identity.get(&layer.identity).copied());+ if !compositing.shown_by_window_server && media_replayed_in_latest_frame != Some(media_replayed) {+ stale_rect = stale_rect.united(media_replayed.reach_in_frame).united(+ media_replayed_in_latest_frame.map_or(IntRect::default(), |latest| latest.reach_in_frame),+ );+ }+ media_replayed_by_identity.insert(layer.identity, media_replayed);+ continue;+ }+ stale_rect = stale_rect.united(self.layers.tiles.stale_rect_of_layer(+ &shown_tiles_by_layer[layer_index.0],+ compositing,+ viewport_rect,+ composited_filter_read_reach_by_layer[layer_index.0],+ ));+ }+ let layer_update = LayerUpdate {+ layers: PaintedLayers {+ stack: stack_the_frame_draws_with,+ compositing_of_layers,+ window_server_placements_of_media,+ content_hash_by_composited_node: composited_effects.content_hash_by_composited_node,+ media_replayed_by_identity,+ },+ read_reaches_of_composited_effects_in_frame: composited_effects.read_reaches_in_frame,+ shown_tiles_by_layer,+ composited_filter_read_reach_by_layer,+ frame_allows_lcd_text,+ };+ Some((layer_update, stale_rect))}- pub(super) fn commit_layer_update(&mut self, layer_update: LayerUpdate) {+ /// Takes in which layers left the stack with the frame painted, or that shows nothing new, whose tiles stay in the+ /// pool for a while, and answers what the frame did with its layers.+ pub(super) fn commit_layer_update(+ &mut self,+ env: &PresentingEnvironment<'_>,+ layer_update: LayerUpdate,+ ) -> PaintedLayers {+ let painted_layers = layer_update.layers;+ let frame_draws_with_stack_of_painted_frame = self+ .painted_frame+ .as_ref()+ .is_some_and(|painted_frame| Rc::ptr_eq(&painted_frame.layers.stack, &painted_layers.stack));let layers = &mut self.layers;- layers.window_server_shows_media = layer_update.has_plan() && layer_update.shown_by_window_server;- if !layer_update.has_plan() {- layers.drop_layers();- return;- }- if let Some(new_plan) = layer_update.new_plan {- layers.plan = Some(new_plan);+ if !frame_draws_with_stack_of_painted_frame {+ let identities_in_stack: HashSet<LayerIdentity> = painted_layers+ .compositing_of_layers+ .iter()+ .map(|compositing| compositing.identity)+ .collect();+ layers.window_server.keep_only_layers(&identities_in_stack);+ layers.tiles.keep_only_layers(&identities_in_stack);}+ layers.tiles.evict_spare_tiles_if_tiles_changed(env);+ painted_layers}+ /// Paints the frame from its layers over `damage_rect`, and answers the rect it painted, which grows to the whole+ /// raster where the frame has to hold what the window server was to show above it.pub(super) fn paint_layered_frame(&mut self,env: &PresentingEnvironment<'_>,surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,- damage_rect: IntRect,- layer_update: &LayerUpdate,- ) -> bool {- // The plan a frame keeps stays with the layers, out of their way while they are painted.- let kept_plan = if layer_update.keeps_plan {- self.layers.plan.take()- } else {- None- };- let plan = kept_plan- .as_ref()- .or(layer_update.new_plan.as_ref())- .expect("a layered frame has a plan");- let painted = self.paint_layers(env, surface, frame, damage_rect, layer_update, plan);- if layer_update.keeps_plan {- self.layers.plan = kept_plan;+ mut damage_rect: IntRect,+ layer_update: &mut LayerUpdate,+ ) -> IntRect {+ env.raster.start_raster_cache_frame(env.context_id);+ // A store can miss the damage of several frames, which joined can reach part of what a composited effect reads.+ damage_rect = layer_update.damage_grown_over_what_composited_effects_read(damage_rect);+ let rects_painted_straight = self.raster_tiles_of_layers(env, surface, frame, layer_update);++ if layer_update.shown_by_window_server() {+ let presented_to_window_server = rects_painted_straight.is_empty()+ && self.present_painted_layers_to_window_server(env, &layer_update.layers, surface)+ && self.present_compositor_overlays_to_window_server(env, frame, surface);+ if !presented_to_window_server {+ for compositing in &mut layer_update.layers.compositing_of_layers {+ compositing.shown_by_window_server = false;+ }+ damage_rect = self.raster_rect();+ }}- painted++ self.composite_frame_from_layers(env, surface, frame, damage_rect, layer_update, &rects_painted_straight);+ damage_rect}- fn paint_layers(+ /// Rasters the tiles that each painted layer of the frame shows and that lack current pixels, and answers the+ /// rects of the frame where tiles are painted straight from the list instead.+ fn raster_tiles_of_layers(&mut self,env: &PresentingEnvironment<'_>,- surface: &Rc<PaintingSurface>,+ like: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,- damage_rect: IntRect,- layer_update: &LayerUpdate,- plan: &LayerPlan,- ) -> bool {+ layer_update: &mut LayerUpdate,+ ) -> Vec<IntRect> {let raster = env.raster;- let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);- raster.start_raster_cache_frame(env.context_id);- let layer_count = plan.layers.len();-- let mut surfaces = std::mem::take(&mut self.layers.surfaces);- surfaces.resize_with(layer_count, LayerSurface::default);- for (index, layer) in plan.layers.iter().enumerate() {- let layer_surface = &mut surfaces[index];- let is_base = matches!(layer.kind, LayerKind::Base);- let rect = if is_base {- rect_of_size(self.raster_size())- } else {- self.raster_rect_of(layer.rect)- };- if matches!(layer.kind, LayerKind::Media { .. }) || rect.is_empty() {- *layer_surface = LayerSurface::default();+ let viewport_rect = self.raster_rect();+ let (raster_scale, raster_translation) = (self.raster_scale, self.raster_translation);+ let surface_clear_color = frame.surface_clear_color();+ let holder_count_by_content_hash = self.layers.tiles.holder_counts(&layer_update.shown_tiles_by_layer);+ let stack_of_frames = self+ .layers+ .stack_of_frames+ .as_ref()+ .expect("a frame with layers has a stack");+ debug_assert!(Rc::ptr_eq(&layer_update.layers.stack, &stack_of_frames.stack));+ let stack = layer_update.layers.stack.as_ref();+ let tiles_replay_the_whole_list = stack.one_layer_list_cannot_tell_which_records_show_in_tile();+ let mut rects_painted_straight = Vec::new();+ for compositing in &layer_update.layers.compositing_of_layers {+ let layer_index = compositing.layer_index;+ let layer = &stack.layers[layer_index.0];+ if matches!(layer.content, LayerContent::Media { .. }) {continue;}- let mut repaints_whole_layer = (layer_update.fully_repainted_layer_bits & (1 << index)) != 0;- let surface_fits = if is_base {- layer_surface.rect == rect- } else {- layer_surface.rect.contains_rect(rect)- };- let shares_backend = layer_surface- .surface- .as_ref()- .is_some_and(|layer_surface| layer_surface.shares_backend_with(surface));- if layer_surface.surface.is_none() || !surface_fits || !shares_backend {- let Some(new_surface) = raster.create_surface(- IntSize {- width: rect.width,- height: rect.height,- },- Some(surface),- false,- ) else {- self.layers.surfaces = surfaces;- return false;- };- *layer_surface = LayerSurface {- surface: Some(new_surface),- rect,- content_version: 0,+ let raster_space_index = stack.space_of_layer(layer_index);+ let composited_filter_read_reach = layer_update.composited_filter_read_reach_by_layer[layer_index.0];+ let rect_shown_in_layer_space =+ compositing.rect_shown_in_layer_space(viewport_rect, composited_filter_read_reach);+ let allows_lcd_text = layer_allows_lcd_text(stack, layer_index, layer_update.frame_allows_lcd_text);+ let frame_rect_in_layer_space = frame_rect_in_space_unless_viewport_or_transformed(+ raster_space_index,+ compositing.space_to_frame,+ viewport_rect,+ );+ let replay_tiles = |target: &Rc<PaintingSurface>, tiles_replayed: &[&TileShownInFrame]| {+ let band_tile_keys = stack_of_frames.band_tile_keys[layer.band_index.0]+ .as_ref()+ .expect("a band with shown tiles has tile keys");+ let geometry = &band_tile_keys.geometry;+ let record_spans = (!tiles_replay_the_whole_list).then(|| {+ band_tile_keys+ .tile_keys+ .record_spans_of_tiles(tiles_replayed.iter().map(|tile| {+ band_tile_keys+ .tile_keys+ .tile(tile.coord, layer_index)+ .expect("a shown tile is keyed")+ }))+ });+ let selection = ReplaySelection {+ record_spans: record_spans.as_deref(),+ clips_left_to_composite: (!geometry.clips_left_to_composite.is_empty())+ .then_some(&geometry.clips_left_to_composite[..]),+ composited_effect: stack.nodes[layer.placement_node_index.0].composited_effect,+ allows_lcd_text,+ frame_edge_backdrop_blurs_mirror_at: frame_rect_in_layer_space.map(IntRect::to_float),+ raster_root: stack.spaces[raster_space_index.0].raster_root(),+ ..ReplaySelection::default()};- repaints_whole_layer = true;- }- let repaint_rect = if repaints_whole_layer {- layer_surface.rect- } else {- self.raster_rect_of(layer_update.damage_of_layers[index])- .intersected(layer_surface.rect)+ apply_raster_transform(raster, target, raster_scale, raster_translation);+ replay_with_scroll_offsets(env, target, frame, selection, &geometry.raster_scroll_offsets);};- if repaint_rect.is_empty() {- continue;- }- let target = layer_surface.surface.as_ref().expect("the layer has a surface");- let save_count = raster.save(target);- raster.translate(target, -layer_surface.rect.x as f32, -layer_surface.rect.y as f32);- raster.clip_rect(target, repaint_rect);- raster.clear(- target,- if is_base {- surface_clear_color- } else {- Color::TRANSPARENT+ let rastered = self.layers.tiles.raster_layer(+ env,+ like,+ LayerToRaster {+ identity: compositing.identity,+ shown: layer_update.shown_tiles_of_layer(layer_index),+ rect_shown_in_layer_space,+ kept_tile_rect: rect_of_kept_tiles(+ raster_space_index,+ rect_shown_in_layer_space,+ viewport_rect,+ composited_filter_read_reach,+ ),+ clear_color: clear_color_of_layer(stack, layer_index, surface_clear_color),+ rastered_within: (raster_space_index == RasterSpaceIndex::VIEWPORT).then_some(viewport_rect),},+ &holder_count_by_content_hash,+ replay_tiles,+ );+ rects_painted_straight.extend(+ rastered+ .rects_painted_straight+ .into_iter()+ .map(|rect_in_layer_space| compositing.rect_in_frame(rect_in_layer_space, viewport_rect)),);- self.apply_raster_transform(raster, target);- replay_into(env, target, frame, replaying_only(&layer.record_spans, false));- raster.restore_to_count(target, save_count);- self.layers.last_content_version += 1;- layer_surface.content_version = self.layers.last_content_version;}- self.layers.surfaces = surfaces;+ rects_painted_straight+ }+ fn composite_frame_from_layers(+ &self,+ env: &PresentingEnvironment<'_>,+ surface: &Rc<PaintingSurface>,+ frame: &FrameToPaint<'_>,+ damage_rect: IntRect,+ layer_update: &LayerUpdate,+ rects_painted_straight: &[IntRect],+ ) {+ let raster = env.raster;let save_count = raster.save(surface);raster.clip_rect(surface, damage_rect);- if let Some(base_surface) = self.layers.surfaces.first()- && let Some(base) = &base_surface.surface- && base_surface.rect.intersected(damage_rect) != IntRect::default()+ if let Some(base_layer_compositing) = layer_update.layers.compositing_of_layers.first()+ && self.layers.tiles.has_layer(&base_layer_compositing.identity){- raster.draw_surface(- surface,- base,- IntRect::new(0, 0, base_surface.rect.width, base_surface.rect.height),- base_surface.rect,- SurfaceBlend::Source,- );+ // The base layer replaces what is below it, and nothing is below it outside its composite clip. Plans+ // clip no base layer, but the compositor does not trust a plan from WebContent.+ if base_layer_compositing.composite_clip.is_some() {+ raster.clear(surface, frame.surface_clear_color());+ }+ self.layers+ .tiles+ .copy_into(raster, surface, damage_rect, base_layer_compositing);}- if !layer_update.shown_by_window_server {- self.composite_layers_above_base_with_plan(env, surface, frame, plan, damage_rect);+ self.composite_layers_above_base_of_stack(+ env,+ surface,+ frame,+ damage_rect,+ &layer_update.layers,+ &layer_update.composited_filter_read_reach_by_layer,+ false,+ );+ if !layer_update.shown_by_window_server() {+ let selection_painting_straight = ReplaySelection {+ allows_lcd_text: layer_update.frame_allows_lcd_text,+ ..Default::default()+ };+ for &rect_painted_straight in rects_painted_straight {+ let damaged_rect_painted_straight = rect_painted_straight.intersected(damage_rect);+ if damaged_rect_painted_straight.is_empty() {+ continue;+ }+ let save_count = raster.save(surface);+ raster.clip_rect(surface, damaged_rect_painted_straight);+ raster.clear(surface, frame.surface_clear_color());+ self.apply_raster_transform(raster, surface);+ replay_into(env, surface, frame, selection_painting_straight);+ raster.restore_to_count(surface, save_count);+ }self.apply_raster_transform(raster, surface);paint_overlays(env, surface, frame.frame_inputs, true);}raster.restore_to_count(surface, save_count);-- // The window server shows everything above the base layer from surfaces of its own.- if layer_update.shown_by_window_server {- if !self.present_painted_layers_to_window_server(env, plan, surface) {- return false;- }- if !self.present_compositor_overlays_to_window_server(env, frame, surface) {- return false;- }- }- true}- pub(super) fn composite_layers_above_base(+ /// Composites the layers above the base layer that the window server showed with the latest frame into the+ /// surface, which holds the rest of the frame, as for a snapshot of the frame on screen.+ pub(super) fn composite_layers_shown_by_window_server(&self,env: &PresentingEnvironment<'_>,surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,damage_rect: IntRect,+ painted: &PaintedLayers,) {- let Some(plan) = self.layers.plan() else {- return;- };- self.composite_layers_above_base_with_plan(env, surface, frame, plan, damage_rect);+ self.composite_layers_above_base_of_stack(env, surface, frame, damage_rect, painted, &[], true);}- fn composite_layers_above_base_with_plan(+ #[allow(clippy::too_many_arguments)]+ fn composite_layers_above_base_of_stack(&self,env: &PresentingEnvironment<'_>,surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,- plan: &LayerPlan,damage_rect: IntRect,+ painted_layers: &PaintedLayers,+ composited_filter_read_reach_by_layer: &[i32],+ composites_layers_the_window_server_shows: bool,) {- for (index, layer) in plan.layers.iter().enumerate().skip(1) {- if matches!(layer.kind, LayerKind::Media { .. }) {- if !self.raster_rect_of(layer.rect).intersected(damage_rect).is_empty() {- let save_count = env.raster.save(surface);- self.apply_raster_transform(env.raster, surface);- replay_into(env, surface, frame, replaying_only(&layer.record_spans, true));- env.raster.restore_to_count(surface, save_count);+ let (stack, compositing_of_layers) = (&painted_layers.stack, &painted_layers.compositing_of_layers);+ if compositing_of_layers+ .iter()+ .skip(1)+ .all(|compositing| compositing.shown_by_window_server != composites_layers_the_window_server_shows)+ {+ return;+ }+ debug_assert!(self.raster_transform() == FloatMatrix4x4::identity());+ composite_inside_effects_of_frame(env, surface, frame, |compositing_session| {+ let mut entered_composited_bands: Vec<BandIndex> = Vec::new();+ let mut composited_bands_around_layer: Vec<BandIndex> = Vec::new();+ for compositing in compositing_of_layers+ .iter()+ .skip(1)+ .filter(|compositing| compositing.shown_by_window_server == composites_layers_the_window_server_shows)+ {+ let layer_index = compositing.layer_index;+ let layer = compositing.layer_in(stack);+ let damage_grown_by_filter_reads = inflated(+ damage_rect,+ composited_filter_read_reach_by_layer+ .get(layer_index.0)+ .copied()+ .unwrap_or(0),+ );+ composited_bands_around_layer.clear();+ composited_bands_around_layer.extend(stack.composited_bands_around_layer_innermost_first(layer_index));+ composited_bands_around_layer.reverse();+ let count_of_bands_still_entered = entered_composited_bands+ .iter()+ .zip(&composited_bands_around_layer)+ .take_while(|(entered, around_layer)| entered == around_layer)+ .count();+ while entered_composited_bands.len() > count_of_bands_still_entered {+ compositing_session.leave_effect();+ entered_composited_bands.pop();+ }+ for &band_index in &composited_bands_around_layer[count_of_bands_still_entered..] {+ let effect = stack.nodes[stack.bands[band_index.0].placement_node_index.0]+ .composited_effect+ .expect("a composited band is of a composited node");+ compositing_session.enter_effect(effect);+ entered_composited_bands.push(band_index);+ }+ if let LayerContent::Media { record_span } = &layer.content {+ if !compositing+ .rect_in_frame(layer.reach, damage_grown_by_filter_reads)+ .is_empty()+ {+ compositing_session.replay_records(*record_span);+ }+ continue;+ }+ let clips_of_layer = CompositeClipsOfRaster {+ rect: compositing.composite_clip,+ rounded_rects: &compositing.rounded_composite_clips,+ };+ let (layer_to_frame_offset, layer_to_frame_transform) = match compositing.space_to_frame {+ SpaceToFrame::Offset(offset) => (offset, None),+ SpaceToFrame::Transform(transform) => (IntPoint::default(), Some(transform)),+ };+ for draw in self+ .layers+ .tiles+ .draws_reaching_into(compositing, damage_grown_by_filter_reads)+ {+ match draw {+ TileDraw::TileSurface {+ surface,+ rect_in_layer_space,+ } => compositing_session.draw_raster(+ surface.as_ffi().cast_mut().cast(),+ rect_of_size(size_of(rect_in_layer_space)),+ rect_in_layer_space.translated(layer_to_frame_offset.x, layer_to_frame_offset.y),+ clips_of_layer,+ layer_to_frame_transform,+ ),+ TileDraw::FillOfJoinedOneColorTiles {+ rect_in_layer_space,+ color,+ } if color.alpha() != 0 => {+ compositing_session.fill_rect(+ rect_in_layer_space.translated(layer_to_frame_offset.x, layer_to_frame_offset.y),+ color,+ clips_of_layer,+ layer_to_frame_transform,+ );+ }+ TileDraw::FillOfJoinedOneColorTiles { .. } => {}+ }}- continue;}- let Some(layer_surface) = self.layers.surfaces.get(index) else {- continue;- };- let Some(source) = &layer_surface.surface else {- continue;- };- if layer_surface.rect.intersected(damage_rect).is_empty() {- continue;+ for _ in entered_composited_bands {+ compositing_session.leave_effect();}- env.raster.draw_surface(- surface,- source,- IntRect::new(0, 0, layer_surface.rect.width, layer_surface.rect.height),- layer_surface.rect,- SurfaceBlend::SourceOver,- );- }+ });}+}- // Each painted layer goes to the window server as its own surface, which is copied from its raster when the raster- // changes. The window server may still show the surface of the frame before, so the copy goes into another one.- fn present_painted_layers_to_window_server(- &mut self,- env: &PresentingEnvironment<'_>,- plan: &LayerPlan,- like: &Rc<PaintingSurface>,- ) -> bool {- let raster = env.raster;- let layers = &mut self.layers;- // The surfaces of the layers that the plan no longer has go with them.- layers- .painted_layer_presentations- .resize_with(plan.layers.len(), PaintedLayerPresentation::default);- for (index, layer) in plan.layers.iter().enumerate() {- let presentation = &mut layers.painted_layer_presentations[index];- let layer_surface = layers.surfaces.get(index);- let source = layer_surface.and_then(|layer_surface| layer_surface.surface.as_ref());- let (Some(layer_surface), Some(source)) = (layer_surface, source) else {- presentation.latest_surface = None;- continue;- };- if !matches!(layer.kind, LayerKind::Painted) || layer.rect.is_empty() {- presentation.latest_surface = None;- continue;- }- if presentation.latest_surface.is_some()- && presentation.rect == layer.rect- && presentation.content_version == layer_surface.content_version- {- continue;- }- let layer_size = IntSize {- width: layer.rect.width,- height: layer.rect.height,- };- let Some(presentable) =- presentation- .surface_pool- .surface_for_next_content(layer_size, like.gpu_backend_context(), || {- raster.create_presentable_surface(layer_size, like)- })- else {- return false;- };- let target = presentable.painting_surface();- let source_rect = IntRect::new(- layer.rect.x - layer_surface.rect.x,- layer.rect.y - layer_surface.rect.y,- layer.rect.width,- layer.rect.height,- );- raster.draw_surface(- target,- source,- source_rect,- rect_of_size(layer_size),- SurfaceBlend::Source,- );- presentation.latest_surface = Some(presentable);- presentation.rect = layer.rect;- presentation.content_version = layer_surface.content_version;- }- true+#[cfg(test)]+mod tests {+ use super::*;+ use libcompositing_rust::display_list::builder::DisplayListBuilder;+ use libcompositing_rust::display_list::commands::{+ ContextRef, EffectNodeIndex, FillRect, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,+ };+ use libcompositing_rust::display_list::storage::DisplayListStorage;+ use libcompositing_rust::display_list::tiles::TileCoord;+ use libcompositing_rust::visual_context::{SpatialData, TransformData, TransformDataRole};+ use libgfx_rust::{AffineTransform, CompositingAndBlendingOperator, FloatRect};+ use std::sync::Arc;++ const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);++ fn tree_of_viewport() -> Arc<VisualContextTree> {+ Arc::new(VisualContextTree::create(TransformData {+ matrix: FloatMatrix4x4::identity(),+ origin: FloatPoint::default(),+ sorting_context_root_index: None,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: false,+ bounds: FloatRect::default(),+ }))}- fn present_compositor_overlays_to_window_server(- &mut self,- env: &PresentingEnvironment<'_>,- frame: &FrameToPaint<'_>,- like: &Rc<PaintingSurface>,+ fn display_list_recorded_by(builder: DisplayListBuilder, tree: &Arc<VisualContextTree>) -> Rc<DisplayList> {+ Rc::new(DisplayList::new(+ DisplayListStorage::recorded(&builder.finish(), tree.clone()),+ 1,+ tree.structural_epoch,+ None,+ None,+ Default::default(),+ ))+ }++ fn empty_display_list(tree: &Arc<VisualContextTree>) -> Rc<DisplayList> {+ display_list_recorded_by(DisplayListBuilder::new(), tree)+ }++ fn one_layer_of(display_list: &Rc<DisplayList>, viewport_rect: IntRect) -> LayerStack {+ LayerStack::one_layer_replaying_whole_list(+ viewport_rect,+ display_list.storage().whole_span(),+ None,+ LayeringObstacles::default(),+ )+ }++ fn scaled_twice() -> FloatMatrix4x4 {+ let mut matrix = FloatMatrix4x4::identity();+ matrix.elements[0][0] = 2.0;+ matrix.elements[1][1] = 2.0;+ matrix+ }++ fn frame_keeps_what_frames_kept_of_the_stack(+ layers: &mut ContextLayers,+ layer_plan: Option<&ReceivedLayerPlan>,+ display_list: &Rc<DisplayList>,+ one_layer: LayerStack,) -> bool {- let raster = env.raster;- let bounds = frame.frame_inputs.overlays.bounds;- self.layers.overlay_rect = bounds;- if bounds.is_empty() {- self.layers.latest_overlay_surface = None;- return true;- }- let bounds_size = IntSize {- width: bounds.width,- height: bounds.height,+ !layers.take_stack_of_frame(layer_plan, display_list, |_| one_layer, FloatMatrix4x4::identity())+ }++ // A plan received again is another plan, even where it holds what the plan before held.+ fn plan_and_plan_received_again(display_list: &Rc<DisplayList>) -> (ReceivedLayerPlan, ReceivedLayerPlan) {+ let plan = ReceivedLayerPlan {+ viewport_rect: VIEWPORT,+ stack: Rc::new(one_layer_of(display_list, VIEWPORT)),+ nodes_whose_scroll_offset_plan_reads: Rc::default(),};- let Some(presentable) =- self.layers- .overlay_surface_pool- .surface_for_next_content(bounds_size, like.gpu_backend_context(), || {- raster.create_presentable_surface(bounds_size, like)- })- else {- return false;+ let plan_received_again = ReceivedLayerPlan {+ stack: Rc::new((*plan.stack).clone()),+ ..plan.clone()};- let target = presentable.painting_surface();- raster.clear(target, Color::TRANSPARENT);- let save_count = raster.save(target);- raster.translate(target, -bounds.x as f32, -bounds.y as f32);- paint_overlays(env, target, frame.frame_inputs, true);- raster.restore_to_count(target, save_count);- self.layers.latest_overlay_surface = Some(presentable);- true+ (plan, plan_received_again)+ }++ #[test]+ fn frames_keep_what_they_kept_of_a_stack_only_while_they_draw_with_the_same_plan() {+ let tree = tree_of_viewport();+ let display_list = empty_display_list(&tree);+ let (plan, plan_received_again) = plan_and_plan_received_again(&display_list);+ let mut layers = ContextLayers::default();+ let one_layer = || one_layer_of(&display_list, VIEWPORT);+ let mut keeps =+ |layer_plan| frame_keeps_what_frames_kept_of_the_stack(&mut layers, layer_plan, &display_list, one_layer());+ assert!(!keeps(Some(&plan)));+ assert!(keeps(Some(&plan)));+ assert!(!keeps(Some(&plan_received_again)));+ assert!(!keeps(None));+ assert!(keeps(None));+ assert!(!keeps(Some(&plan_received_again)));}- pub(super) fn sublayers_shown_by_window_server(&self, live_content: &LiveContent) -> Vec<FfiSublayer> {- let layers = &self.layers;- let mut sublayers = Vec::new();- let Some(plan) = layers.plan.as_ref().filter(|_| layers.window_server_shows_media) else {- return sublayers;+ #[test]+ fn frames_not_drawn_as_planned_keep_their_stack_of_one_layer_only_while_it_is_the_same() {+ let tree = tree_of_viewport();+ let display_list = empty_display_list(&tree);+ let another_display_list = empty_display_list(&tree);+ let resized_viewport = IntRect::new(0, 0, 400, 300);+ let mut layers = ContextLayers::default();+ let mut keeps = |display_list: &Rc<DisplayList>, viewport_rect: IntRect| {+ let one_layer = one_layer_of(display_list, viewport_rect);+ frame_keeps_what_frames_kept_of_the_stack(&mut layers, None, display_list, one_layer)};- // The same canvas or video can be drawn by more than one record, and each drawing is a sublayer of its own.- let mut drawings_of_media: HashMap<u64, u64> = HashMap::new();- for (index, layer) in plan.layers.iter().enumerate().skip(1) {- if let LayerKind::Media { content } = layer.kind {- let Some(Ok(placement)) = &layer.window_server_placement else {- continue;- };- let (kind, id, mut identity, has_content) = match content {- LiveMedia::Canvas(id) => (- SublayerContentKind::Canvas,- id.0,- CANVAS_SUBLAYER_IDENTITY_TAG | id.0,- live_content- .canvases- .get(&id.0)- .is_some_and(|canvas| canvas.has_presentable_surface),- ),- LiveMedia::VideoFrame(id) => (- SublayerContentKind::Video,- id.0,- VIDEO_SUBLAYER_IDENTITY_TAG | id.0,- live_content- .video_sinks- .get(&id.0)- .is_some_and(|sink| sink.has_frame && sink.frame_has_surface),- ),- LiveMedia::ImageFrame(_) | LiveMedia::CompositedContext(_) => continue,- };- if !has_content {- continue;- }- let earlier_drawings = drawings_of_media.entry(identity).or_insert(0);- identity |= *earlier_drawings << MEDIA_DRAWING_INDEX_SHIFT;- *earlier_drawings += 1;- sublayers.push(FfiSublayer {- identity,- content_kind: kind,- media_id: id,- presentable_surface: std::ptr::null_mut(),- placement: sublayer_placement_of(placement),- });- continue;- }- let Some(presentation) = layers.painted_layer_presentations.get(index) else {- continue;- };- let Some(surface) = &presentation.latest_surface else {- continue;- };- sublayers.push(surface_sublayer(- PAINTED_LAYER_SUBLAYER_IDENTITY_TAG | index as u64,- surface,- presentation.rect,- ));+ assert!(!keeps(&display_list, VIEWPORT));+ assert!(keeps(&display_list, VIEWPORT));+ assert!(!keeps(&another_display_list, VIEWPORT));+ assert!(!keeps(&another_display_list, resized_viewport));+ assert!(keeps(&another_display_list, resized_viewport));+ }++ #[test]+ fn a_new_stack_keeps_the_geometries_of_spaces_at_the_same_anchors_under_the_same_raster_transform() {+ let tree = tree_of_viewport();+ let display_list = empty_display_list(&tree);+ let identity = FloatMatrix4x4::identity();+ let resized_viewport = IntRect::new(0, 0, 400, 300);+ let mut layers = ContextLayers::default();+ layers.take_stack_of_frame(None, &display_list, |_| one_layer_of(&display_list, VIEWPORT), identity);+ let stack_of_frames = layers.stack_of_frames.as_mut().expect("the frame took a stack");+ let geometry = stack_of_frames.geometries_of_spaces(&tree, &[]).remove(0);++ assert!(layers.take_stack_of_frame(+ None,+ &display_list,+ |_| one_layer_of(&display_list, resized_viewport),+ identity+ ));+ let resized = layers.stack_of_frames.as_mut().expect("the frame took a stack");+ assert!(Rc::ptr_eq(&resized.geometries_of_spaces(&tree, &[])[0], &geometry));++ layers.take_stack_of_frame(+ None,+ &display_list,+ |_| one_layer_of(&display_list, resized_viewport),+ scaled_twice(),+ );+ let scaled = layers.stack_of_frames.as_ref().expect("the frame took a stack");+ assert!(scaled.geometry_by_space.iter().all(Option::is_none));+ }++ // A red plane in front of a blue plane that covers the viewport, though the red plane comes first in the list, as+ // `transform-style: preserve-3d` and `translateZ()` make them.+ fn planes_sorted_by_depth() -> (Arc<VisualContextTree>, Rc<DisplayList>) {+ let mut tree = (*tree_of_viewport()).clone();+ let plane = |tree: &mut VisualContextTree,+ parent: SpatialNodeIndex,+ sorting_context_root: Option<SpatialNodeIndex>,+ matrix: FloatMatrix4x4| {+ tree.append_spatial(+ SpatialData::Transform(TransformData {+ matrix,+ origin: FloatPoint::default(),+ sorting_context_root_index: sorting_context_root,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: sorting_context_root.is_none(),+ bounds: VIEWPORT.to_float(),+ }),+ parent,+ )+ };+ let context_root = plane(&mut tree, VISUAL_VIEWPORT_NODE_INDEX, None, FloatMatrix4x4::identity());+ let mut moved_forward = FloatMatrix4x4::identity();+ moved_forward.elements[2][3] = 10.0;+ let red_plane = plane(&mut tree, context_root, Some(context_root), moved_forward);+ let blue_plane = plane(&mut tree, context_root, Some(context_root), FloatMatrix4x4::identity());+ let tree = Arc::new(tree);+ let mut builder = DisplayListBuilder::new();+ for (spatial, color) in [+ (red_plane, Color::from_rgb(255, 0, 0)),+ (blue_plane, Color::from_rgb(0, 0, 255)),+ ] {+ builder.append(+ &FillRect {+ rect: VIEWPORT,+ color,+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ },+ &[],+ ContextRef {+ spatial,+ ..ContextRef::default()+ },+ );}- if let Some(surface) = &layers.latest_overlay_surface {- sublayers.push(surface_sublayer(- COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY,- surface,- layers.overlay_rect,- ));+ let display_list = display_list_recorded_by(builder, &tree);+ (tree, display_list)+ }++ // A frame is not drawn as planned at a pinch, at a resize, or under the raster transform of a nested context.+ #[test]+ fn frames_not_drawn_as_planned_look_at_a_list_and_a_tree_once_for_what_keeps_tiles_from_replaying_part_of_it() {+ let (tree, display_list) = planes_sorted_by_depth();+ let mut layers = ContextLayers::default();+ let not_as_planned = WhyListIsOneLayer::FrameIsNotDrawnAsPlanned;+ let stack = layers.one_layer_stack_of_frame(&display_list, &tree, VIEWPORT, not_as_planned);+ assert!(stack.one_layer_list_cannot_tell_which_records_show_in_tile());++ // The list and the tree are looked at once for the frames that draw them.+ let obstacles_of_list_and_tree = stack.layering_obstacles;+ layers+ .layering_obstacles_of_frames_not_drawn_as_planned+ .as_mut()+ .expect("the obstacles of the list and the tree are kept")+ .obstacles+ .mask_declared_under_effects_its_mask_is_not_under = true;+ let stack_of_next_frame = layers.one_layer_stack_of_frame(&display_list, &tree, VIEWPORT, not_as_planned);+ assert!(+ stack_of_next_frame+ .layering_obstacles+ .mask_declared_under_effects_its_mask_is_not_under+ );+ let another_tree = Arc::new((*tree).clone());+ let stack_of_another_tree =+ layers.one_layer_stack_of_frame(&display_list, &another_tree, VIEWPORT, not_as_planned);+ assert_eq!(stack_of_another_tree.layering_obstacles, obstacles_of_list_and_tree);+ }++ // A spinner that the compositor rotates, whose label a new list makes shorter.+ #[test]+ fn a_layer_moved_by_an_animated_transform_damages_what_it_showed_in_the_frame_before() {+ let tree = tree_of_viewport();+ let display_list = empty_display_list(&tree);+ let short_label = IntRect::new(0, 0, 100, 20);+ let long_label = IntRect::new(0, 0, 300, 20);+ // The one layer of the stack reaches as far as the short label.+ let stack = one_layer_of(&display_list, short_label);+ let composited_at = |y: f32| LayerCompositingInFrame {+ layer_index: LayerIndex(0),+ identity: stack.layers[0].identity,+ space_to_frame: SpaceToFrame::Transform(AffineTransform::new(1.0, 0.0, 0.0, 1.0, 100.0, y)),+ composite_clip: None,+ rounded_composite_clips: Vec::new(),+ shown_by_window_server: false,+ };+ let (latest, current) = (composited_at(100.0), composited_at(200.0));+ let layer_update = layer_update_of(Rc::new(stack), vec![current.clone()], Vec::new());+ // The frame before held the tiles of the long label.+ let damage = damage_of_layers_moved_by_animated_transforms(+ std::slice::from_ref(&latest),+ |_| long_label,+ &layer_update,+ VIEWPORT,+ )+ .expect("only an animated transform moved the layer");+ assert!(damage.contains_rect(latest.rect_in_frame(long_label, VIEWPORT)));+ assert!(damage.contains_rect(current.rect_in_frame(short_label, VIEWPORT)));+ }++ // The layer update of a frame that shows no tiles, of a stack whose layers it each composites.+ fn layer_update_of(+ stack: Rc<LayerStack>,+ compositing_of_layers: Vec<LayerCompositingInFrame>,+ read_reaches_of_composited_effects_in_frame: Vec<IntRect>,+ ) -> LayerUpdate {+ LayerUpdate {+ shown_tiles_by_layer: compositing_of_layers.iter().map(|_| Vec::new()).collect(),+ composited_filter_read_reach_by_layer: vec![0; compositing_of_layers.len()],+ layers: PaintedLayers {+ stack,+ compositing_of_layers,+ window_server_placements_of_media: WindowServerPlacementsOfMedia::default(),+ content_hash_by_composited_node: HashMap::new(),+ media_replayed_by_identity: HashMap::new(),+ },+ read_reaches_of_composited_effects_in_frame,+ frame_allows_lcd_text: false,}- sublayers+ }++ fn layer_update_with_read_reaches(read_reaches_of_composited_effects_in_frame: Vec<IntRect>) -> LayerUpdate {+ let stack = one_layer_of(&empty_display_list(&tree_of_viewport()), VIEWPORT);+ layer_update_of(Rc::new(stack), Vec::new(), read_reaches_of_composited_effects_in_frame)+ }++ // Composited effects whose reads overlap in a chain, listed from the far end of the chain, so that each pass over+ // them grows the damage by one more.+ #[test]+ fn damage_grows_over_a_long_chain_of_what_composited_effects_read_in_a_bounded_number_of_passes() {+ let chain_of_reads = |length: i32| -> Vec<IntRect> {+ (0..length)+ .rev()+ .map(|index| IntRect::new(10 + index * 10, 0, 15, 10))+ .collect()+ };+ let damage = IntRect::new(0, 0, 12, 10);+ let read_apart = IntRect::new(500, 500, 10, 10);+ let mut short_chain = chain_of_reads(3);+ short_chain.push(read_apart);+ let grown = layer_update_with_read_reaches(short_chain).damage_grown_over_what_composited_effects_read(damage);+ assert_eq!(grown, IntRect::new(0, 0, 45, 10));++ let length = 4 * MAXIMUM_PASSES_GROWING_DAMAGE_OVER_WHAT_COMPOSITED_EFFECTS_READ as i32;+ let long_chain = chain_of_reads(length);+ let grown =+ layer_update_with_read_reaches(long_chain.clone()).damage_grown_over_what_composited_effects_read(damage);+ assert!(long_chain.iter().all(|read| grown.contains_rect(*read)));+ assert!(+ layer_update_with_read_reaches(long_chain).damage_grown_over_what_composited_effects_read(read_apart)+ == read_apart+ );+ }++ // The squares of a checkerboard, light ones first, as layers above would leave them, split what they leave of a+ // tile into many parts before the dark ones cover the rest.+ #[test]+ fn a_tile_that_rects_cover_only_after_splitting_it_into_many_parts_is_not_hidden() {+ let tile = IntRect::new(0, 0, 512, 512);+ let squares_of_color = |color: i32| {+ (0..32)+ .flat_map(|row| (0..32).map(move |column| (row, column)))+ .filter(move |(row, column)| (row + column) % 2 == color)+ .map(|(row, column)| IntRect::new(column * 16, row * 16, 16, 16))+ };+ let checkerboard: Vec<IntRect> = squares_of_color(0).chain(squares_of_color(1)).collect();+ assert!(!rect_is_covered_by_union_of(tile, &checkerboard));+ assert!(rect_is_covered_by_union_of(+ tile,+ &[IntRect::new(0, 0, 300, 512), IntRect::new(200, 0, 312, 512)]+ ));+ }++ // A frame from another process can composite many effects that each read past each of their pixels.+ #[test]+ fn tiles_are_tested_against_the_bounds_of_what_composited_effects_read_past_a_bound() {+ let reads: Vec<IntRect> = (0..MAXIMUM_COMPOSITED_EFFECT_READS_TESTED_ONE_BY_ONE as i32)+ .map(|index| IntRect::new(index * 10, 0, 5, 5))+ .collect();+ assert_eq!(*composited_effect_reads_tiles_are_tested_against(&reads), reads[..]);+ let mut reads_past_bound = reads;+ reads_past_bound.push(IntRect::new(0, 1000, 5, 5));+ let tested = composited_effect_reads_tiles_are_tested_against(&reads_past_bound);+ assert_eq!(tested.len(), 1);+ assert!(reads_past_bound.iter().all(|read| tested[0].contains_rect(*read)));+ }++ // Many layers that each hold a fill of the whole viewport, of one color or not, or many small fills.+ #[test]+ fn a_frame_drawn_with_a_plan_shows_tiles_of_any_color_up_to_a_budget_of_pixels_and_of_tiles() {+ // A viewport of 800 by 600 pixels touches at most 3 by 3 cells.+ let cells_shown_most = MAXIMUM_LAYERS_OF_TILES_A_PLAN_SHOWS * 9;+ let whole_cell = TileCoord::new(0, 0).cell_rect();+ let one_pixel = IntRect::new(0, 0, 1, 1);+ let mut budget_of_whole_cells = TileBudgetOfFrame::within(VIEWPORT);+ assert!((0..cells_shown_most).all(|_| budget_of_whole_cells.takes_tile(whole_cell)));+ assert!(!budget_of_whole_cells.takes_tile(one_pixel));+ let tiles_shown_most = MAXIMUM_TILES_A_PLAN_SHOWS_PER_CELL_ONE_LAYER_SHOWS * 9;+ let mut budget_of_small_tiles = TileBudgetOfFrame::within(VIEWPORT);+ assert!((0..tiles_shown_most).all(|_| budget_of_small_tiles.takes_tile(one_pixel)));+ assert!(!budget_of_small_tiles.takes_tile(one_pixel));+ }++ #[test]+ fn a_plan_whose_frame_shows_more_tiles_than_a_frame_may_is_drawn_as_one_layer_until_another_plan_comes() {+ let tree = tree_of_viewport();+ let display_list = empty_display_list(&tree);+ let (plan, plan_received_again) = plan_and_plan_received_again(&display_list);+ let mut layers = ContextLayers::default();+ layers.take_stack_of_frame(+ Some(&plan),+ &display_list,+ |_| unreachable!("a frame drawn with a plan takes its stack"),+ FloatMatrix4x4::identity(),+ );+ assert!(!layers.plan_shows_too_many_tiles(&plan));+ layers.draw_plan_of_frames_as_one_layer();+ assert!(layers.plan_shows_too_many_tiles(&plan));+ assert!(!layers.plan_shows_too_many_tiles(&plan_received_again));+ }++ // An iframe smaller than a cell shows a whole cell of each layer whose space it scrolls.+ #[test]+ fn the_tiles_of_a_viewport_smaller_than_a_cell_are_counted_in_whole_cells() {+ assert_eq!(cells_one_layer_shows_at_most(IntRect::new(0, 0, 1, 1)), 1);+ assert_eq!(cells_one_layer_shows_at_most(IntRect::new(0, 0, 100, 40)), 4);+ assert_eq!(cells_one_layer_shows_at_most(IntRect::new(0, 0, 800, 1)), 3);+ assert_eq!(cells_one_layer_shows_at_most(VIEWPORT), 9);+ assert_eq!(cells_one_layer_shows_at_most(IntRect::new(0, 0, 1025, 513)), 6);}}diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rsindex aecec86a672..c6d9ca93a65 100644--- a/Services/Compositor/Rust/src/presenting/mod.rs+++ b/Services/Compositor/Rust/src/presenting/mod.rs@@ -11,6 +11,8 @@mod damage;mod layers;pub mod pacing;+mod tiles;+mod window_server;use crate::backing_stores::{AllocationOutcome, BackingStores, Publication, StorePublication, StoreResizeOutcome};use crate::frame_inputs::FrameInputs;@@ -21,19 +23,15 @@ use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;use damage::{PaintedFrame, StoreDamage};use layers::ContextLayers;-use libcompositing_rust::display_list::commands::{CompositorContextId, EffectNodeIndex};+use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::display_list::replay::{- CompositedContexts, NoCompositedContexts, ReplayFrame, ReplaySelection, ResolvedCompositedContext,- replay_display_list,+ CompositedContexts, CompositingInsideEffects, NoCompositedContexts, ReplayFrame, ReplaySelection,+ ResolvedCompositedContext, composite_inside_effects, replay_display_list,};-use libcompositing_rust::host::RecordSpan;+use libcompositing_rust::host::FfiRasterPainter;use libcompositing_rust::scrolling::DisplayList;use libcompositing_rust::time::{Duration, MonotonicTime};-use libcompositing_rust::visual_context::EffectNodeData;-use libgfx_rust::{- Color, CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize,- enclosing_int_rect,-};+use libgfx_rust::{Color, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize, enclosing_int_rect};use pacing::PacedTickRequest;use std::rc::Rc;@@ -85,18 +83,21 @@ pub struct PreparedFrame {pub bitmap_id: i32,pub damage_rect: IntRect,pub device_pixel_ratio: f64,- // What the window server shows above the frame, bottom to top, lent by the presenting state until the next frame.+ /// What the window server shows above the frame, bottom to top, lent by the presenting state until the next frame.pub sublayers: Vec<FfiSublayer>,}-// The display list and the frame inputs a frame is painted with.pub(crate) struct FrameToPaint<'a> {pub display_list: &'a Rc<DisplayList>,pub frame_inputs: &'a FrameInputs,}-// Bounds the embedding scale of a nested context's raster, so that its surface uses at most 64 MiB, even when an-// embedding transform magnifies a large iframe.+impl FrameToPaint<'_> {+ pub fn surface_clear_color(&self) -> Color {+ self.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT)+ }+}+fn bounded_composited_raster_scale(mut scale: FloatSize, viewport_size: IntSize) -> FloatSize {if viewport_size.width <= 0 || viewport_size.height <= 0 {return FloatSize {@@ -110,13 +111,13 @@ fn bounded_composited_raster_scale(mut scale: FloatSize, viewport_size: IntSize)};// Reserve a pixel on each axis for fractional placement.const MAXIMUM_DIMENSION: f32 = 16384.0;- const MAXIMUM_PIXELS: f32 = 16.0 * 1024.0 * 1024.0;+ const MAXIMUM_PIXEL_COUNT_OF_64_MIB_SURFACE: f32 = 16.0 * 1024.0 * 1024.0;scale.width = scale.width.min((MAXIMUM_DIMENSION - 1.0) / viewport_size.width as f32);scale.height = scale.height.min((MAXIMUM_DIMENSION - 1.0) / viewport_size.height as f32);let pixel_count = (viewport_size.width as f32 * scale.width) * (viewport_size.height as f32 * scale.height);- const MAXIMUM_CONTENT_PIXELS: f32 = MAXIMUM_PIXELS - 2.0 * MAXIMUM_DIMENSION - 1.0;+ const MAXIMUM_CONTENT_PIXELS: f32 = MAXIMUM_PIXEL_COUNT_OF_64_MIB_SURFACE - 2.0 * MAXIMUM_DIMENSION - 1.0;if pixel_count > MAXIMUM_CONTENT_PIXELS {let factor = (MAXIMUM_CONTENT_PIXELS / pixel_count).sqrt();scale.width *= factor;@@ -129,15 +130,29 @@ fn rect_of_size(size: IntSize) -> IntRect {IntRect::new(0, 0, size.width, size.height)}+fn size_of(rect: IntRect) -> IntSize {+ IntSize {+ width: rect.width,+ height: rect.height,+ }+}++fn inflated(rect: IntRect, margin: i32) -> IntRect {+ if rect.is_empty() || margin == 0 {+ return rect;+ }+ rect.inflated_edges(margin, margin, margin, margin)+}+pub struct ContextPresenting {pub presents_to_client: bool,pub display_id: Option<u64>,pub display_refresh_rate: f64,- // Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.+ /// Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.pub presents_from_cpu_memory: bool,pub scales_frames_to_fit: bool,pub shown_in_remote_layer: bool,- // The viewport size of the frame that the page presented last, which it laid out at.+ /// The viewport size of the frame that the page presented last, which it laid out at.pub size_laid_out_by_page: IntSize,pub rendering_opportunity_request: PacedTickRequest,pub clock_tick_request: PacedTickRequest,@@ -153,11 +168,9 @@ pub struct ContextPresenting {frame_without_store_in_flight: bool,backing_stores: BackingStores,- // The frame that the latest rendered surface holds, which the presented frame runs ahead of while its GPU work is in- // flight.+ sublayers_of_latest_frame: Vec<FfiSublayer>,size_of_latest_rendered_frame: IntSize,store_damage: StoreDamage,- damage_surface: Option<Rc<PaintingSurface>>,surplus_store_retirement_is_scheduled: bool,// The context was hidden long enough to keep only the store that holds its latest frame, and gets no new stores// until it is shown again.@@ -193,9 +206,9 @@ impl ContextPresenting {frame_generation: 0,frame_without_store_in_flight: false,backing_stores: BackingStores::default(),+ sublayers_of_latest_frame: Vec::new(),size_of_latest_rendered_frame: IntSize::default(),store_damage: StoreDamage::default(),- damage_surface: None,surplus_store_retirement_is_scheduled: false,stores_are_retired_while_hidden: false,surface_drawn_by_parent: None,@@ -217,11 +230,6 @@ impl ContextPresenting {self.backing_stores.publication()}- // The window server reads what it shows above the store straight from GPU memory.- pub fn remote_layer_may_show_media(&self, has_gpu: bool) -> bool {- self.shown_in_remote_layer && has_gpu && !self.presents_from_cpu_memory- }-pub fn set_viewport_size(&mut self,viewport_size: IntSize,@@ -245,7 +253,7 @@ impl ContextPresenting {self.window_resize_in_progress = false;}- // The viewport rect of the next frame, or of the frame presented last, at the viewport size.+ /// The viewport rect of the next frame, or of the frame presented last, at the viewport size.pub fn viewport_rect_of_current_frame(&self) -> Option<IntRect> {if self.viewport_size.is_empty() {return None;@@ -301,8 +309,6 @@ impl ContextPresenting {};if outcome != StoreResizeOutcome::Unchanged {self.painted_frame = None;- // A partial repaint must inherit the pixel geometry of the new backing stores.- self.damage_surface = None;self.store_damage.forget_every_store();}outcome@@ -478,8 +484,6 @@ impl ContextPresenting {pub fn start_retiring_stores_while_hidden(&mut self) {self.stores_are_retired_while_hidden = true;- // The scratch surface of partial repaints is made again for the next one.- self.damage_surface = None;}/// Answers whether the stores were retired while the context was hidden.@@ -569,6 +573,8 @@ impl ContextPresenting {})}+ /// What a parent that draws the context tells its frames apart by: it changes with each frame queued, and each time+ /// a frame cannot be painted into the surface the parent draws.pub fn frame_generation(&self) -> u64 {self.frame_generation}@@ -672,6 +678,14 @@ impl ContextPresenting {}}+ fn raster_rect(&self) -> IntRect {+ rect_of_size(self.raster_size())+ }++ fn raster_transform(&self) -> FloatMatrix4x4 {+ raster_transform_of(self.raster_scale, self.raster_translation)+ }+fn raster_rect_of(&self, rect: IntRect) -> IntRect {if rect.is_empty() {return IntRect::default();@@ -714,62 +728,65 @@ impl ContextPresenting {frame_inputs: &frame_inputs,};let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);- let mut damage_rect = frame_damage.rect;+ let mut damage_rect = frame_damage.rect_in_raster_device_pixels;// NB: A changed content rect must still reach the client even if the pixels are identical.if damage_rect.is_empty() && self.presented_frame == Some(pending_frame.viewport_rect) {let only_media_shown_by_window_server_changed =- frame_damage.layers.shown_by_window_server && frame_damage.live_media_changed;- self.commit_layer_update(frame_damage.layers);+ frame_damage.layers.shown_by_window_server() && frame_damage.live_media_changed;self.remember_painted_frame(env,pending_frame.viewport_rect,display_list,frame_inputs,&live_content,+ frame_damage.layers,);- if !only_media_shown_by_window_server_changed {+ let sublayers = self.sublayers_shown_by_window_server(&live_content);+ let media_shown_by_window_server_moved_resized_or_turned = sublayers != self.sublayers_of_latest_frame;+ if !only_media_shown_by_window_server_changed && !media_shown_by_window_server_moved_resized_or_turned {return None;}self.frame_without_store_in_flight = true;+ self.sublayers_of_latest_frame = sublayers.clone();return Some(PreparedFrame {rendered_surface: None,bitmap_id: -1,damage_rect: IntRect::default(),device_pixel_ratio: self.device_pixel_ratio,- sublayers: self.sublayers_shown_by_window_server(&live_content),+ sublayers,});}- let raster_damage_rect = self.raster_rect_of(damage_rect);let Some((bitmap_id, store)) = self.backing_stores.acquire_render_target() else {self.queue_present_frame(pending_frame);return None;};let store_rect = rect_of_size(store.size());- let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);- self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);- let full_damage_rect = rect_of_size(IntSize {- width: pending_frame.viewport_rect.width,- height: pending_frame.viewport_rect.height,- });- if frame_damage.layers.repaints_everything && damage_rect != full_damage_rect {- damage_rect = full_damage_rect;- self.store_damage- .add_damage_to_other_stores(bitmap_id, self.raster_rect_of(damage_rect));+ let repaint_rect = self.store_damage.take(bitmap_id, damage_rect, store_rect);+ let painted_rect = self.paint_layered_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);+ // The other stores miss all of what this one now holds.+ if painted_rect != repaint_rect {+ damage_rect = rect_of_size(IntSize {+ width: pending_frame.viewport_rect.width,+ height: pending_frame.viewport_rect.height,+ });+ self.store_damage.add_damage_to_other_stores(bitmap_id, painted_rect);}- self.commit_layer_update(frame_damage.layers);self.remember_painted_frame(env,pending_frame.viewport_rect,display_list,frame_inputs,&live_content,+ frame_damage.layers,);+ let sublayers = self.sublayers_shown_by_window_server(&live_content);+ self.sublayers_of_latest_frame = sublayers.clone();Some(PreparedFrame {rendered_surface: Some(store),bitmap_id,damage_rect,device_pixel_ratio: self.device_pixel_ratio,- sublayers: self.sublayers_shown_by_window_server(&live_content),+ sublayers,})}@@ -791,30 +808,39 @@ impl ContextPresenting {None => return,},};- let live_content = self.live_content(env, display_list);- let frame = FrameToPaint {- display_list,- frame_inputs: &frame_inputs,- };- let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);+ // The surface comes first, so that a frame that cannot be painted does not work out its layers.let raster_size = self.raster_size();- let (surface, repaint_rect) = match self.surface_drawn_by_parent.take() {- Some(surface) if surface.size() == raster_size => (surface, self.raster_rect_of(frame_damage.rect)),+ let (surface, holds_earlier_frame) = match self.surface_drawn_by_parent.take() {+ Some(surface) if surface.size() == raster_size => (surface, true),_ => {let Some(surface) = env.raster.create_surface(raster_size, None, false) else {+ // The parent draws nothing of the context into the tiles it rasters now. A new generation makes+ // the next frame of the parent key those tiles again, and so paint the context again.+ self.frame_generation += 1;return;};- (surface, rect_of_size(raster_size))+ (surface, false)}};- self.paint_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers);- self.commit_layer_update(frame_damage.layers);+ let live_content = self.live_content(env, display_list);+ let frame = FrameToPaint {+ display_list,+ frame_inputs: &frame_inputs,+ };+ let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);+ let repaint_rect = if holds_earlier_frame {+ frame_damage.rect_in_raster_device_pixels+ } else {+ rect_of_size(raster_size)+ };+ let _ = self.paint_layered_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers);self.remember_painted_frame(env,pending_frame.viewport_rect,display_list,frame_inputs,&live_content,+ frame_damage.layers,);env.raster.flush(&surface);self.surface_drawn_by_parent = Some(surface);@@ -835,22 +861,40 @@ impl ContextPresenting {display_list,frame_inputs,};- self.paint_current_display_list(env, target, &frame, None, false, false);+ let save_count = env.raster.save(target);+ replay_into(env, target, &frame, ReplaySelection::default());+ paint_overlays(env, target, frame_inputs, false);+ env.raster.restore_to_count(target, save_count);env.raster.flush(target);}/// The surface that holds the frame on screen as a whole, with what the window server shows above the store/// composited into it, and the size of the frame in it.pub fn presented_frame_for_snapshot(- &mut self,+ &self,env: &PresentingEnvironment<'_>,) -> Option<(Rc<PaintingSurface>, IntSize)> {- let latest_rendered_surface = self.backing_stores.latest_rendered_surface()?;- let mut source = latest_rendered_surface;- // The store then holds only what is under the canvases, videos and overlays that the window server shows above it.- if self.layers.window_server_shows_media()- && self.layers.has_plan()- && let Some(painted_frame) = self.painted_frame.take()+ let source = self.surface_of_presented_frame_with_window_server_layers_composited_in(env)?;+ let source_size = source.size();+ let frame_size = IntSize {+ width: self.size_of_latest_rendered_frame.width.min(source_size.width),+ height: self.size_of_latest_rendered_frame.height.min(source_size.height),+ };+ if frame_size.is_empty() {+ return None;+ }+ Some((source, frame_size))+ }++ fn surface_of_presented_frame_with_window_server_layers_composited_in(+ &self,+ env: &PresentingEnvironment<'_>,+ ) -> Option<Rc<PaintingSurface>> {+ let mut source = self.backing_stores.latest_rendered_surface()?;+ if let Some(painted_frame) = self+ .painted_frame+ .as_ref()+ .filter(|painted_frame| painted_frame.layers.shown_by_window_server()){let source_size = source.size();let composited = env.raster.create_surface(source_size, Some(&source), false);@@ -867,125 +911,30 @@ impl ContextPresenting {remote_layer: env.remote_layer.clone(),..*env};- self.composite_layers_above_base(&snapshot_env, &composited, &frame, source_rect);+ self.composite_layers_shown_by_window_server(+ &snapshot_env,+ &composited,+ &frame,+ source_rect,+ &painted_frame.layers,+ );paint_overlays(&snapshot_env, &composited, &painted_frame.frame_inputs, true);source = composited;}- self.painted_frame = Some(painted_frame);- }- let source_size = source.size();- let frame_size = IntSize {- width: self.size_of_latest_rendered_frame.width.min(source_size.width),- height: self.size_of_latest_rendered_frame.height.min(source_size.height),- };- if frame_size.is_empty() {- return None;}- Some((source, frame_size))+ Some(source)}- fn paint_frame(- &mut self,- env: &PresentingEnvironment<'_>,- surface: &Rc<PaintingSurface>,- frame: &FrameToPaint<'_>,- mut damage_rect: IntRect,- layer_update: &mut layers::LayerUpdate,- ) {- if layer_update.has_plan() {- if self.paint_layered_frame(env, surface, frame, damage_rect, layer_update) {- return;- }- // Unlayered replay paints the media into the base and can change text antialiasing across the frame.- damage_rect = rect_of_size(self.raster_size());- layer_update.repaints_everything = true;- layer_update.new_plan = None;- layer_update.keeps_plan = false;- layer_update.shown_by_window_server = false;- self.layers.drop_layers();- }- // NB: Only a frame shown on screen ages the rasters it did not use, so a screenshot keeps them.- env.raster.start_raster_cache_frame(env.context_id);- self.paint_current_display_list(env, surface, frame, Some(damage_rect), true, true);+ pub fn spare_tile_eviction_timer_fired(&mut self, env: &PresentingEnvironment<'_>) {+ self.layers.spare_tile_eviction_timer_fired(env);}- fn paint_current_display_list(- &mut self,- env: &PresentingEnvironment<'_>,- surface: &Rc<PaintingSurface>,- frame: &FrameToPaint<'_>,- damage_rect: Option<IntRect>,- paints_ui_overlays: bool,- applies_raster_transform: bool,- ) {- let raster = env.raster;- let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);- let allows_lcd_text = damage_rect.is_some() && self.allows_lcd_text(frame.display_list, frame.frame_inputs);- let paint_display_list = |target: &Rc<PaintingSurface>| {- replay_into(- env,- target,- frame,- ReplaySelection {- allows_lcd_text,- ..Default::default()- },- );- paint_overlays(env, target, frame.frame_inputs, paints_ui_overlays);- };-- if let Some(damage_rect) = damage_rect- && !damage_rect.is_empty()- && self.presents_to_client- && (IntSize {- width: damage_rect.width,- height: damage_rect.height,- }) != surface.size()- && surface.uses_gpu()- {- let damage_size = IntSize {- width: damage_rect.width,- height: damage_rect.height,- };- if self- .damage_surface- .as_ref()- .is_none_or(|damage_surface| damage_surface.size() != damage_size)- {- self.damage_surface = raster.create_surface(damage_size, Some(surface), true);- }- if let Some(damage_surface) = &self.damage_surface {- raster.clear(damage_surface, surface_clear_color);- let save_count = raster.save(damage_surface);- raster.translate(damage_surface, -damage_rect.x as f32, -damage_rect.y as f32);- paint_display_list(damage_surface);- raster.restore_to_count(damage_surface, save_count);- raster.draw_surface(- surface,- damage_surface,- rect_of_size(damage_size),- damage_rect,- SurfaceBlend::Source,- );- return;- }- }-- let save_count = raster.save(surface);- if let Some(damage_rect) = damage_rect {- raster.clip_rect(surface, damage_rect);- raster.clear(surface, surface_clear_color);- }- if applies_raster_transform {- self.apply_raster_transform(raster, surface);- }- paint_display_list(surface);- raster.restore_to_count(surface, save_count);+ pub fn tile_raster_scratch_surface_release_timer_fired(&mut self) {+ self.layers.tile_raster_scratch_surface_release_timer_fired();}fn apply_raster_transform(&self, raster: &RasterHost, surface: &Rc<PaintingSurface>) {- raster.translate(surface, self.raster_translation.x, self.raster_translation.y);- raster.scale(surface, self.raster_scale.width, self.raster_scale.height);+ apply_raster_transform(raster, surface, self.raster_scale, self.raster_translation);}fn allows_lcd_text(&self, display_list: &DisplayList, frame_inputs: &FrameInputs) -> bool {@@ -996,20 +945,47 @@ impl ContextPresenting {&& self.device_pixel_ratio.fract() == 0.0&& display_list.storage().summary().destination_blending_records.is_empty()// A blend or backdrop filter that reads the root group needs its original isolation from the canvas fill.- && !tree.effect_nodes.iter().enumerate().any(|(index, node)| {- matches!(&node.data, EffectNodeData::Effects(effects)- if effects.blend_mode != CompositingAndBlendingOperator::Normal || effects.backdrop_filter.is_some())- && tree.effect_backdrop_is_root_group(EffectNodeIndex(index as u32))- })+ && !tree.blend_mode_or_backdrop_filter_reads_root_group()+ }+}++fn raster_transform_of(scale: FloatSize, translation: FloatPoint) -> FloatMatrix4x4 {+ FloatMatrix4x4 {+ elements: [+ [scale.width, 0.0, 0.0, translation.x],+ [0.0, scale.height, 0.0, translation.y],+ [0.0, 0.0, 1.0, 0.0],+ [0.0, 0.0, 0.0, 1.0],+ ],}}-// Replays the frame's display list into the target, through the painter of the context's page.+pub(crate) fn apply_raster_transform(+ raster: &RasterHost,+ surface: &Rc<PaintingSurface>,+ scale: FloatSize,+ translation: FloatPoint,+) {+ raster.translate(surface, translation.x, translation.y);+ raster.scale(surface, scale.width, scale.height);+}+pub(crate) fn replay_into(env: &PresentingEnvironment<'_>,target: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,selection: ReplaySelection<'_>,+) {+ let scroll_offsets = frame.frame_inputs.presented_scroll_state_snapshot.device_offsets();+ replay_with_scroll_offsets(env, target, frame, selection, scroll_offsets);+}++pub(crate) fn replay_with_scroll_offsets(+ env: &PresentingEnvironment<'_>,+ target: &Rc<PaintingSurface>,+ frame: &FrameToPaint<'_>,+ selection: ReplaySelection<'_>,+ scroll_offsets: &[FloatPoint],) {let frame_inputs = frame.frame_inputs;let display_list = frame.display_list;@@ -1025,7 +1001,7 @@ pub(crate) fn replay_into(|painter| {let scrollbars = frame_inputs.scrollbars_shown_for_the_page();let replay_frame = ReplayFrame {- scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ scroll_offsets,scrollbars: &scrollbars,time_ns: frame_inputs.painted_at.nanoseconds(),composited_contexts: env.nested_contexts,@@ -1034,9 +1010,7 @@ pub(crate) fn replay_into(let tree = frame_inputs.visual_context_tree.as_arc();replay_display_list(tree,- storage.bytes(),- storage.command_runs(),- storage.effect_clip_plan(tree),+ storage,display_list.root_group_color(),&replay_frame,selection,@@ -1046,16 +1020,40 @@ pub(crate) fn replay_into();}-pub(crate) fn replaying_only(record_spans: &[RecordSpan], skip_root_isolation_layer: bool) -> ReplaySelection<'_> {- ReplaySelection {- record_spans: Some(record_spans),- skip_root_isolation_layer,- allows_lcd_text: false,- }+/// Composites rasters of the frame into the target through `composite`, which enters the effects the compositor applies+/// to them as a replay of the frame's list enters them.+pub(crate) fn composite_inside_effects_of_frame(+ env: &PresentingEnvironment<'_>,+ target: &Rc<PaintingSurface>,+ frame: &FrameToPaint<'_>,+ composite: impl FnOnce(&mut CompositingInsideEffects<'_, '_, FfiRasterPainter>),+) {+ let frame_inputs = frame.frame_inputs;+ let display_list = frame.display_list;+ env.raster+ .paint(env.context_id, target, PaintingResources::Page, false, |painter| {+ let scrollbars = frame_inputs.scrollbars_shown_for_the_page();+ let replay_frame = ReplayFrame {+ scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ scrollbars: &scrollbars,+ time_ns: frame_inputs.painted_at.nanoseconds(),+ composited_contexts: env.nested_contexts,+ };+ let storage = display_list.storage();+ let tree = frame_inputs.visual_context_tree.as_arc();+ composite_inside_effects(+ tree,+ storage,+ display_list.root_group_color(),+ &replay_frame,+ painter,+ composite,+ );+ });}-// Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the-// browser.+/// Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the+/// browser.pub(crate) fn paint_overlays(env: &PresentingEnvironment<'_>,target: &Rc<PaintingSurface>,diff --git a/Services/Compositor/Rust/src/presenting/tiles.rs b/Services/Compositor/Rust/src/presenting/tiles.rsnew file mode 100644index 00000000000..c9b69db603e--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/tiles.rs@@ -0,0 +1,914 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The tiles the layers of a context hold, the pool of their pixels, and the surface tiles are rastered through. The+//! pixels of a tile are pooled under the tile's content hash, which hashes all they depend on, so a layer finds the+//! tiles another layer or an earlier stack rastered.++use super::layers::LayerCompositingInFrame;+use super::{PresentingEnvironment, inflated, rect_of_size, size_of};+use crate::host::ContextTimer;+use crate::raster_host::{RasterHost, SurfaceBlend};+use crate::surfaces::painting_surface::PaintingSurface;+use libcompositing_rust::display_list::layers::{BarrierCutsOfCell, LayerIdentity, SpaceToFrame};+use libcompositing_rust::display_list::tile_keys::{ContentHash, TileCoverage};+use libcompositing_rust::display_list::tiles::{CellRange, TileCoord, entries_within};+use libcompositing_rust::time::{Duration, MonotonicTime};+use libgfx_rust::{Color, IntRect, IntSize};+use std::collections::{BTreeMap, HashMap, HashSet};+use std::rc::Rc;++const RASTER_SCRATCH_SURFACE_RELEASE_DELAY: Duration = Duration::from_milliseconds(3000);+const TIME_SPARE_TILE_STAYS_POOLED_FOR_CONTENT_THAT_COMES_BACK: Duration = Duration::from_milliseconds(3000);++pub(super) struct TileShownInFrame {+ pub(super) coord: TileCoord,+ pub(super) content_hash: ContentHash,+ pub(super) part_of_cell_needed: IntRect,+ pub(super) cuts: BarrierCutsOfCell,+ pub(super) raster_margin_in_device_pixels: Option<i32>,+ pub(super) coverage: TileCoverage,+}++struct PooledTile {+ pixels: TilePixels,+ held_part_of_cell: IntRect,+ holds_current_pixels: bool,+ /// Of a tile no layer holds, when a layer last held it.+ last_held_at: MonotonicTime,+ held_at_latest_eviction: bool,+}++enum TilePixels {+ Surface {+ surface: Rc<PaintingSurface>,+ every_pixel_is_opaque: bool,+ },+ OneColor(Color),+}++impl PooledTile {+ fn holds_current_pixels_over_ignoring_backend(&self, part_of_cell_needed: IntRect) -> bool {+ self.holds_current_pixels && self.held_part_of_cell.contains_rect(part_of_cell_needed)+ }++ fn surface(&self) -> Option<&Rc<PaintingSurface>> {+ match &self.pixels {+ TilePixels::Surface { surface, .. } => Some(surface),+ TilePixels::OneColor(_) => None,+ }+ }++ fn coverage(&self) -> TileCoverage {+ match self.pixels {+ TilePixels::Surface {+ every_pixel_is_opaque: true,+ ..+ } => TileCoverage::Opaque,+ TilePixels::Surface {+ every_pixel_is_opaque: false,+ ..+ } => TileCoverage::Unknown,+ TilePixels::OneColor(color) => TileCoverage::OneColor(color),+ }+ }+}++type TilePool = HashMap<ContentHash, PooledTile>;++/// The tiles a layer holds, by cell, and a version that changes with them.+#[derive(Default)]+struct HeldTiles {+ by_cell: BTreeMap<TileCoord, ContentHash>,+ content_version: u64,+}++fn pooled_held_tiles<'a>(+ held_tiles: &'a BTreeMap<TileCoord, ContentHash>,+ tile_pool: &'a TilePool,+) -> impl Iterator<Item = (TileCoord, &'a PooledTile)> {+ held_tiles+ .iter()+ .filter_map(|(coord, content_hash)| Some((*coord, tile_pool.get(content_hash)?)))+}++pub(super) enum TileDraw<'a> {+ TileSurface {+ surface: &'a Rc<PaintingSurface>,+ rect_in_layer_space: IntRect,+ },+ FillOfJoinedOneColorTiles {+ rect_in_layer_space: IntRect,+ color: Color,+ },+}++/// What rastering the tiles a layer shows needs to know of the layer besides its tiles.+pub(super) struct LayerToRaster<'a> {+ pub(super) identity: LayerIdentity,+ pub(super) shown: &'a [TileShownInFrame],+ pub(super) rect_shown_in_layer_space: IntRect,+ pub(super) kept_tile_rect: IntRect,+ pub(super) clear_color: Color,+ /// What a raster of several tiles at once stays within, for a layer of the viewport's space: the viewport.+ pub(super) rastered_within: Option<IntRect>,+}++pub(super) struct RasteredLayer {+ /// In the layer's space, where tiles are painted straight from the list into the frame instead.+ pub(super) rects_painted_straight: Vec<IntRect>,+}++/// The tiles the layers of a context hold under the identities of the layers, and the pool of their pixels.+#[derive(Default)]+pub(super) struct LayerTiles {+ held_by_layer: HashMap<LayerIdentity, HeldTiles>,+ pool: TilePool,+ /// Whether a layer took or let go of tiles, or the pixels of pooled tiles changed, since spare tiles were last+ /// evicted.+ changed_since_eviction: bool,+ raster_scratch_surface: Option<Rc<PaintingSurface>>,+}++impl LayerTiles {+ pub(super) fn invalidate_every_tile(&mut self) {+ self.changed_since_eviction = true;+ for tile in self.pool.values_mut() {+ tile.holds_current_pixels = false;+ }+ }++ /// The coverage of the pooled tile of the content hash, where it holds current pixels over the part of its cell.+ pub(super) fn current_coverage(+ &self,+ content_hash: ContentHash,+ part_of_cell_needed: IntRect,+ ) -> Option<TileCoverage> {+ self.pool+ .get(&content_hash)+ .filter(|pooled| pooled.holds_current_pixels_over_ignoring_backend(part_of_cell_needed))+ .map(PooledTile::coverage)+ }++ /// The content version of the tiles the layer holds, or none for a layer that holds no tiles yet.+ pub(super) fn content_version_of(&self, identity: &LayerIdentity) -> Option<u64> {+ Some(self.held_by_layer.get(identity)?.content_version)+ }++ pub(super) fn bounds_held_by(&self, identity: &LayerIdentity) -> IntRect {+ let Some(held) = self.held_by_layer.get(identity) else {+ return IntRect::default();+ };+ pooled_held_tiles(&held.by_cell, &self.pool).fold(IntRect::default(), |bounds, (_, tile)| {+ bounds.united(tile.held_part_of_cell)+ })+ }++ pub(super) fn stale_rect_of_layer(+ &self,+ shown: &[TileShownInFrame],+ compositing: &LayerCompositingInFrame,+ viewport_rect: IntRect,+ composited_filter_read_reach: i32,+ ) -> IntRect {+ let no_held_tiles = BTreeMap::new();+ let held_tiles = self+ .held_by_layer+ .get(&compositing.identity)+ .map_or(&no_held_tiles, |held| &held.by_cell);+ let rect_shown_in_layer_space =+ compositing.rect_shown_in_layer_space(viewport_rect, composited_filter_read_reach);+ let in_frame_as_far_as_filters_around_layer_read = |rect_in_layer_space: IntRect| {+ compositing.rect_in_frame(+ inflated(rect_in_layer_space, composited_filter_read_reach),+ viewport_rect,+ )+ };+ let mut stale_rect = IntRect::default();+ debug_assert!(shown.is_sorted_by_key(|tile| tile.coord));+ for (coord, held_tile) in pooled_held_tiles(held_tiles, &self.pool) {+ if held_tile_lies_in_shown_rect_at_unshown_cell(coord, held_tile, rect_shown_in_layer_space, shown) {+ stale_rect = stale_rect.united(in_frame_as_far_as_filters_around_layer_read(+ held_tile.held_part_of_cell,+ ));+ }+ }+ for tile in shown {+ let held_content_hash = held_tiles.get(&tile.coord);+ let tile_is_unchanged = held_content_hash == Some(&tile.content_hash)+ && self+ .pool+ .get(&tile.content_hash)+ .is_some_and(|pooled| pooled.holds_current_pixels_over_ignoring_backend(tile.part_of_cell_needed));+ if tile_is_unchanged {+ continue;+ }+ stale_rect = stale_rect.united(in_frame_as_far_as_filters_around_layer_read(tile.part_of_cell_needed));+ if let Some(held_tile) = held_content_hash.and_then(|held_content_hash| self.pool.get(held_content_hash)) {+ stale_rect = stale_rect.united(in_frame_as_far_as_filters_around_layer_read(+ held_tile.held_part_of_cell,+ ));+ }+ }+ stale_rect+ }++ /// Per content hash, how many layers hold or show a tile of it in the frame.+ pub(super) fn holder_counts(&self, shown_tiles_by_layer: &[Vec<TileShownInFrame>]) -> HashMap<ContentHash, usize> {+ let mut holder_count_by_content_hash: HashMap<ContentHash, usize> = HashMap::new();+ for content_hash in self.held_by_layer.values().flat_map(|held| held.by_cell.values()) {+ *holder_count_by_content_hash.entry(*content_hash).or_default() += 1;+ }+ for tile in shown_tiles_by_layer.iter().flatten() {+ *holder_count_by_content_hash.entry(tile.content_hash).or_default() += 1;+ }+ holder_count_by_content_hash+ }++ pub(super) fn draws_reaching_into(+ &self,+ compositing: &LayerCompositingInFrame,+ area_in_frame: IntRect,+ ) -> Vec<TileDraw<'_>> {+ let Some(held) = self.held_by_layer.get(&compositing.identity) else {+ return Vec::new();+ };+ let mut draws = Vec::new();+ let mut one_color_fills = Vec::new();+ // A transform can map the area to many more cells than the layer holds tiles at.+ let area_in_layer_space = compositing.space_to_frame.rect_in_space(area_in_frame);+ for (_, content_hash) in entries_within(&held.by_cell, CellRange::touched_by(area_in_layer_space)) {+ let Some(tile) = self.pool.get(content_hash) else {+ continue;+ };+ if compositing+ .rect_in_frame(tile.held_part_of_cell, area_in_frame)+ .is_empty()+ {+ continue;+ }+ let rect_in_layer_space = tile.held_part_of_cell;+ match &tile.pixels {+ TilePixels::Surface { surface, .. } => draws.push(TileDraw::TileSurface {+ surface,+ rect_in_layer_space,+ }),+ TilePixels::OneColor(color) => one_color_fills.push((rect_in_layer_space, *color)),+ }+ }+ draws.extend(joined_rects_of_grid_given_row_by_row(one_color_fills).into_iter().map(+ |(rect_in_layer_space, color)| TileDraw::FillOfJoinedOneColorTiles {+ rect_in_layer_space,+ color,+ },+ ));+ draws+ }++ pub(super) fn has_layer(&self, identity: &LayerIdentity) -> bool {+ self.held_by_layer.contains_key(identity)+ }++ pub(super) fn copy_into(+ &self,+ raster: &RasterHost,+ target: &Rc<PaintingSurface>,+ area_in_frame: IntRect,+ compositing: &LayerCompositingInFrame,+ ) {+ let SpaceToFrame::Offset(composite_offset) = compositing.space_to_frame else {+ unreachable!("the frame holds the layers of spaces it composites through a transform");+ };+ let save_count = raster.save(target);+ if let Some(composite_clip) = compositing.composite_clip {+ raster.clip_rect(target, composite_clip);+ }+ for draw in self.draws_reaching_into(compositing, area_in_frame) {+ match draw {+ TileDraw::TileSurface {+ surface,+ rect_in_layer_space,+ } => {+ raster.draw_surface(+ target,+ surface,+ rect_of_size(size_of(rect_in_layer_space)),+ rect_in_layer_space.translated(composite_offset.x, composite_offset.y),+ SurfaceBlend::Source,+ );+ }+ TileDraw::FillOfJoinedOneColorTiles {+ rect_in_layer_space,+ color,+ } => {+ let save_count = raster.save(target);+ raster.clip_rect(+ target,+ rect_in_layer_space.translated(composite_offset.x, composite_offset.y),+ );+ raster.clear(target, color);+ raster.restore_to_count(target, save_count);+ }+ }+ }+ raster.restore_to_count(target, save_count);+ }++ /// Drops the tiles of the layers that left the stack, whose pixels stay in the pool for a while.+ pub(super) fn keep_only_layers(&mut self, identities: &HashSet<LayerIdentity>) {+ let layer_count_before = self.held_by_layer.len();+ self.held_by_layer.retain(|identity, _| identities.contains(identity));+ self.changed_since_eviction |= self.held_by_layer.len() != layer_count_before;+ }++ /// Evicts spare tiles where the tiles changed since spare tiles were last evicted, as otherwise every tile held then+ /// is still held, and the timer evicts what grows too old.+ pub(super) fn evict_spare_tiles_if_tiles_changed(&mut self, env: &PresentingEnvironment<'_>) {+ if self.changed_since_eviction {+ self.evict_spare_tiles(env);+ }+ }++ pub(super) fn evict_spare_tiles(&mut self, env: &PresentingEnvironment<'_>) {+ if let Some(time_until_a_spare_tile_grows_too_old) = self.evict_spare_tiles_at(env.now) {+ env.host.set_timer(+ env.context_id,+ ContextTimer::SpareTileEviction,+ time_until_a_spare_tile_grows_too_old,+ );+ }+ }++ /// Evicts spare tiles as of `now`, and answers how long the least recently held spare tile left stays pooled.+ fn evict_spare_tiles_at(&mut self, now: MonotonicTime) -> Option<Duration> {+ let held_content_hashes: HashSet<ContentHash> = self+ .held_by_layer+ .values()+ .flat_map(|held| held.by_cell.values().copied())+ .collect();+ let surface_pixel_count_of = |tile: &PooledTile| match tile.pixels {+ TilePixels::Surface { .. } => {+ tile.held_part_of_cell.width.max(0) as u64 * tile.held_part_of_cell.height.max(0) as u64+ }+ TilePixels::OneColor(_) => 0,+ };+ let mut pixel_count_of_held_tiles = 0u64;+ let mut spare_tiles: Vec<(MonotonicTime, ContentHash, u64)> = Vec::new();+ self.pool.retain(|content_hash, tile| {+ if held_content_hashes.contains(content_hash) {+ tile.held_at_latest_eviction = true;+ pixel_count_of_held_tiles += surface_pixel_count_of(tile);+ return true;+ }+ // A frame that lets go of tiles evicts spare tiles as it is committed, so a tile let go since the latest+ // eviction was held until now.+ if std::mem::take(&mut tile.held_at_latest_eviction) {+ tile.last_held_at = now;+ }+ if !tile.holds_current_pixels+ || now - tile.last_held_at >= TIME_SPARE_TILE_STAYS_POOLED_FOR_CONTENT_THAT_COMES_BACK+ {+ return false;+ }+ spare_tiles.push((tile.last_held_at, *content_hash, surface_pixel_count_of(tile)));+ true+ });+ self.changed_since_eviction = false;+ let spare_tiles_least_recently_held_first = {+ spare_tiles.sort_unstable();+ spare_tiles+ };+ let spare_pixel_budget = pixel_count_of_held_tiles;+ let mut pixel_count_of_spare_tiles: u64 = spare_tiles_least_recently_held_first+ .iter()+ .map(|(_, _, pixel_count)| pixel_count)+ .sum();+ let mut evicted_count = 0;+ for (_, content_hash, pixel_count) in &spare_tiles_least_recently_held_first {+ if pixel_count_of_spare_tiles <= spare_pixel_budget {+ break;+ }+ self.pool.remove(content_hash);+ pixel_count_of_spare_tiles -= pixel_count;+ evicted_count += 1;+ }+ spare_tiles_least_recently_held_first+ .get(evicted_count)+ .map(|(least_recently_held_at, _, _)| {+ TIME_SPARE_TILE_STAYS_POOLED_FOR_CONTENT_THAT_COMES_BACK - (now - *least_recently_held_at)+ })+ }++ pub(super) fn release_raster_scratch_surface(&mut self) {+ self.raster_scratch_surface = None;+ }++ /// Keeps the tiles the layer shows and those it may show again soon, and rasters the shown tiles that lack current+ /// pixels: `replay_tiles` replays the records of the tiles it is given into a target.+ pub(super) fn raster_layer(+ &mut self,+ env: &PresentingEnvironment<'_>,+ like: &Rc<PaintingSurface>,+ layer: LayerToRaster<'_>,+ holder_count_by_content_hash: &HashMap<ContentHash, usize>,+ replay_tiles: impl Fn(&Rc<PaintingSurface>, &[&TileShownInFrame]),+ ) -> RasteredLayer {+ let LayerToRaster {+ identity,+ shown,+ rect_shown_in_layer_space,+ kept_tile_rect,+ clear_color,+ rastered_within,+ } = layer;+ let raster = env.raster;+ let mut rects_painted_straight = Vec::new();+ let held = self.held_by_layer.entry(identity).or_default();+ let tile_pool = &mut self.pool;++ let held_tile_count_before = held.by_cell.len();+ debug_assert!(shown.is_sorted_by_key(|tile| tile.coord));+ held.by_cell.retain(|coord, content_hash| {+ !coord.cell_rect().intersected(kept_tile_rect).is_empty()+ && tile_pool.get(content_hash).is_some_and(|held_tile| {+ !held_tile_lies_in_shown_rect_at_unshown_cell(*coord, held_tile, rect_shown_in_layer_space, shown)+ })+ });+ let mut held_tiles_changed = held.by_cell.len() != held_tile_count_before;++ let mut tiles_to_raster: Vec<TileToRaster> = Vec::new();+ for (shown_tile_index, tile) in shown.iter().enumerate() {+ let held_content_hash = held.by_cell.get(&tile.coord).copied();+ if held_content_hash != Some(tile.content_hash) {+ held.by_cell.insert(tile.coord, tile.content_hash);+ held_tiles_changed = true;+ }+ let pooled_tile_holds_needed_part_drawable_into_frame = |pooled: &PooledTile| {+ pooled.held_part_of_cell.contains_rect(tile.part_of_cell_needed)+ && pooled.surface().is_none_or(|surface| surface.shares_backend_with(like))+ };+ if tile_pool.get(&tile.content_hash).is_some_and(|pooled| {+ pooled_tile_holds_needed_part_drawable_into_frame(pooled) && pooled.holds_current_pixels+ }) {+ continue;+ }+ if let TileCoverage::OneColor(color) = tile.coverage {+ tile_pool.insert(+ tile.content_hash,+ PooledTile {+ pixels: TilePixels::OneColor(color),+ held_part_of_cell: tile.part_of_cell_needed,+ holds_current_pixels: true,+ last_held_at: env.now,+ held_at_latest_eviction: false,+ },+ );+ held_tiles_changed = true;+ continue;+ }+ let every_pixel_is_opaque = tile.coverage == TileCoverage::Opaque;+ match tile_pool.get_mut(&tile.content_hash) {+ Some(pooled)+ if pooled.surface().is_some() && pooled_tile_holds_needed_part_drawable_into_frame(pooled) =>+ {+ if let TilePixels::Surface {+ every_pixel_is_opaque: pooled_every_pixel_is_opaque,+ ..+ } = &mut pooled.pixels+ {+ *pooled_every_pixel_is_opaque = every_pixel_is_opaque;+ }+ }+ _ => {+ // The surface of the tile the layer held at the cell takes the new content hash only where it holds+ // the very part of the cell a new surface would: the GPU antialiases some content, such as rounded+ // clips, by where in its surface the content lands.+ let surface_held_by_this_layer_alone = held_content_hash+ .filter(|held_content_hash| {+ *held_content_hash != tile.content_hash+ && holder_count_by_content_hash+ .get(held_content_hash)+ .copied()+ .unwrap_or(0)+ <= 1+ && tile_pool.get(held_content_hash).is_some_and(|held_tile| {+ held_tile.held_part_of_cell == tile.part_of_cell_needed+ && held_tile+ .surface()+ .is_some_and(|surface| surface.shares_backend_with(like))+ })+ })+ .and_then(|held_content_hash| tile_pool.remove(&held_content_hash))+ .and_then(|held_tile| match held_tile.pixels {+ TilePixels::Surface { surface, .. } => Some(surface),+ TilePixels::OneColor(_) => None,+ });+ let surface = surface_held_by_this_layer_alone+ .or_else(|| create_surface_on_backend_of(raster, size_of(tile.part_of_cell_needed), like));+ let Some(surface) = surface else {+ held.by_cell.remove(&tile.coord);+ held_tiles_changed = true;+ rects_painted_straight.push(tile.part_of_cell_needed);+ continue;+ };+ tile_pool.insert(+ tile.content_hash,+ PooledTile {+ pixels: TilePixels::Surface {+ surface,+ every_pixel_is_opaque,+ },+ held_part_of_cell: tile.part_of_cell_needed,+ holds_current_pixels: false,+ last_held_at: env.now,+ held_at_latest_eviction: false,+ },+ );+ }+ }+ tiles_to_raster.push(TileToRaster {+ shown_tile_index,+ was_rastered: false,+ });+ }+ if held_tiles_changed || !tiles_to_raster.is_empty() {+ held.content_version = held.content_version.wrapping_add(1);+ self.changed_since_eviction = true;+ }+ if tiles_to_raster.is_empty() {+ return RasteredLayer { rects_painted_straight };+ }++ let pooled_surface_and_held_part = |tile_pool: &TilePool, tile: &TileShownInFrame| {+ let pooled = tile_pool+ .get(&tile.content_hash)+ .expect("a tile to raster is in the pool");+ let surface = pooled.surface().expect("a tile to raster has a surface");+ (surface.clone(), pooled.held_part_of_cell)+ };+ let bounds_held_by = |tile_pool: &TilePool, tiles: &[&TileShownInFrame]| {+ tiles+ .iter()+ .filter_map(|tile| tile_pool.get(&tile.content_hash))+ .fold(IntRect::default(), |bounds, pooled| {+ bounds.united(pooled.held_part_of_cell)+ })+ };++ for batch in batch_tiles_to_raster_by_cuts(shown, &tiles_to_raster) {+ let batch_tiles: Vec<&TileShownInFrame> = batch+ .iter()+ .map(|&position_in_tiles_to_raster| {+ &shown[tiles_to_raster[position_in_tiles_to_raster].shown_tile_index]+ })+ .collect();+ let largest_raster_margin_if_every_one_is_known = batch_tiles.iter().try_fold(0i32, |largest, tile| {+ Some(largest.max(tile.raster_margin_in_device_pixels?))+ });+ let was_rastered = if largest_raster_margin_if_every_one_is_known == Some(0) && batch_tiles.len() == 1 {+ let (surface, held_part_of_cell) = pooled_surface_and_held_part(&self.pool, batch_tiles[0]);+ let save_count = raster.save(&surface);+ raster.translate(&surface, -held_part_of_cell.x as f32, -held_part_of_cell.y as f32);+ raster.clip_rect(&surface, held_part_of_cell);+ raster.clear(&surface, clear_color);+ replay_tiles(&surface, &batch_tiles);+ raster.restore_to_count(&surface, save_count);+ true+ } else {+ // A backdrop filter reading by an unknown reach needs every shown tile cut alike replayed.+ let tiles_replayed: Vec<&TileShownInFrame> = match largest_raster_margin_if_every_one_is_known {+ Some(_) => batch_tiles.clone(),+ None => shown.iter().filter(|tile| tile.cuts == batch_tiles[0].cuts).collect(),+ };+ let raster_margin = largest_raster_margin_if_every_one_is_known.unwrap_or(0);+ let mut scratch_rect_in_space = bounds_held_by(&self.pool, &tiles_replayed).inflated_edges(+ raster_margin,+ raster_margin,+ raster_margin,+ raster_margin,+ );+ if let Some(rastered_within) = rastered_within {+ scratch_rect_in_space = scratch_rect_in_space.intersected(rastered_within);+ }+ scratch_rect_in_space = scratch_rect_in_space.united(bounds_held_by(&self.pool, &batch_tiles));+ let target_tiles: Vec<(Rc<PaintingSurface>, IntRect)> = batch_tiles+ .iter()+ .map(|tile| pooled_surface_and_held_part(&self.pool, tile))+ .collect();+ let scratch = raster_scratch_surface_of_size(+ &mut self.raster_scratch_surface,+ env,+ size_of(scratch_rect_in_space),+ like,+ );+ if let Some(scratch) = &scratch {+ replay_into_scratch_and_copy_into_tiles(+ raster,+ scratch,+ &target_tiles,+ scratch_rect_in_space,+ clear_color,+ &|target| {+ replay_tiles(target, &tiles_replayed);+ },+ );+ }+ scratch.is_some()+ };+ for position_in_tiles_to_raster in batch {+ tiles_to_raster[position_in_tiles_to_raster].was_rastered = was_rastered;+ }+ }++ for tile_to_raster in &tiles_to_raster {+ let tile = &shown[tile_to_raster.shown_tile_index];+ let Some(pooled) = self.pool.get_mut(&tile.content_hash) else {+ continue;+ };+ pooled.holds_current_pixels = tile_to_raster.was_rastered;+ if !tile_to_raster.was_rastered {+ rects_painted_straight.push(pooled.held_part_of_cell);+ }+ }+ RasteredLayer { rects_painted_straight }+ }+}++fn raster_scratch_surface_of_size(+ raster_scratch_surface: &mut Option<Rc<PaintingSurface>>,+ env: &PresentingEnvironment<'_>,+ size: IntSize,+ like: &Rc<PaintingSurface>,+) -> Option<Rc<PaintingSurface>> {+ let cached_surface_fits = raster_scratch_surface+ .as_ref()+ .is_some_and(|surface| surface.size() == size && surface.shares_backend_with(like));+ if !cached_surface_fits {+ *raster_scratch_surface = None;+ *raster_scratch_surface = Some(create_surface_on_backend_of(env.raster, size, like)?);+ }+ env.host.set_timer(+ env.context_id,+ ContextTimer::TileRasterScratchSurfaceRelease,+ RASTER_SCRATCH_SURFACE_RELEASE_DELAY,+ );+ raster_scratch_surface.clone()+}++fn replay_into_scratch_and_copy_into_tiles(+ raster: &RasterHost,+ scratch: &Rc<PaintingSurface>,+ target_tiles: &[(Rc<PaintingSurface>, IntRect)],+ scratch_rect_in_space: IntRect,+ clear_color: Color,+ replay: &dyn Fn(&Rc<PaintingSurface>),+) {+ let save_count = raster.save(scratch);+ raster.clear(scratch, clear_color);+ raster.translate(+ scratch,+ -scratch_rect_in_space.x as f32,+ -scratch_rect_in_space.y as f32,+ );+ replay(scratch);+ raster.restore_to_count(scratch, save_count);+ for (tile_surface, tile_rect_in_space) in target_tiles {+ raster.draw_surface(+ tile_surface,+ scratch,+ tile_rect_in_space.translated(-scratch_rect_in_space.x, -scratch_rect_in_space.y),+ rect_of_size(size_of(*tile_rect_in_space)),+ SurfaceBlend::Source,+ );+ }+}++// A surface that fell back to the CPU on a GPU backend would be allocated again with every frame.+fn create_surface_on_backend_of(+ raster: &RasterHost,+ size: IntSize,+ like: &Rc<PaintingSurface>,+) -> Option<Rc<PaintingSurface>> {+ let inherits_lcd_text = true;+ raster+ .create_surface(size, Some(like), inherits_lcd_text)+ .filter(|surface| surface.shares_backend_with(like))+}++pub(super) fn joined_rects_of_grid_given_row_by_row<T: Copy + PartialEq>(+ rects: impl IntoIterator<Item = (IntRect, T)>,+) -> Vec<(IntRect, T)> {+ let mut rects_joined_within_rows: Vec<(IntRect, T)> = Vec::new();+ for (rect, value) in rects {+ if rect.is_empty() {+ continue;+ }+ if let Some((left, left_value)) = rects_joined_within_rows.last_mut()+ && *left_value == value+ && left.y == rect.y+ && left.height == rect.height+ && left.right() == rect.x+ {+ left.width += rect.width;+ continue;+ }+ rects_joined_within_rows.push((rect, value));+ }+ let mut joined: Vec<(IntRect, T)> = Vec::new();+ let mut index_of_joined_rect_by_left_width_and_bottom: HashMap<(i32, i32, i32), usize> = HashMap::new();+ for (row_rect, value) in rects_joined_within_rows {+ let left_width_and_bottom_of_rect_above = (row_rect.x, row_rect.width, row_rect.y);+ match index_of_joined_rect_by_left_width_and_bottom.get(&left_width_and_bottom_of_rect_above) {+ Some(&index) if joined[index].1 == value => {+ index_of_joined_rect_by_left_width_and_bottom.remove(&left_width_and_bottom_of_rect_above);+ joined[index].0.height += row_rect.height;+ index_of_joined_rect_by_left_width_and_bottom+ .insert((row_rect.x, row_rect.width, joined[index].0.bottom()), index);+ }+ _ => {+ index_of_joined_rect_by_left_width_and_bottom+ .insert((row_rect.x, row_rect.width, row_rect.bottom()), joined.len());+ joined.push((row_rect, value));+ }+ }+ }+ joined+}++fn held_tile_lies_in_shown_rect_at_unshown_cell(+ coord: TileCoord,+ held_tile: &PooledTile,+ rect_shown_in_layer_space: IntRect,+ shown_sorted_by_cell: &[TileShownInFrame],+) -> bool {+ !held_tile+ .held_part_of_cell+ .intersected(rect_shown_in_layer_space)+ .is_empty()+ && shown_sorted_by_cell+ .binary_search_by(|tile| tile.coord.cmp(&coord))+ .is_err()+}++struct TileToRaster {+ shown_tile_index: usize,+ was_rastered: bool,+}++fn batch_tiles_to_raster_by_cuts(shown: &[TileShownInFrame], tiles_to_raster: &[TileToRaster]) -> Vec<Vec<usize>> {+ let mut batches: Vec<(&BarrierCutsOfCell, Vec<usize>)> = Vec::new();+ for (position_in_tiles_to_raster, tile_to_raster) in tiles_to_raster.iter().enumerate() {+ let cuts = &shown[tile_to_raster.shown_tile_index].cuts;+ match batches.iter_mut().find(|(batch_cuts, _)| *batch_cuts == cuts) {+ Some((_, batch)) => batch.push(position_in_tiles_to_raster),+ None => batches.push((cuts, vec![position_in_tiles_to_raster])),+ }+ }+ batches.into_iter().map(|(_, batch)| batch).collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use libcompositing_rust::display_list::layers::{LayerIndex, PlacementNodeIdentity};+ use libgfx_rust::AffineTransform;++ const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);++ const LAYER: LayerIdentity = LayerIdentity::Painted {+ node: PlacementNodeIdentity(1),+ band_ordinal_in_node: 0,+ above_barrier: None,+ };++ fn layer_composited_through(transform: AffineTransform) -> LayerCompositingInFrame {+ LayerCompositingInFrame {+ layer_index: LayerIndex(1),+ identity: LAYER,+ space_to_frame: SpaceToFrame::Transform(transform),+ composite_clip: None,+ rounded_composite_clips: Vec::new(),+ shown_by_window_server: false,+ }+ }++ fn one_color_tiles_at(coords: &[TileCoord]) -> LayerTiles {+ let by_cell: BTreeMap<TileCoord, ContentHash> = coords+ .iter()+ .enumerate()+ .map(|(index, coord)| (*coord, index as ContentHash + 1))+ .collect();+ let pool: TilePool = by_cell+ .iter()+ .map(|(coord, content_hash)| {+ (+ *content_hash,+ PooledTile {+ // A color of its own, so that no two tiles join into one fill.+ pixels: TilePixels::OneColor(Color::from_rgb(0, 128, *content_hash as u8)),+ held_part_of_cell: coord.cell_rect(),+ holds_current_pixels: true,+ last_held_at: MonotonicTime::default(),+ held_at_latest_eviction: false,+ },+ )+ })+ .collect();+ LayerTiles {+ held_by_layer: HashMap::from([(+ LAYER,+ HeldTiles {+ by_cell,+ content_version: 0,+ },+ )]),+ pool,+ ..LayerTiles::default()+ }+ }++ fn rects_of_draws(draws: &[TileDraw<'_>]) -> Vec<IntRect> {+ draws+ .iter()+ .map(|draw| match draw {+ TileDraw::TileSurface {+ rect_in_layer_space, ..+ }+ | TileDraw::FillOfJoinedOneColorTiles {+ rect_in_layer_space, ..+ } => *rect_in_layer_space,+ })+ .collect()+ }++ // A layer of another process can show many tiles of one color, with colors that keep any two from joining.+ #[test]+ fn rects_of_a_grid_given_row_by_row_join_into_columns_without_a_search_of_every_joined_rect() {+ let cell = |column: i32, row: i32| IntRect::new(column * 16, row * 16, 16, 16);+ let grid = |columns: i32, rows: i32, value_of_cell: fn(i32, i32) -> i32| {+ (0..rows)+ .flat_map(move |row| (0..columns).map(move |column| (cell(column, row), value_of_cell(column, row))))+ };+ assert_eq!(+ joined_rects_of_grid_given_row_by_row(grid(300, 300, |column, _| column / 100)),+ [+ (IntRect::new(0, 0, 1600, 4800), 0),+ (IntRect::new(1600, 0, 1600, 4800), 1),+ (IntRect::new(3200, 0, 1600, 4800), 2),+ ]+ );+ let checkerboard = joined_rects_of_grid_given_row_by_row(grid(300, 300, |column, row| (column + row) % 2));+ assert_eq!(checkerboard.len(), 300 * 300);+ assert_eq!(checkerboard[300 * 300 - 1], (cell(299, 299), 0));+ }++ // A box that the compositor scales up from nothing shows at a tiny part of its raster scale at first.+ #[test]+ fn a_layer_shown_at_a_tiny_scale_draws_its_held_tiles_without_visiting_every_cell_the_viewport_maps_to() {+ let tiny_scale = 1.0e-5;+ let layer = layer_composited_through(AffineTransform::new(tiny_scale, 0.0, 0.0, tiny_scale, 400.0, 300.0));+ let shown_rect = layer.rect_shown_in_layer_space(VIEWPORT, 0);+ assert!(CellRange::touched_by(shown_rect).cell_count() > 1_000_000_000);+ let held_cells = [TileCoord::new(-1, -1), TileCoord::new(0, 0), TileCoord::new(3, 0)];+ let tiles = one_color_tiles_at(&held_cells);+ let draws = tiles.draws_reaching_into(&layer, VIEWPORT);+ assert_eq!(rects_of_draws(&draws), held_cells.map(TileCoord::cell_rect));+ }++ // A frame lets go of a tile that the screen showed through a spell of no frames.+ #[test]+ fn a_tile_let_go_after_a_spell_of_no_frames_stays_pooled_for_a_while() {+ let mut tiles = one_color_tiles_at(&[TileCoord::new(0, 0)]);+ let at_start = MonotonicTime::from_nanoseconds(1_000_000_000);+ assert_eq!(tiles.evict_spare_tiles_at(at_start), None);+ let after_spell_of_no_frames = at_start + Duration::from_milliseconds(10_000);+ tiles.keep_only_layers(&HashSet::new());+ assert_eq!(+ tiles.evict_spare_tiles_at(after_spell_of_no_frames),+ Some(TIME_SPARE_TILE_STAYS_POOLED_FOR_CONTENT_THAT_COMES_BACK)+ );+ assert_eq!(tiles.pool.len(), 1);+ }++ #[test]+ fn a_layer_whose_transform_is_not_finite_or_has_no_inverse_shows_nothing() {+ let tiles = one_color_tiles_at(&[TileCoord::new(0, 0)]);+ for transform in [+ AffineTransform::new(f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0),+ AffineTransform::new(1.0, 0.0, 0.0, 1.0, f32::INFINITY, 0.0),+ AffineTransform::new(0.0, 0.0, 0.0, 1.0, 0.0, 0.0),+ AffineTransform::new(1.0e-30, 0.0, 0.0, 1.0e-30, 0.0, 0.0),+ ] {+ let layer = layer_composited_through(transform);+ assert_eq!(layer.rect_shown_in_layer_space(VIEWPORT, 0), IntRect::default());+ assert_eq!(+ layer.rect_in_frame(TileCoord::new(0, 0).cell_rect(), VIEWPORT),+ IntRect::default()+ );+ assert!(tiles.draws_reaching_into(&layer, VIEWPORT).is_empty());+ }+ }+}diff --git a/Services/Compositor/Rust/src/presenting/window_server.rs b/Services/Compositor/Rust/src/presenting/window_server.rsnew file mode 100644index 00000000000..5f51c4b6375--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/window_server.rs@@ -0,0 +1,371 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the window server shows above a frame by itself: the media layers it can show, and the surfaces it shows+//! painted layers and the overlays of the compositor from.++use super::layers::{LayerCompositingInFrame, PaintedLayers};+use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, paint_overlays, rect_of_size, size_of};+use crate::raster_host::{FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, SublayerContentKind};+use crate::surfaces::painting_surface::PaintingSurface;+use crate::surfaces::presentable_surface::{PresentableSurface, PresentableSurfacePool};+use libcompositing_rust::display_list::layers::{+ LayerContent, LayerIdentity, LayerIndex, StackLayer, WindowServerPlacementsOfMedia,+};+use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;+use libcompositing_rust::display_list::window_server_placement::{+ WhyWindowServerCannotShowMedia, WindowServerPlacement,+};+use libgfx_rust::{Color, IntRect, ScalingMode};+use std::collections::{HashMap, HashSet};+use std::rc::Rc;++const CANVAS_SUBLAYER_IDENTITY_TAG: u64 = 1 << 60;+const VIDEO_SUBLAYER_IDENTITY_TAG: u64 = 2 << 60;+const PAINTED_LAYER_SUBLAYER_IDENTITY_TAG: u64 = 3 << 60;+const COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY: u64 = 4 << 60;+// The checks of a plan keep the ordinal of a media layer below the most media layers a plan makes, so it stays clear of+// the tag.+const MEDIA_ORDINAL_SHIFT_PAST_CANVAS_AND_VIDEO_IDS: u32 = 44;++struct PaintedLayerPresentation {+ sublayer_ordinal: u32,+ surface_pool: PresentableSurfacePool,+ latest_surface: Option<Rc<PresentableSurface>>,+ rect_in_frame: IntRect,+ copied_content_version: u64,+ // Under a composite clip, the same rect of the frame shows other tiles once the layer's space scrolls.+ copied_with_compositing: Option<LayerCompositingInFrame>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum WhyMediaIsReplayed {+ ContextIsNotShownInARemoteLayer,+ NoGpu,+ ContextIsPresentedFromCpuMemory,+ Placement(WhyWindowServerCannotShowMedia),+ NoPlacement(LiveMedia),+ CanvasHasNoPresentableSurface,+ VideoHasNoFrame,+ HighDynamicRangeIsNotShownNow,+ WindowServerCannotShowThePlacement,+}++#[derive(Default)]+pub(super) struct WindowServerLayers {+ presentation_by_layer: HashMap<LayerIdentity, PaintedLayerPresentation>,+ compositor_overlays_surface_pool: PresentableSurfacePool,+ latest_compositor_overlays_surface_and_rect: Option<(Rc<PresentableSurface>, IntRect)>,+ next_sublayer_ordinal: u32,+}++impl WindowServerLayers {+ pub(super) fn keep_only_layers(&mut self, identities_in_stack: &HashSet<LayerIdentity>) {+ self.presentation_by_layer+ .retain(|identity, _| identities_in_stack.contains(identity));+ }+}++fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacement {+ let rounded_clip = placement.rounded_clip;+ FfiSublayerPlacement {+ content_rect: placement.content_rect,+ content_to_frame: placement.content_to_viewport.values,+ clip_rect: placement.clip_rect,+ has_rounded_clip: rounded_clip.is_some(),+ rounded_clip_rect: rounded_clip.map(|clip| clip.rect).unwrap_or_default(),+ rounded_clip_radius: rounded_clip.map_or(0.0, |clip| clip.radius),+ rounds_top_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_left),+ rounds_top_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_right),+ rounds_bottom_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_right),+ rounds_bottom_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_left),+ scaling_mode: placement.scaling_mode,+ }+}++fn unclipped_untransformed_surface_sublayer(+ identity: u64,+ surface: &Rc<PresentableSurface>,+ rect_in_frame: IntRect,+) -> FfiSublayer {+ FfiSublayer {+ identity,+ content_kind: SublayerContentKind::PresentableSurface,+ media_id: 0,+ presentable_surface: surface.as_ffi(),+ placement: FfiSublayerPlacement {+ content_rect: rect_in_frame,+ content_to_frame: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],+ clip_rect: rect_in_frame.to_float(),+ scaling_mode: ScalingMode::NearestNeighbor,+ ..Default::default()+ },+ }+}++impl ContextPresenting {+ pub(super) fn why_window_server_shows_no_media_of_this_context(+ &self,+ env: &PresentingEnvironment<'_>,+ ) -> Option<WhyMediaIsReplayed> {+ if !self.shown_in_remote_layer {+ return Some(WhyMediaIsReplayed::ContextIsNotShownInARemoteLayer);+ }+ if !env.has_gpu {+ return Some(WhyMediaIsReplayed::NoGpu);+ }+ if self.presents_from_cpu_memory {+ return Some(WhyMediaIsReplayed::ContextIsPresentedFromCpuMemory);+ }+ None+ }++ pub(super) fn why_window_server_does_not_show_media_layer(+ &self,+ env: &PresentingEnvironment<'_>,+ window_server_placements_of_media: &WindowServerPlacementsOfMedia,+ layer_index: LayerIndex,+ layer: &StackLayer,+ live_content: &LiveContent,+ ) -> Option<WhyMediaIsReplayed> {+ let LayerIdentity::Media { content, .. } = &layer.identity else {+ return None;+ };+ let placement = match window_server_placements_of_media.of_layer(layer_index) {+ Some(Ok(placement)) => placement,+ Some(Err(why)) => return Some(WhyMediaIsReplayed::Placement(*why)),+ None => return Some(WhyMediaIsReplayed::NoPlacement(*content)),+ };+ let (kind, id) = match content {+ LiveMedia::Canvas(id) => {+ let has_presentable_surface = live_content+ .canvases+ .get(&id.0)+ .is_some_and(|canvas| canvas.has_presentable_surface);+ if !has_presentable_surface {+ return Some(WhyMediaIsReplayed::CanvasHasNoPresentableSurface);+ }+ (MediaKind::Canvas, id.0)+ }+ LiveMedia::VideoFrame(id) => {+ let Some(sink) = live_content.video_sinks.get(&id.0).filter(|sink| sink.has_frame) else {+ return Some(WhyMediaIsReplayed::VideoHasNoFrame);+ };+ if !env.window_server_may_show_high_dynamic_range && sink.frame_holds_high_dynamic_range {+ return Some(WhyMediaIsReplayed::HighDynamicRangeIsNotShownNow);+ }+ (MediaKind::Video, id.0)+ }+ LiveMedia::ImageFrame(_) | LiveMedia::CompositedContext(_) => {+ return Some(WhyMediaIsReplayed::NoPlacement(*content));+ }+ };+ let Some(remote_layer) = &env.remote_layer else {+ return Some(WhyMediaIsReplayed::ContextIsNotShownInARemoteLayer);+ };+ if !env.raster.remote_layer_can_show(+ &remote_layer.layer,+ env.context_id,+ kind,+ id,+ &sublayer_placement_of(placement),+ self.device_pixel_ratio,+ ) {+ return Some(WhyMediaIsReplayed::WindowServerCannotShowThePlacement);+ }+ None+ }++ pub(super) fn present_painted_layers_to_window_server(+ &mut self,+ env: &PresentingEnvironment<'_>,+ painted_layers: &PaintedLayers,+ like: &Rc<PaintingSurface>,+ ) -> bool {+ let raster = env.raster;+ let viewport_rect = rect_of_size(self.viewport_size);+ let layers = &mut self.layers;+ let (stack, compositing_of_layers) = (&painted_layers.stack, &painted_layers.compositing_of_layers);+ for compositing in compositing_of_layers+ .iter()+ .skip(1)+ .filter(|compositing| compositing.shown_by_window_server)+ .filter(|compositing| matches!(stack.layers[compositing.layer_index.0].content, LayerContent::Painted))+ {+ let Some(content_version_of_held_tiles) = layers.tiles.content_version_of(&compositing.identity) else {+ continue;+ };+ let held_rect_in_frame =+ compositing.rect_in_frame(layers.tiles.bounds_held_by(&compositing.identity), viewport_rect);+ if held_rect_in_frame.is_empty() {+ if let Some(presentation) = layers+ .window_server+ .presentation_by_layer+ .get_mut(&compositing.identity)+ {+ presentation.latest_surface = None;+ }+ continue;+ }+ let presentation = layers+ .window_server+ .presentation_by_layer+ .entry(compositing.identity)+ .or_insert_with(|| {+ let sublayer_ordinal = layers.window_server.next_sublayer_ordinal;+ layers.window_server.next_sublayer_ordinal += 1;+ PaintedLayerPresentation {+ sublayer_ordinal,+ surface_pool: PresentableSurfacePool::default(),+ latest_surface: None,+ rect_in_frame: IntRect::default(),+ copied_content_version: 0,+ copied_with_compositing: None,+ }+ });+ if presentation.latest_surface.is_some()+ && presentation.rect_in_frame == held_rect_in_frame+ && presentation.copied_content_version == content_version_of_held_tiles+ && presentation.copied_with_compositing.as_ref() == Some(compositing)+ {+ continue;+ }+ let held_size = size_of(held_rect_in_frame);+ let Some(presentable) =+ presentation+ .surface_pool+ .surface_for_next_content(held_size, like.gpu_backend_context(), || {+ raster.create_presentable_surface(held_size, like)+ })+ else {+ return false;+ };+ let target = presentable.painting_surface();+ raster.clear(target, Color::TRANSPARENT);+ let save_count = raster.save(target);+ raster.translate(target, -held_rect_in_frame.x as f32, -held_rect_in_frame.y as f32);+ layers.tiles.copy_into(raster, target, held_rect_in_frame, compositing);+ raster.restore_to_count(target, save_count);+ presentation.latest_surface = Some(presentable);+ presentation.rect_in_frame = held_rect_in_frame;+ presentation.copied_content_version = content_version_of_held_tiles;+ presentation.copied_with_compositing = Some(compositing.clone());+ }+ true+ }++ pub(super) fn present_compositor_overlays_to_window_server(+ &mut self,+ env: &PresentingEnvironment<'_>,+ frame: &FrameToPaint<'_>,+ like: &Rc<PaintingSurface>,+ ) -> bool {+ let raster = env.raster;+ let overlays_rect = frame.frame_inputs.overlays.bounds;+ if overlays_rect.is_empty() {+ self.layers.window_server.latest_compositor_overlays_surface_and_rect = None;+ return true;+ }+ let overlays_size = size_of(overlays_rect);+ let Some(presentable) = self+ .layers+ .window_server+ .compositor_overlays_surface_pool+ .surface_for_next_content(overlays_size, like.gpu_backend_context(), || {+ raster.create_presentable_surface(overlays_size, like)+ })+ else {+ return false;+ };+ let target = presentable.painting_surface();+ raster.clear(target, Color::TRANSPARENT);+ let save_count = raster.save(target);+ raster.translate(target, -overlays_rect.x as f32, -overlays_rect.y as f32);+ paint_overlays(env, target, frame.frame_inputs, true);+ raster.restore_to_count(target, save_count);+ self.layers.window_server.latest_compositor_overlays_surface_and_rect = Some((presentable, overlays_rect));+ true+ }++ pub(super) fn sublayers_shown_by_window_server(&self, live_content: &LiveContent) -> Vec<FfiSublayer> {+ let layers = &self.layers.window_server;+ let mut sublayers = Vec::new();+ let Some(painted) = self+ .painted_frame+ .as_ref()+ .map(|painted_frame| &painted_frame.layers)+ .filter(|painted| painted.shown_by_window_server())+ else {+ return sublayers;+ };+ for compositing in painted+ .compositing_of_layers+ .iter()+ .skip(1)+ .filter(|compositing| compositing.shown_by_window_server)+ {+ let layer_index = compositing.layer_index;+ let layer = compositing.layer_in(&painted.stack);+ if let LayerIdentity::Media { content, ordinal } = layer.identity {+ let Some(Ok(placement)) = painted.window_server_placements_of_media.of_layer(layer_index) else {+ continue;+ };+ let (kind, id, sublayer_identity_of_media, has_content) = match content {+ LiveMedia::Canvas(id) => (+ SublayerContentKind::Canvas,+ id.0,+ CANVAS_SUBLAYER_IDENTITY_TAG | id.0,+ live_content+ .canvases+ .get(&id.0)+ .is_some_and(|canvas| canvas.has_presentable_surface),+ ),+ LiveMedia::VideoFrame(id) => (+ SublayerContentKind::Video,+ id.0,+ VIDEO_SUBLAYER_IDENTITY_TAG | id.0,+ live_content+ .video_sinks+ .get(&id.0)+ .is_some_and(|sink| sink.has_frame && sink.frame_has_surface),+ ),+ LiveMedia::ImageFrame(_) | LiveMedia::CompositedContext(_) => continue,+ };+ if !has_content {+ continue;+ }+ sublayers.push(FfiSublayer {+ identity: sublayer_identity_of_media+ | (u64::from(ordinal) << MEDIA_ORDINAL_SHIFT_PAST_CANVAS_AND_VIDEO_IDS),+ content_kind: kind,+ media_id: id,+ presentable_surface: std::ptr::null(),+ placement: sublayer_placement_of(placement),+ });+ continue;+ }+ let Some(presentation) = layers.presentation_by_layer.get(&compositing.identity) else {+ continue;+ };+ let Some(surface) = &presentation.latest_surface else {+ continue;+ };+ sublayers.push(unclipped_untransformed_surface_sublayer(+ PAINTED_LAYER_SUBLAYER_IDENTITY_TAG | u64::from(presentation.sublayer_ordinal),+ surface,+ presentation.rect_in_frame,+ ));+ }+ if let Some((surface, rect_in_frame)) = &layers.latest_compositor_overlays_surface_and_rect {+ sublayers.push(unclipped_untransformed_surface_sublayer(+ COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY,+ surface,+ *rect_in_frame,+ ));+ }+ sublayers+ }+}diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex f550566482a..9547cc15114 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -15,7 +15,7 @@ use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::display_list::storage::{- PackedChunkSize, ReceivedChunk, receive_packed_chunks_from_shared_memory,+ ListChunk, PackedChunkSize, receive_packed_chunks_from_shared_memory,};use libcompositing_rust::host::FfiRasterPainter;use libcompositing_rust::ipc_types::{@@ -58,7 +58,7 @@ pub enum FrameHandOff {pub struct FfiCanvasContent {pub id: u64,pub content_generation: u64,- // Whether the window server can show the canvas as it is.+ /// Whether the window server can show the canvas as it is.pub has_presentable_surface: bool,}@@ -69,7 +69,7 @@ pub struct FfiVideoSinkContent {pub has_frame: bool,pub frame_id: u64,pub frame_holds_high_dynamic_range: bool,- // Whether the window server can show the frame as it is.+ /// Whether the window server can show the frame as it is.pub frame_has_surface: bool,}@@ -106,7 +106,7 @@ pub enum MediaKind {}/// Where the window server shows a sublayer, and how it clips it, in device pixels.-#[derive(Clone, Copy, Debug, Default)]+#[derive(Clone, Copy, Debug, Default, PartialEq)]#[repr(C)]pub struct FfiSublayerPlacement {pub content_rect: IntRect,@@ -133,7 +133,7 @@ pub enum SublayerContentKind {/// A sublayer the window server shows above a frame: a canvas of the context by its id, a video by the handle of its/// sink, or a surface.-#[derive(Clone, Copy, Debug)]+#[derive(Clone, Copy, Debug, PartialEq)]#[repr(C)]pub struct FfiSublayer {pub identity: u64,@@ -662,8 +662,8 @@ impl RasterHost {&self,buffer: Core_AnonymousBuffer,sizes: &[PackedChunkSize],- ) -> Result<Vec<ReceivedChunk>, &'static str> {- let Some((size, file)) = buffer.shared_memory else {+ ) -> Result<Vec<ListChunk>, &'static str> {+ let Some((size_of_packed_chunks, file)) = buffer.shared_memory else {// SAFETY: Nothing is read from an empty buffer.return unsafe { receive_packed_chunks_from_shared_memory(std::ptr::null(), 0, sizes) };};@@ -672,18 +672,24 @@ impl RasterHost {#[cfg(windows)]let descriptor = file.0.into_raw();let mut data = std::ptr::null();- let mut data_size = 0;+ let mut mapped_size = 0;// SAFETY: The host outlives this, and takes the descriptor over.- let mapping =- unsafe { (self.0.map_shared_memory)(self.host(), descriptor, size, &raw mut data, &raw mut data_size) };+ let mapping = unsafe {+ (self.0.map_shared_memory)(+ self.host(),+ descriptor,+ size_of_packed_chunks,+ &raw mut data,+ &raw mut mapped_size,+ )+ };if mapping.is_null() {return Err("Display list buffer is smaller than it claims");}- // The mapping may hold more than the chunks, which fill the size the buffer was sent with.- let chunks = match usize::try_from(size) {- Ok(size) if size <= data_size => {- // SAFETY: The mapping holds `data_size` readable bytes at `data` until it is dropped below.- unsafe { receive_packed_chunks_from_shared_memory(data, size, sizes) }+ let chunks = match usize::try_from(size_of_packed_chunks) {+ Ok(size_of_packed_chunks) if size_of_packed_chunks <= mapped_size => {+ // SAFETY: The mapping holds `mapped_size` readable bytes at `data` until it is dropped below.+ unsafe { receive_packed_chunks_from_shared_memory(data, size_of_packed_chunks, sizes) }}_ => Err("Display list buffer is smaller than it claims"),};diff --git a/Tests/LibWeb/Ref/expected/backdrop-filter-is-a-backdrop-root-for-what-it-holds-ref.html b/Tests/LibWeb/Ref/expected/backdrop-filter-is-a-backdrop-root-for-what-it-holds-ref.htmlnew file mode 100644index 00000000000..83fd0a97d76--- /dev/null+++ b/Tests/LibWeb/Ref/expected/backdrop-filter-is-a-backdrop-root-for-what-it-holds-ref.html@@ -0,0 +1,8 @@+<!DOCTYPE html>+<style>+ body { margin: 0; background: cyan; }+ div { position: absolute; top: 0; width: 50px; height: 50px; background: green; }+</style>+<div style="left: 0"></div>+<div style="left: 150px; opacity: 0.99"></div>+<div style="top: 60px; left: 0; background: black"></div>diff --git a/Tests/LibWeb/Ref/expected/iframe-composited-blur-reads-past-the-frame-ref.html b/Tests/LibWeb/Ref/expected/iframe-composited-blur-reads-past-the-frame-ref.htmlnew file mode 100644index 00000000000..afbbab4af4f--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-composited-blur-reads-past-the-frame-ref.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; left: -100px; top: 25px; width: 200px; height: 100px; background: black; }+ .square { position: absolute; left: 160px; top: 25px; width: 20px; height: 20px; background: lime; }+ </style>+ <div style='filter: blur(12px)'>+ <div class='box'></div>+ <div class='square'></div>+ </div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-composited-drop-shadow-of-content-outside-its-clip-ref.html b/Tests/LibWeb/Ref/expected/iframe-composited-drop-shadow-of-content-outside-its-clip-ref.htmlnew file mode 100644index 00000000000..4cb6af9f5ab--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-composited-drop-shadow-of-content-outside-its-clip-ref.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .clip { position: relative; overflow: hidden; width: 200px; height: 150px; }+ .box { position: absolute; left: -50px; top: 20px; width: 40px; height: 40px; background: black; }+ .square { position: absolute; left: 100px; top: 100px; width: 20px; height: 20px; background: lime; }+ </style>+ <div class='clip'>+ <div style='filter: drop-shadow(80px 0 0 blue)'>+ <div class='box'></div>+ <div class='square'></div>+ </div>+ </div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-content-scrolled-into-view-within-the-cells-shown-before-ref.html b/Tests/LibWeb/Ref/expected/iframe-content-scrolled-into-view-within-the-cells-shown-before-ref.htmlnew file mode 100644index 00000000000..66223e31afa--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-content-scrolled-into-view-within-the-cells-shown-before-ref.html@@ -0,0 +1,12 @@+<!DOCTYPE html>+<style>+ body { margin: 0; }+ iframe { display: block; width: 300px; height: 200px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ html { scrollbar-width: none; }+ body { margin: 0; }+ #box { position: absolute; left: 50px; top: 100px; width: 100px; height: 100px; background: green; opacity: 0.5; }+ </style>+ <div id='box'></div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-filter-reading-farther-than-tiles-are-followed-ref.html b/Tests/LibWeb/Ref/expected/iframe-filter-reading-farther-than-tiles-are-followed-ref.htmlnew file mode 100644index 00000000000..94560a865e2--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-filter-reading-farther-than-tiles-are-followed-ref.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; left: -2400px; top: 20px; width: 40px; height: 40px; background: black; }+ .square { position: absolute; left: 150px; top: 100px; width: 20px; height: 20px; background: lime; }+ </style>+ <div style='filter: drop-shadow(2500px 0 0 blue)'>+ <div class='box'></div>+ <div class='square'></div>+ </div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animation-at-an-angle-ref.html b/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animation-at-an-angle-ref.htmlnew file mode 100644index 00000000000..b86712a33c3--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animation-at-an-angle-ref.html@@ -0,0 +1,9 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 200px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ </style>+ <div style='position: absolute; left: 50px; top: 50px; width: 80px; height: 80px; background: navy; transform: rotate(30deg)'></div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animations-ref.html b/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animations-ref.htmlnew file mode 100644index 00000000000..004deaaac0c--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-layers-of-compositor-animations-ref.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 300px; height: 220px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; width: 60px; height: 60px; }+ </style>+ <div class='box' style='left: 10px; top: 10px; background: green'></div>+ <div class='box' style='left: 40px; top: 40px; background: blue; opacity: 0.5'></div>+ <div class='box' style='left: 150px; top: 20px; background: orange; transform: rotate(90deg)'><div style='height: 20px; background: purple'></div></div>+ <div class='box' style='left: 170px; top: 40px; width: 20px; height: 20px; background: black'></div>+ <div style='position: absolute; left: 20px; top: 120px; width: 200px; height: 50px; overflow: hidden; border-radius: 16px; background: gray'>+ <div style='width: 50px; height: 50px; background: red; transform: translateX(40px)'></div>+ </div>+ <div class='box' style='left: 240px; top: 150px; width: 20px; height: 20px; background: teal; transform: scale(2)'></div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-tile-of-planes-put-into-a-3d-sorting-context-ref.html b/Tests/LibWeb/Ref/expected/iframe-tile-of-planes-put-into-a-3d-sorting-context-ref.htmlnew file mode 100644index 00000000000..cb03baa7942--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-tile-of-planes-put-into-a-3d-sorting-context-ref.html@@ -0,0 +1,7 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>body { margin: 0; }</style>+ <div style='width: 200px; height: 150px; background: red'></div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/iframe-tiles-of-sibling-opacity-groups-ref.html b/Tests/LibWeb/Ref/expected/iframe-tiles-of-sibling-opacity-groups-ref.htmlnew file mode 100644index 00000000000..f8b80f67082--- /dev/null+++ b/Tests/LibWeb/Ref/expected/iframe-tiles-of-sibling-opacity-groups-ref.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; top: 20px; width: 100px; height: 100px; background: black; opacity: 0.5; }+ </style>+ <div class='box' style='left: 20px'></div>+ <div class='box' style='left: 70px'></div>"></iframe>diff --git a/Tests/LibWeb/Ref/expected/sticky-toolbar-spinner-is-covered-by-content-painted-after-it-ref.html b/Tests/LibWeb/Ref/expected/sticky-toolbar-spinner-is-covered-by-content-painted-after-it-ref.htmlnew file mode 100644index 00000000000..d1b3a5dbf62--- /dev/null+++ b/Tests/LibWeb/Ref/expected/sticky-toolbar-spinner-is-covered-by-content-painted-after-it-ref.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<html class="reftest-wait">+<style>+ body { margin: 0; }+ #scroller { position: absolute; left: 0; top: 0; width: 800px; height: 600px; overflow: auto; }+ #toolbar { position: sticky; top: 0; height: 60px; }+ #label { position: absolute; left: 10px; top: 10px; width: 100px; height: 40px; background: green; }+ #spinner { position: absolute; left: 650px; top: 10px; width: 40px; height: 40px; background: orange; transform: rotate(45deg); }+ .card { position: relative; height: 200px; margin-bottom: 20px; background: blue; }+</style>+<div id="scroller">+ <div id="toolbar"><div id="label"></div><div id="spinner"></div></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+</div>+<script>+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ document.getElementById("scroller").scrollTop = 100;+ for (let i = 0; i < 4; ++i)+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/backdrop-filter-is-a-backdrop-root-for-what-it-holds.html b/Tests/LibWeb/Ref/input/backdrop-filter-is-a-backdrop-root-for-what-it-holds.htmlnew file mode 100644index 00000000000..91366714e14--- /dev/null+++ b/Tests/LibWeb/Ref/input/backdrop-filter-is-a-backdrop-root-for-what-it-holds.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<link rel="match" href="../expected/backdrop-filter-is-a-backdrop-root-for-what-it-holds-ref.html">+<style>+ body { margin: 0; background: cyan; }+ div { position: absolute; width: 50px; height: 50px; }+ /* Each outer box reads its backdrop, so what is inside it reads only what the box paints, not the cyan behind it.+ The inner boxes sit beside the outer one, where it paints nothing, so inverting what they read leaves the cyan. */+ .outer { top: 0; background: green; backdrop-filter: invert(0); }+ #opaque-outer { left: 0; }+ #translucent-outer { left: 150px; opacity: 0.99; }+ .inverting { left: 50px; backdrop-filter: invert(1); }+ .blending { top: 60px; left: 0; background: black; mix-blend-mode: difference; }+</style>+<div class="outer" id="opaque-outer"><div class="inverting"></div><div class="blending"></div></div>+<div class="outer" id="translucent-outer"><div class="inverting"></div></div>diff --git a/Tests/LibWeb/Ref/input/iframe-composited-blur-reads-past-the-frame.html b/Tests/LibWeb/Ref/input/iframe-composited-blur-reads-past-the-frame.htmlnew file mode 100644index 00000000000..cb137517b66--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-composited-blur-reads-past-the-frame.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<link rel="match" href="../expected/iframe-composited-blur-reads-past-the-frame-ref.html">+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; left: -100px; top: 25px; width: 200px; height: 100px; background: black; }+ canvas { position: absolute; left: 160px; top: 25px; }+ </style>+ <div style='filter: blur(12px)'>+ <div class='box'></div>+ <canvas width='20' height='20'></canvas>+ </div>+ <script>+ const context = document.querySelector('canvas').getContext('2d');+ context.fillStyle = 'lime';+ context.fillRect(0, 0, 20, 20);+ </script>"></iframe>diff --git a/Tests/LibWeb/Ref/input/iframe-composited-drop-shadow-of-content-outside-its-clip.html b/Tests/LibWeb/Ref/input/iframe-composited-drop-shadow-of-content-outside-its-clip.htmlnew file mode 100644index 00000000000..d13fc02bd28--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-composited-drop-shadow-of-content-outside-its-clip.html@@ -0,0 +1,23 @@+<!DOCTYPE html>+<link rel="match" href="../expected/iframe-composited-drop-shadow-of-content-outside-its-clip-ref.html">+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .clip { position: relative; overflow: hidden; width: 200px; height: 150px; }+ .box { position: absolute; left: -50px; top: 20px; width: 40px; height: 40px; background: black; }+ canvas { position: absolute; left: 100px; top: 100px; }+ </style>+ <div class='clip'>+ <div style='filter: drop-shadow(80px 0 0 blue)'>+ <div class='box'></div>+ <canvas width='20' height='20'></canvas>+ </div>+ </div>+ <script>+ const context = document.querySelector('canvas').getContext('2d');+ context.fillStyle = 'lime';+ context.fillRect(0, 0, 20, 20);+ </script>"></iframe>diff --git a/Tests/LibWeb/Ref/input/iframe-content-scrolled-into-view-within-the-cells-shown-before.html b/Tests/LibWeb/Ref/input/iframe-content-scrolled-into-view-within-the-cells-shown-before.htmlnew file mode 100644index 00000000000..34d1a4bd6ca--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-content-scrolled-into-view-within-the-cells-shown-before.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/iframe-content-scrolled-into-view-within-the-cells-shown-before-ref.html">+<meta name="fuzzy" content="maxDifference=0-1;totalPixels=0-10000">+<style>+ body { margin: 0; }+ iframe { display: block; width: 300px; height: 200px; border: 0; }+</style>+<iframe></iframe>+<script>+ // The box lies below the viewport of the iframe, in the cells of tiles the viewport shows. The compositor scrolls the+ // iframe so that the box shows in those cells.+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ @keyframes still-fade { from { opacity: 0.5; } to { opacity: 0.5; } }+ html { scrollbar-width: none; }+ body { margin: 0; height: 2000px; }+ #box { position: absolute; left: 50px; top: 300px; width: 100px; height: 100px; background: green; animation: still-fade 100s linear infinite; }+ </style>+ <div id="box"></div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ for (let i = 0; i < 4; ++i)+ await frame();+ if (!window.internals) {+ iframe.contentWindow.scrollTo(0, 200);+ document.documentElement.classList.remove("reftest-wait");+ return;+ }+ while (internals.compositorWheelTargetAt(100, 100, 0, 200).document !== iframe.contentDocument)+ await frame();+ const scrollEnded = new Promise(resolve => iframe.contentWindow.addEventListener("scrollend", resolve, { once: true }));+ await internals.wheelThroughUIProcess(100, 100, 0, 200);+ await scrollEnded;+ for (let i = 0; i < 4; ++i)+ await frame();+ internals.signalTestIsDone("PASS");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/iframe-filter-reading-farther-than-tiles-are-followed.html b/Tests/LibWeb/Ref/input/iframe-filter-reading-farther-than-tiles-are-followed.htmlnew file mode 100644index 00000000000..2f170ea3c7f--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-filter-reading-farther-than-tiles-are-followed.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<link rel="match" href="../expected/iframe-filter-reading-farther-than-tiles-are-followed-ref.html">+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe srcdoc="<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; left: -2400px; top: 20px; width: 40px; height: 40px; background: black; }+ canvas { position: absolute; left: 150px; top: 100px; }+ </style>+ <div style='filter: drop-shadow(2500px 0 0 blue)'>+ <div class='box'></div>+ <canvas width='20' height='20'></canvas>+ </div>+ <script>+ const context = document.querySelector('canvas').getContext('2d');+ context.fillStyle = 'lime';+ context.fillRect(0, 0, 20, 20);+ </script>"></iframe>diff --git a/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animation-at-an-angle.html b/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animation-at-an-angle.htmlnew file mode 100644index 00000000000..d965ce4b1c1--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animation-at-an-angle.html@@ -0,0 +1,27 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/iframe-layers-of-compositor-animation-at-an-angle-ref.html">+<!-- The compositor resamples the rotated tiles bilinearly, which a direct raster of the rotated box does not. -->+<meta name="fuzzy" content="maxDifference=0-80;totalPixels=0-400">+<style>+ iframe { display: block; width: 200px; height: 200px; border: 0; }+</style>+<iframe></iframe>+<script>+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ @keyframes still-turn { from { transform: rotate(30deg); } to { transform: rotate(30deg); } }+ body { margin: 0; }+ </style>+ <div style="position: absolute; left: 50px; top: 50px; width: 80px; height: 80px; background: navy; animation: still-turn 100s linear infinite"></div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ for (let i = 0; i < 4; ++i)+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animations.html b/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animations.htmlnew file mode 100644index 00000000000..0ddc6bce691--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-layers-of-compositor-animations.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/iframe-layers-of-compositor-animations-ref.html">+<!-- The rounded clip around the slide is antialiased as the frame composites it rather than in its raster. -->+<meta name="fuzzy" content="maxDifference=0-2;totalPixels=0-20">+<style>+ iframe { display: block; width: 300px; height: 220px; border: 0; }+</style>+<iframe></iframe>+<script>+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ @keyframes still-fade { from { opacity: 0.5; } to { opacity: 0.5; } }+ @keyframes still-turn { from { transform: rotate(90deg); } to { transform: rotate(90deg); } }+ @keyframes still-slide { from { transform: translateX(40px); } to { transform: translateX(40px); } }+ @keyframes still-zoom { from { transform: scale(2); } to { transform: scale(2); } }+ body { margin: 0; }+ .box { position: absolute; width: 60px; height: 60px; }+ </style>+ <div class="box" style="left: 10px; top: 10px; background: green"></div>+ <div class="box" style="left: 40px; top: 40px; background: blue; animation: still-fade 100s linear infinite"></div>+ <div class="box" style="left: 150px; top: 20px; background: orange; animation: still-turn 100s linear infinite"><div style="height: 20px; background: purple"></div></div>+ <div class="box" style="left: 170px; top: 40px; width: 20px; height: 20px; background: black"></div>+ <div style="position: absolute; left: 20px; top: 120px; width: 200px; height: 50px; overflow: hidden; border-radius: 16px; background: gray">+ <div style="width: 50px; height: 50px; background: red; animation: still-slide 100s linear infinite"></div>+ </div>+ <div class="box" style="left: 240px; top: 150px; width: 20px; height: 20px; background: teal; animation: still-zoom 100s linear infinite"></div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ for (let i = 0; i < 4; ++i)+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/iframe-tile-of-planes-put-into-a-3d-sorting-context.html b/Tests/LibWeb/Ref/input/iframe-tile-of-planes-put-into-a-3d-sorting-context.htmlnew file mode 100644index 00000000000..5b640f7e0ab--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-tile-of-planes-put-into-a-3d-sorting-context.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/iframe-tile-of-planes-put-into-a-3d-sorting-context-ref.html">+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe></iframe>+<script>+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ body { margin: 0; }+ #context { transform: rotateX(0deg); }+ .plane { position: absolute; left: 0; top: 0; width: 200px; height: 150px; }+ </style>+ <div id="context">+ <div class="plane" style="background: red; transform: translateZ(20px)"></div>+ <div class="plane" style="background: blue; transform: translateZ(5px)"></div>+ </div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ await frame();+ await frame();+ // Sorted by depth, the plane painted first is in front.+ iframe.contentDocument.getElementById("context").style.transformStyle = "preserve-3d";+ await frame();+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/iframe-tiles-of-sibling-opacity-groups.html b/Tests/LibWeb/Ref/input/iframe-tiles-of-sibling-opacity-groups.htmlnew file mode 100644index 00000000000..30835c9a339--- /dev/null+++ b/Tests/LibWeb/Ref/input/iframe-tiles-of-sibling-opacity-groups.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/iframe-tiles-of-sibling-opacity-groups-ref.html">+<style>+ iframe { display: block; width: 200px; height: 150px; border: 0; }+</style>+<iframe></iframe>+<script>+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ body { margin: 0; }+ .box { position: absolute; top: 20px; width: 100px; height: 100px; background: black; }+ </style>+ <div id="group" style="opacity: 0.5">+ <div class="box" style="left: 20px"></div>+ <div class="box" style="left: 70px"></div>+ </div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ await frame();+ await frame();+ // The overlap of two groups is darker than that of one group holding both boxes.+ const content = iframe.contentDocument;+ content.getElementById("group").style.removeProperty("opacity");+ for (const box of content.querySelectorAll(".box"))+ box.style.opacity = "0.5";+ await frame();+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Ref/input/sticky-toolbar-spinner-is-covered-by-content-painted-after-it.html b/Tests/LibWeb/Ref/input/sticky-toolbar-spinner-is-covered-by-content-painted-after-it.htmlnew file mode 100644index 00000000000..bbbea32e53d--- /dev/null+++ b/Tests/LibWeb/Ref/input/sticky-toolbar-spinner-is-covered-by-content-painted-after-it.html@@ -0,0 +1,43 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/sticky-toolbar-spinner-is-covered-by-content-painted-after-it-ref.html">+<style>+ body { margin: 0; }+ iframe { display: block; width: 800px; height: 600px; border: 0; }+</style>+<!-- The label and the spinner of the transparent toolbar are in different tiles. The cards are painted after the+ toolbar, so a card that scrolls under it covers the spinner too. The page is in an iframe, which is drawn through+ its layers and tiles. -->+<iframe></iframe>+<script>+ const iframe = document.querySelector("iframe");+ iframe.srcdoc = `<!DOCTYPE html>+ <style>+ @keyframes still-turn { from { transform: rotate(45deg); } to { transform: rotate(45deg); } }+ body { margin: 0; }+ #scroller { position: absolute; left: 0; top: 0; width: 800px; height: 600px; overflow: auto; }+ #toolbar { position: sticky; top: 0; height: 60px; }+ #label { position: absolute; left: 10px; top: 10px; width: 100px; height: 40px; background: green; }+ #spinner { position: absolute; left: 650px; top: 10px; width: 40px; height: 40px; background: orange; animation: still-turn 100s linear infinite; }+ .card { position: relative; height: 200px; margin-bottom: 20px; background: blue; }+ </style>+ <div id="scroller">+ <div id="toolbar"><div id="label"></div><div id="spinner"></div></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ <div class="card"></div>+ </div>`;+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ window.onload = async () => {+ iframe.contentDocument.getElementById("scroller").scrollTop = 100;+ for (let i = 0; i < 4; ++i)+ await frame();+ if (window.internals)+ internals.signalTestIsDone("PASS");+ else+ document.documentElement.classList.remove("reftest-wait");+ };+</script>diff --git a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-region-hit-testing.txt b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-region-hit-testing.txtindex 9c8395c232a..06da6db8466 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-region-hit-testing.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-region-hit-testing.txt@@ -18,7 +18,10 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[20,160 100x100] min_scroll_offset=[0,0] max_scroll_offset=[100,0] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-CompositorBlockingWheelEventRegion@s2/e0 rect=[20,20 100x100] owner=BlockContainer<DIV>#transformed phase=scroll-metadata-CompositorBlockingWheelEventRegion@s3/c0/e0 rect=[20,160 200x100] owner=BlockContainer<DIV>#clipped-target phase=scroll-metadata+L0 CompositorBlockingWheelEventRegion@s2/e0 rect=[20,20 100x100] owner=BlockContainer<DIV>#transformed phase=scroll-metadata+L0 CompositorBlockingWheelEventRegion@s3/c0/e0 rect=[20,160 200x100] owner=BlockContainer<DIV>#clipped-target phase=scroll-metadatadiff --git a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-regions.txt b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-regions.txtindex 412bec0f389..5560a4d9303 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-regions.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-event-regions.txt@@ -36,16 +36,19 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[0,0 200x200] min_scroll_offset=[0,0] max_scroll_offset=[800,900] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 200x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata-CompositorBlockingWheelEventRegion@s2/c0/e0 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,100 1000x1000] owner=BlockContainer<DIV>#spacer phase=scroll-metadata-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] expanded_thumb_rect=[187,2 11x36] scroll_size=0.17819444444444443 expanded_scroll_size=0.17819444444444443 max_scroll_offset=900 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] scroll_size=0.17819444444444443 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] expanded_thumb_rect=[2,187 36x11] scroll_size=0.181015625 expanded_scroll_size=0.181015625 max_scroll_offset=800 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] scroll_size=0.181015625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 200x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata+L0 CompositorBlockingWheelEventRegion@s2/c0/e0 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,100 1000x1000] owner=BlockContainer<DIV>#spacer phase=scroll-metadata+L0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] expanded_thumb_rect=[187,2 11x36] scroll_size=0.17819444444444443 expanded_scroll_size=0.17819444444444443 max_scroll_offset=900 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] scroll_size=0.17819444444444443 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] expanded_thumb_rect=[2,187 36x11] scroll_size=0.181015625 expanded_scroll_size=0.181015625 max_scroll_offset=800 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L0 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] scroll_size=0.181015625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-listener-invalidation.txt b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-listener-invalidation.txtindex 1c1e0882156..ccb4483344f 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-listener-invalidation.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/blocking-wheel-listener-invalidation.txt@@ -10,5 +10,8 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1413] is_viewport=true+Layers:+ [L0] single layer replaying the whole list: empty display list+DisplayList:diff --git a/Tests/LibWeb/Text/expected/async-scrolling/nested-navigable-wheel-admission.txt b/Tests/LibWeb/Text/expected/async-scrolling/nested-navigable-wheel-admission.txtindex 044e3b1c679..c0924b040e2 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/nested-navigable-wheel-admission.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/nested-navigable-wheel-admission.txt@@ -14,8 +14,8 @@ ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1413] is_viewport=trueLayers:- [L0] base rect=[0,0 800x600]- [L1] composited context rect=[37,37 166x126]+ [L0] base space=viewport+ [L2] composited context #0 space=document region=[37,37 166x126]DisplayList:L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata@@ -23,6 +23,6 @@ L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800xL0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2000] owner=BlockContainer<BODY> phase=scroll-metadataL0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2000] owner=BlockContainer<DIV>#spacer phase=scroll-metadataL0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[40,40 160x120] owner=NavigableContainerViewport<IFRAME> phase=scroll-metadata-L1 DrawCompositedContext@s1/e0 dst_rect=[40,40 160x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[40,40 160x120]] owner=NavigableContainerViewport<IFRAME> phase=foreground+L2 DrawCompositedContext@s1/e0 dst_rect=[40,40 160x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[40,40 160x120]] owner=NavigableContainerViewport<IFRAME> phase=foregroundL0 CompositorNestedContextWheelRegion@s1/e0 rect=[40,40 160x120] child_context_id=context1 owner=NavigableContainerViewport<IFRAME> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/async-scrolling/nested-scroller-keeps-sync-wheel.txt b/Tests/LibWeb/Text/expected/async-scrolling/nested-scroller-keeps-sync-wheel.txtindex e20c48fc22e..96ac1e8c04c 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/nested-scroller-keeps-sync-wheel.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/nested-scroller-keeps-sync-wheel.txt@@ -15,13 +15,16 @@ ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1513] is_viewport=trueScrollNode scroll_node_index=s2 parent_scroll_node_index=s1 scrollport_rect=[0,0 100x100] min_scroll_offset=[0,0] max_scroll_offset=[0,400] is_viewport=false+Layers:+ [L1] base space=document+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV>#page-spacer phase=scroll-metadata-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV>#page-spacer phase=scroll-metadata+L1 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-parent-nodes.txt b/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-parent-nodes.txtindex 11696b5a676..6695d4dba3e 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-parent-nodes.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-parent-nodes.txt@@ -18,16 +18,20 @@ ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1513] is_viewport=trueScrollNode scroll_node_index=s3 parent_scroll_node_index=s1 scrollport_rect=[0,0 100x100] min_scroll_offset=[0,0] max_scroll_offset=[400,400] is_viewport=false+Layers:+ [L0] base space=viewport+ [L2] painted space=sticky@s2 in document+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV> phase=scroll-metadata-CompositorWheelHitTestTarget@s2/e0 target_scroll_node_index=s1 rect=[0,0 800x100] owner=BlockContainer<DIV>#sticky phase=scroll-metadata-CompositorWheelHitTestTarget@s2/e0 target_scroll_node_index=s3 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s3/c0/e0 target_scroll_node_index=s3 rect=[0,0 500x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata-CompositorScrollbar@s2/e0 scroll_node_index=s3 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s2/e0 scroll_node_index=s3 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-CompositorScrollbar@s2/e0 scroll_node_index=s3 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] expanded_thumb_rect=[2,87 24x11] scroll_size=0.1425 expanded_scroll_size=0.1425 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s2/e0 scroll_node_index=s3 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] scroll_size=0.1425 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/e0 target_scroll_node_index=s1 rect=[0,0 800x100] owner=BlockContainer<DIV>#sticky phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/e0 target_scroll_node_index=s3 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s3/c0/e0 target_scroll_node_index=s3 rect=[0,0 500x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata+L0 CompositorScrollbar@s2/e0 scroll_node_index=s3 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L2 PaintScrollBar@s2/e0 scroll_node_index=s3 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorScrollbar@s2/e0 scroll_node_index=s3 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] expanded_thumb_rect=[2,87 24x11] scroll_size=0.1425 expanded_scroll_size=0.1425 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L2 PaintScrollBar@s2/e0 scroll_node_index=s3 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] scroll_size=0.1425 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-shape.txt b/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-shape.txtindex a38852cdccb..42e98717d13 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-shape.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/scroll-tree-shape.txt@@ -19,15 +19,18 @@ ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1513] is_viewport=trueScrollNode scroll_node_index=s2 parent_scroll_node_index=s1 scrollport_rect=[0,0 100x100] min_scroll_offset=[0,0] max_scroll_offset=[400,400] is_viewport=false+Layers:+ [L1] base space=document+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 500x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV> phase=scroll-metadata-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] expanded_thumb_rect=[2,87 24x11] scroll_size=0.1425 expanded_scroll_size=0.1425 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] scroll_size=0.1425 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L1 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 500x500] owner=BlockContainer<DIV>#spacer phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV> phase=scroll-metadata+L1 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] expanded_thumb_rect=[2,87 24x11] scroll_size=0.1425 expanded_scroll_size=0.1425 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L1 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,91 24x7] track_rect=[0,91 85x9] expanded_gutter_rect=[0,85 85x15] scroll_size=0.1425 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/async-scrolling/sticky-areas.txt b/Tests/LibWeb/Text/expected/async-scrolling/sticky-areas.txtindex 5e21c116f15..34c8cca7993 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/sticky-areas.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/sticky-areas.txt@@ -18,6 +18,10 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1429] is_viewport=true+Layers:+ [L0] base space=viewport+ [L2] painted space=sticky@s2 in document+DisplayList:-DrawGlyphRun@s3/e0 font_id=font1 glyphs=6 rect=[0,0 45x16] glyph_bounding_rect=[0,0 51x15] translation=[0,13] color=rgb(0, 0, 0) text="sticky" owner=BlockContainer<DIV>#inner phase=foreground+L2 DrawGlyphRun@s3/e0 font_id=font1 glyphs=6 rect=[0,0 45x16] glyph_bounding_rect=[0,0 51x15] translation=[0,13] color=rgb(0, 0, 0) text="sticky" owner=BlockContainer<DIV>#inner phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/async-scrolling/viewport-wheel-with-nested-scroller.txt b/Tests/LibWeb/Text/expected/async-scrolling/viewport-wheel-with-nested-scroller.txtindex 90fb9e8cb9b..ef8d9b57086 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/viewport-wheel-with-nested-scroller.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/viewport-wheel-with-nested-scroller.txt@@ -17,13 +17,16 @@ ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1513] is_viewport=trueScrollNode scroll_node_index=s2 parent_scroll_node_index=s1 scrollport_rect=[0,0 100x100] min_scroll_offset=[0,0] max_scroll_offset=[0,400] is_viewport=false+Layers:+ [L1] base space=document+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x500] owner=BlockContainer<DIV>#scroller-spacer phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV>#page-spacer phase=scroll-metadata-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2113] owner=BlockContainer<HTML> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2100] owner=BlockContainer<BODY> phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x500] owner=BlockContainer<DIV>#scroller-spacer phase=scroll-metadata+L1 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,100 800x2000] owner=BlockContainer<DIV>#page-spacer phase=scroll-metadata+L1 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] expanded_thumb_rect=[87,2 11x24] scroll_size=0.18 expanded_scroll_size=0.18 max_scroll_offset=400 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L1 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[91,2 7x24] track_rect=[91,0 9x100] expanded_gutter_rect=[85,0 15x100] scroll_size=0.18 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/async-scrolling/wheel-scroll-admission.txt b/Tests/LibWeb/Text/expected/async-scrolling/wheel-scroll-admission.txtindex 09b2e9eca09..4a9403bfc94 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/wheel-scroll-admission.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/wheel-scroll-admission.txt@@ -23,17 +23,20 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[0,0 200x200] min_scroll_offset=[0,0] max_scroll_offset=[800,900] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 200x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata-CompositorBlockingWheelEventRegion@s2/c0/e0 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,100 1000x1000] owner=BlockContainer<DIV>#spacer phase=scroll-metadata-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] expanded_thumb_rect=[187,2 11x36] scroll_size=0.17819444444444443 expanded_scroll_size=0.17819444444444443 max_scroll_offset=900 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] scroll_size=0.17819444444444443 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] expanded_thumb_rect=[2,187 36x11] scroll_size=0.181015625 expanded_scroll_size=0.181015625 max_scroll_offset=800 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] scroll_size=0.181015625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[250,0 100x100] owner=BlockContainer<DIV>#not-scrollable phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 200x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata+L0 CompositorBlockingWheelEventRegion@s2/c0/e0 rect=[0,0 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,100 1000x1000] owner=BlockContainer<DIV>#spacer phase=scroll-metadata+L0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] expanded_thumb_rect=[187,2 11x36] scroll_size=0.17819444444444443 expanded_scroll_size=0.17819444444444443 max_scroll_offset=900 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,2 7x36] track_rect=[191,0 9x200] expanded_gutter_rect=[185,0 15x200] scroll_size=0.17819444444444443 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] expanded_thumb_rect=[2,187 36x11] scroll_size=0.181015625 expanded_scroll_size=0.181015625 max_scroll_offset=800 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L0 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[2,191 36x7] track_rect=[0,191 185x9] expanded_gutter_rect=[0,185 185x15] scroll_size=0.181015625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[250,0 100x100] owner=BlockContainer<DIV>#not-scrollable phase=scroll-metadatadiff --git a/Tests/LibWeb/Text/expected/css/text-underline-position.txt b/Tests/LibWeb/Text/expected/css/text-underline-position.txtindex 6b1aeb31245..db86baf6031 100644--- a/Tests/LibWeb/Text/expected/css/text-underline-position.txt+++ b/Tests/LibWeb/Text/expected/css/text-underline-position.txt@@ -5,10 +5,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,8 28x16] glyph_bounding_rect=[8,8 30x15] translation=[8,21] color=rgb(0, 0, 0) text="foo" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,23 27x2] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[35,8 9x16] glyph_bounding_rect=[35,8 13x15] translation=[35.15625,21] color=rgb(0, 0, 0) text=" " owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[43,8 28x16] glyph_bounding_rect=[43,8 32x15] translation=[43.15625,21] color=rgb(0, 0, 0) text="bar" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[43,26 28x2] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,8 28x16] glyph_bounding_rect=[8,8 30x15] translation=[8,21] color=rgb(0, 0, 0) text="foo" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,23 27x2] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[35,8 9x16] glyph_bounding_rect=[35,8 13x15] translation=[35.15625,21] color=rgb(0, 0, 0) text=" " owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[43,8 28x16] glyph_bounding_rect=[43,8 32x15] translation=[43.15625,21] color=rgb(0, 0, 0) text="bar" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[43,26 28x2] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/abspos-escaping-overflow-clip-inside-opacity.txt b/Tests/LibWeb/Text/expected/display_list/abspos-escaping-overflow-clip-inside-opacity.txtindex 188f4c3f137..39d0106a3f1 100644--- a/Tests/LibWeb/Text/expected/display_list/abspos-escaping-overflow-clip-inside-opacity.txt+++ b/Tests/LibWeb/Text/expected/display_list/abspos-escaping-overflow-clip-inside-opacity.txt@@ -6,7 +6,10 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[opacity=0.5] (BlockContainer<DIV>#group)+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e1 rect=[0,0 200x200] color=rgb(255, 0, 0) owner=BlockContainer<DIV>#group phase=background-FillRect@s1/e1 rect=[50,50 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#escaping phase=background+L0 FillRect@s1/e1 rect=[0,0 200x200] color=rgb(255, 0, 0) owner=BlockContainer<DIV>#group phase=background+L0 FillRect@s1/e1 rect=[50,50 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#escaping phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/abspos-inside-nested-opacity-inside-relpos.txt b/Tests/LibWeb/Text/expected/display_list/abspos-inside-nested-opacity-inside-relpos.txtindex 63af18e6418..583eb4abe13 100644--- a/Tests/LibWeb/Text/expected/display_list/abspos-inside-nested-opacity-inside-relpos.txt+++ b/Tests/LibWeb/Text/expected/display_list/abspos-inside-nested-opacity-inside-relpos.txt@@ -9,6 +9,9 @@ AccumulatedVisualContext Tree:[e1 in s1 out=c0] effects=[opacity=0.5] (BlockContainer<DIV>.outer-opacity)[e2 in s1 out=c0] effects=[opacity=0.3] (BlockContainer<DIV>.inner-opacity)+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e2 rect=[8,8 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.abspos phase=background+L0 FillRect@s1/c0/e2 rect=[8,8 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.abspos phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/abspos-inside-opacity-inside-relpos.txt b/Tests/LibWeb/Text/expected/display_list/abspos-inside-opacity-inside-relpos.txtindex 9d1b4b7aded..0a3361abcdd 100644--- a/Tests/LibWeb/Text/expected/display_list/abspos-inside-opacity-inside-relpos.txt+++ b/Tests/LibWeb/Text/expected/display_list/abspos-inside-opacity-inside-relpos.txt@@ -8,6 +8,9 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1 out=c0] effects=[opacity=0.5] (BlockContainer<DIV>.opacity)+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e1 rect=[8,8 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.abspos phase=background+L0 FillRect@s1/c0/e1 rect=[8,8 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.abspos phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/abspos-under-clipped-transformed-opacity.txt b/Tests/LibWeb/Text/expected/display_list/abspos-under-clipped-transformed-opacity.txtindex dd407ffcacb..869ffa7bef3 100644--- a/Tests/LibWeb/Text/expected/display_list/abspos-under-clipped-transformed-opacity.txt+++ b/Tests/LibWeb/Text/expected/display_list/abspos-under-clipped-transformed-opacity.txt@@ -7,6 +7,9 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s2] effects=[opacity=0.5] (BlockContainer<DIV>#clipped)+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e1 rect=[160,160 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#escaping phase=background+L0 FillRect@s2/e1 rect=[160,160 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#escaping phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/animated-clip-path-visual-context-update.txt b/Tests/LibWeb/Text/expected/display_list/animated-clip-path-visual-context-update.txtindex ee1c287ed1f..fdd46d7d9ba 100644--- a/Tests/LibWeb/Text/expected/display_list/animated-clip-path-visual-context-update.txt+++ b/Tests/LibWeb/Text/expected/display_list/animated-clip-path-visual-context-update.txt@@ -10,6 +10,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/animated-transform-visual-context-update.txt b/Tests/LibWeb/Text/expected/display_list/animated-transform-visual-context-update.txtindex 6968897d5a9..6f639c92731 100644--- a/Tests/LibWeb/Text/expected/display_list/animated-transform-visual-context-update.txt+++ b/Tests/LibWeb/Text/expected/display_list/animated-transform-visual-context-update.txt@@ -7,8 +7,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgroundAfter animation update:AccumulatedVisualContext Tree:@@ -19,6 +22,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/backdrop-filter-effect-node.txt b/Tests/LibWeb/Text/expected/display_list/backdrop-filter-effect-node.txtindex 7da95c2aae4..fc9d11d06c9 100644--- a/Tests/LibWeb/Text/expected/display_list/backdrop-filter-effect-node.txt+++ b/Tests/LibWeb/Text/expected/display_list/backdrop-filter-effect-node.txt@@ -12,8 +12,13 @@ AccumulatedVisualContext Tree:[e2 in s1] effects=[opacity=0.5] (BlockContainer<DIV>#plain)[e3 in s1] effects=[backdrop-filter=[region=[400,20 50x50] filter=[blur(2,2)]]] (BlockContainer<DIV>#empty)+Layers:+ [L0] base space=viewport+ e1 is not composited: it reads only its own layer+ e3 is not composited: it reads only its own layer+DisplayList:-BackdropFilterRegion@s2/c0/e1 rect=[20,20 100x100] owner=BlockContainer<DIV>#transformed phase=background-FillRect@s3/e2 rect=[200,20 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#plain phase=background-BackdropFilterRegion@s1/e3 rect=[400,20 50x50] owner=BlockContainer<DIV>#empty phase=background+L0 BackdropFilterRegion@s2/c0/e1 rect=[20,20 100x100] owner=BlockContainer<DIV>#transformed phase=background+L0 FillRect@s3/e2 rect=[200,20 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#plain phase=background+L0 BackdropFilterRegion@s1/e3 rect=[400,20 50x50] owner=BlockContainer<DIV>#empty phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/background-attachment-change-repaints.txt b/Tests/LibWeb/Text/expected/display_list/background-attachment-change-repaints.txtindex de9dd57699f..7e9a1b4ccfd 100644--- a/Tests/LibWeb/Text/expected/display_list/background-attachment-change-repaints.txt+++ b/Tests/LibWeb/Text/expected/display_list/background-attachment-change-repaints.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintLinearGradient@s1/e0 gradient_rect=[0,0 200x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 200x200]] owner=BlockContainer<DIV>#box phase=background+L0 PaintLinearGradient@s1/e0 gradient_rect=[0,0 200x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 200x200]] owner=BlockContainer<DIV>#box phase=backgroundAfter background-attachment change:AccumulatedVisualContext Tree:@@ -16,6 +19,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintLinearGradient@s0/e0 gradient_rect=[0,0 800x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 200x200] in s1] owner=BlockContainer<DIV>#box phase=background+L0 PaintLinearGradient@s0/e0 gradient_rect=[0,0 800x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 200x200] in s1] owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/background-attachment-fixed.txt b/Tests/LibWeb/Text/expected/display_list/background-attachment-fixed.txtindex 380c37fab85..c63ce33a8bd 100644--- a/Tests/LibWeb/Text/expected/display_list/background-attachment-fixed.txt+++ b/Tests/LibWeb/Text/expected/display_list/background-attachment-fixed.txt@@ -7,6 +7,9 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,613] is_viewport=true+Layers:+ [L0] base space=viewport+DisplayList:-PaintLinearGradient@s0/e0 gradient_rect=[0,0 800x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 800x1213] in s1] owner=BlockContainer<HTML> phase=background+L0 PaintLinearGradient@s0/e0 gradient_rect=[0,0 800x600] gradient_angle=180 color_stops=[rgb(0, 128, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[0,0 800x1213] in s1] owner=BlockContainer<HTML> phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/background-blend-mode-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/background-blend-mode-invalidation.txtindex d89c3286e8d..03447bf3f86 100644--- a/Tests/LibWeb/Text/expected/display_list/background-blend-mode-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/background-blend-mode-invalidation.txt@@ -6,10 +6,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-PaintLinearGradient@s1/e0 gradient_rect=[8,13 100x100] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,13 100x100]] owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 PaintLinearGradient@s1/e0 gradient_rect=[8,13 100x100] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,13 100x100]] owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter background-blend-mode change:AccumulatedVisualContext Tree:@@ -19,8 +22,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-PaintLinearGradient@s1/e0 gradient_rect=[8,13 100x100] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[8,13 100x100]] owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 PaintLinearGradient@s1/e0 gradient_rect=[8,13 100x100] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[8,13 100x100]] owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/background-blend-mode-isolated-group.txt b/Tests/LibWeb/Text/expected/display_list/background-blend-mode-isolated-group.txtindex 207e8d86d55..ee6fb72b9fe 100644--- a/Tests/LibWeb/Text/expected/display_list/background-blend-mode-isolated-group.txt+++ b/Tests/LibWeb/Text/expected/display_list/background-blend-mode-isolated-group.txt@@ -5,8 +5,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawIsolatedGroup@s1/e0 clip_rect=[8,8 100x50] owner=BlockContainer<DIV>#box phase=background- PaintLinearGradient@s1/e0 gradient_rect=[8,8 100x50] gradient_angle=180 color_stops=[rgb(0, 0, 255) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x50]] owner=BlockContainer<DIV>#box phase=background- PaintLinearGradient@s1/e0 gradient_rect=[8,8 100x50] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[8,8 100x50]] owner=BlockContainer<DIV>#box phase=background+L0 DrawIsolatedGroup@s1/e0 clip_rect=[8,8 100x50] owner=BlockContainer<DIV>#box phase=background+ PaintLinearGradient@s1/e0 gradient_rect=[8,8 100x50] gradient_angle=180 color_stops=[rgb(0, 0, 255) 0, rgb(0, 0, 255) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x50]] owner=BlockContainer<DIV>#box phase=background+ PaintLinearGradient@s1/e0 gradient_rect=[8,8 100x50] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[8,8 100x50]] owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/background-clip-text-color-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/background-clip-text-color-invalidation.txtindex f19532866ce..ad3278ac2c6 100644--- a/Tests/LibWeb/Text/expected/display_list/background-clip-text-color-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/background-clip-text-color-invalidation.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>#box.box phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>#box.box phase=foregroundAfter background-color change:AccumulatedVisualContext Tree:@@ -17,10 +20,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawIsolatedGroup@s1/e0 clip_rect=[8,13 100x50] owner=BlockContainer<DIV>#box.box phase=background- FillRect@s1/e0 rect=[8,13 100x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#box.box phase=background- Mask:- DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>#box.box phase=foreground+L0 DrawIsolatedGroup@s1/e0 clip_rect=[8,13 100x50] owner=BlockContainer<DIV>#box.box phase=background+ FillRect@s1/e0 rect=[8,13 100x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#box.box phase=background+ Mask:+ DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,13 71x30] glyph_bounding_rect=[8,14 83x27] translation=[8,37] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/block-in-inline-no-border-for-phantom-inline-box.txt b/Tests/LibWeb/Text/expected/display_list/block-in-inline-no-border-for-phantom-inline-box.txtindex 3759ff50548..1206abff141 100644--- a/Tests/LibWeb/Text/expected/display_list/block-in-inline-no-border-for-phantom-inline-box.txt+++ b/Tests/LibWeb/Text/expected/display_list/block-in-inline-no-border-for-phantom-inline-box.txt@@ -5,10 +5,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[0,3 8x14] top_width=2 bottom_width=2 left_width=2 color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[2,5 6x10] glyph_bounding_rect=[2,5 8x9] translation=[2,13] color=rgb(0, 0, 0) text="a" owner=BlockContainer<DIV> phase=text-fragment-FillRoundedRectRing@s1/e0 rect=[0,63 8x14] top_width=2 right_width=2 bottom_width=2 color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[0,65 6x10] glyph_bounding_rect=[0,65 8x9] translation=[0,73] color=rgb(0, 0, 0) text="b" owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[100,55 7x10] glyph_bounding_rect=[100,55 8x9] translation=[100,63] color=rgb(0, 0, 0) text="x" owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[0,3 8x14] top_width=2 bottom_width=2 left_width=2 color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=inline-piece+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[2,5 6x10] glyph_bounding_rect=[2,5 8x9] translation=[2,13] color=rgb(0, 0, 0) text="a" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRoundedRectRing@s1/e0 rect=[0,63 8x14] top_width=2 right_width=2 bottom_width=2 color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=inline-piece+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[0,65 6x10] glyph_bounding_rect=[0,65 8x9] translation=[0,73] color=rgb(0, 0, 0) text="b" owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[100,55 7x10] glyph_bounding_rect=[100,55 8x9] translation=[100,63] color=rgb(0, 0, 0) text="x" owner=BlockContainer<DIV> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/blocking-wheel-listener-cache-replay.txt b/Tests/LibWeb/Text/expected/display_list/blocking-wheel-listener-cache-replay.txtindex 67824925773..7ab01571622 100644--- a/Tests/LibWeb/Text/expected/display_list/blocking-wheel-listener-cache-replay.txt+++ b/Tests/LibWeb/Text/expected/display_list/blocking-wheel-listener-cache-replay.txt@@ -1 +1 @@-CompositorBlockingWheelEventRegion@s1/e0 rect=[8,8 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadata+L0 CompositorBlockingWheelEventRegion@s1/e0 rect=[8,8 100x100] owner=BlockContainer<DIV>#target phase=scroll-metadatadiff --git a/Tests/LibWeb/Text/expected/display_list/border-inner-corner-right-angle-all-edges.txt b/Tests/LibWeb/Text/expected/display_list/border-inner-corner-right-angle-all-edges.txtindex 4add807bcee..ec5b5928e3e 100644--- a/Tests/LibWeb/Text/expected/display_list/border-inner-corner-right-angle-all-edges.txt+++ b/Tests/LibWeb/Text/expected/display_list/border-inner-corner-right-angle-all-edges.txt@@ -5,13 +5,16 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s1/e0 path_bounding_rect=[166,12.651531 20x110.696945] path_data=[curved path: 20 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border-FillPath@s1/e0 path_bounding_rect=[11.232849,113 168.56511x15] path_data=[curved path: 52 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border-FillPath@s1/e0 path_bounding_rect=[7.999998,14.061594 8.000002x107.876816] path_data=[curved path: 12 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border-FillPath@s1/e0 path_bounding_rect=[11.232849,8 168.56511x15] path_data=[curved path: 52 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border-FillPath@s1/e0 path_bounding_rect=[173,134.20204 15x117.59592] path_data=[curved path: 36 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border-FillPath@s1/e0 path_bounding_rect=[12.651531,238 170.69693x20] path_data=[curved path: 20 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border-FillPath@s1/e0 path_bounding_rect=[8,134.20204 15x117.59592] path_data=[curved path: 36 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border-FillPath@s1/e0 path_bounding_rect=[12.651531,128 170.69693x20] path_data=[curved path: 20 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[166,12.651531 20x110.696945] path_data=[curved path: 20 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[11.232849,113 168.56511x15] path_data=[curved path: 52 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[7.999998,14.061594 8.000002x107.876816] path_data=[curved path: 12 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[11.232849,8 168.56511x15] path_data=[curved path: 52 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.wide-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[173,134.20204 15x117.59592] path_data=[curved path: 36 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[12.651531,238 170.69693x20] path_data=[curved path: 20 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,134.20204 15x117.59592] path_data=[curved path: 36 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=border+L0 FillPath@s1/e0 path_bounding_rect=[12.651531,128 170.69693x20] path_data=[curved path: 20 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.tall-corners phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/border-radius-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/border-radius-invalidation.txtindex 2da79c9e286..f438b4233bd 100644--- a/Tests/LibWeb/Text/expected/display_list/border-radius-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/border-radius-invalidation.txt@@ -8,9 +8,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter border-radius change:AccumulatedVisualContext Tree:@@ -22,7 +25,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) corner_radii=[20x20,20x20,20x20,20x20] owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) corner_radii=[20x20,20x20,20x20,20x20] owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/button-with-text-decoration.txt b/Tests/LibWeb/Text/expected/display_list/button-with-text-decoration.txtindex 61e9d1aa208..85c71bffddc 100644--- a/Tests/LibWeb/Text/expected/display_list/button-with-text-decoration.txt+++ b/Tests/LibWeb/Text/expected/display_list/button-with-text-decoration.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,8 98x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 98x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=11 rect=[17,11 80x14] glyph_bounding_rect=[17,12 83x12] translation=[17,22] color=rgb(0, 0, 0) text="foo the bar" owner=BlockContainer(anonymous) phase=foreground-FillRect@s1/e0 rect=[17,24 80x1] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,8 98x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 98x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=11 rect=[17,11 80x14] glyph_bounding_rect=[17,12 83x12] translation=[17,22] color=rgb(0, 0, 0) text="foo the bar" owner=BlockContainer(anonymous) phase=foreground+L0 FillRect@s1/e0 rect=[17,24 80x1] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/canvas-compositor-surface.txt b/Tests/LibWeb/Text/expected/display_list/canvas-compositor-surface.txtindex 7e983319dda..ad5fbe1aff1 100644--- a/Tests/LibWeb/Text/expected/display_list/canvas-compositor-surface.txt+++ b/Tests/LibWeb/Text/expected/display_list/canvas-compositor-surface.txt@@ -6,8 +6,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[5,5 38x38] shown by the window server: clip=[0,0 800x600]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[5,5 38x38] shown by the window server: clip=[0,0 800x600]DisplayList:L1 DrawCanvas@s1/e0 dst_rect=[8,8 32x32] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/canvas-drawn-on-after-layout-reached-it.txt b/Tests/LibWeb/Text/expected/display_list/canvas-drawn-on-after-layout-reached-it.txtindex 30429717baf..7ecb829e9e5 100644--- a/Tests/LibWeb/Text/expected/display_list/canvas-drawn-on-after-layout-reached-it.txt+++ b/Tests/LibWeb/Text/expected/display_list/canvas-drawn-on-after-layout-reached-it.txt@@ -6,8 +6,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[5,5 206x126] shown by the window server: clip=[0,0 800x600]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[5,5 206x126] shown by the window server: clip=[0,0 800x600]DisplayList:L1 DrawCanvas@s1/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/clip-auto-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/clip-auto-invalidation.txtindex 4ab28a36eaf..c6b06f572bd 100644--- a/Tests/LibWeb/Text/expected/display_list/clip-auto-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/clip-auto-invalidation.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,13 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/e0 rect=[8,13 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgroundAfter clip change:AccumulatedVisualContext Tree:@@ -19,6 +22,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/clip-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/clip-invalidation.txtindex 7a7201f80ea..688da73f92a 100644--- a/Tests/LibWeb/Text/expected/display_list/clip-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/clip-invalidation.txt@@ -8,9 +8,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter clip change:AccumulatedVisualContext Tree:@@ -22,7 +25,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,13 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,13 30x16] glyph_bounding_rect=[8,14 33x15] translation=[8,26] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/clip-path-empty-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/clip-path-empty-invalidation.txtindex 50f2a2d67c7..be43ab231f0 100644--- a/Tests/LibWeb/Text/expected/display_list/clip-path-empty-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/clip-path-empty-invalidation.txt@@ -8,8 +8,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgroundAfter clip-path change:AccumulatedVisualContext Tree:@@ -21,6 +24,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/clip-path-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/clip-path-invalidation.txtindex e7456aa5b43..716a51534a0 100644--- a/Tests/LibWeb/Text/expected/display_list/clip-path-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/clip-path-invalidation.txt@@ -8,9 +8,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter clip-path change:AccumulatedVisualContext Tree:@@ -22,7 +25,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/clip-positioned-descendants.txt b/Tests/LibWeb/Text/expected/display_list/clip-positioned-descendants.txtindex 1af71a1e0c1..a8d77984af4 100644--- a/Tests/LibWeb/Text/expected/display_list/clip-positioned-descendants.txt+++ b/Tests/LibWeb/Text/expected/display_list/clip-positioned-descendants.txt@@ -8,7 +8,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[0,0 200x200] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.abspos phase=background-FillRect@s0/c1/e0 rect=[220,0 200x200] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.fixed phase=background+L0 FillRect@s1/c0/e0 rect=[0,0 200x200] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.abspos phase=background+L0 FillRect@s0/c1/e0 rect=[220,0 200x200] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.fixed phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/color-and-file-input-appearance.txt b/Tests/LibWeb/Text/expected/display_list/color-and-file-input-appearance.txtindex fc1fd52297c..d72869d329d 100644--- a/Tests/LibWeb/Text/expected/display_list/color-and-file-input-appearance.txt+++ b/Tests/LibWeb/Text/expected/display_list/color-and-file-input-appearance.txt@@ -8,14 +8,17 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,8 50x27] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<INPUT> phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 50x27] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<INPUT> phase=border-FillRect@s1/c0/e0 rect=[13,14 40x15] color=rgb(68, 136, 255) owner=BlockContainer<DIV> phase=background-FillRoundedRectRing@s1/c0/e0 rect=[13,14 40x15] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(119, 119, 119) owner=BlockContainer<DIV> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[58,16 8x16] glyph_bounding_rect=[58,16 13x15] translation=[58,29] color=rgb(0, 0, 0) text=" " owner=BlockContainer(anonymous) phase=text-fragment-FillRectWithRoundedCorners@s1/c1/e0 rect=[66,15 97x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background-FillRoundedRectRing@s1/c1/e0 rect=[66,15 97x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/c1/e0 font_id=font2 glyphs=14 rect=[75,18 79x14] glyph_bounding_rect=[75,19 86x12] translation=[75,29] color=rgb(0, 0, 0) text="Select file..." owner=BlockContainer(anonymous) phase=foreground-DrawGlyphRun@s1/c1/e0 font_id=font2 glyphs=17 rect=[166,18 108x14] glyph_bounding_rect=[167,19 114x12] translation=[166.65625,29] color=rgb(0, 0, 0) text="No file selected." owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,8 50x27] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<INPUT> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 50x27] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<INPUT> phase=border+L0 FillRect@s1/c0/e0 rect=[13,14 40x15] color=rgb(68, 136, 255) owner=BlockContainer<DIV> phase=background+L0 FillRoundedRectRing@s1/c0/e0 rect=[13,14 40x15] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(119, 119, 119) owner=BlockContainer<DIV> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=1 rect=[58,16 8x16] glyph_bounding_rect=[58,16 13x15] translation=[58,29] color=rgb(0, 0, 0) text=" " owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRectWithRoundedCorners@s1/c1/e0 rect=[66,15 97x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background+L0 FillRoundedRectRing@s1/c1/e0 rect=[66,15 97x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/c1/e0 font_id=font2 glyphs=14 rect=[75,18 79x14] glyph_bounding_rect=[75,19 86x12] translation=[75,29] color=rgb(0, 0, 0) text="Select file..." owner=BlockContainer(anonymous) phase=foreground+L0 DrawGlyphRun@s1/c1/e0 font_id=font2 glyphs=17 rect=[166,18 108x14] glyph_bounding_rect=[167,19 114x12] translation=[166.65625,29] color=rgb(0, 0, 0) text="No file selected." owner=BlockContainer(anonymous) phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-3d-sorting-context.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-3d-sorting-context.txtindex 105cd4eaa1e..5088d659fe2 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-3d-sorting-context.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-3d-sorting-context.txt@@ -8,9 +8,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]-Layers: none (3D sorting context)+Layers:+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[5,5 206x126] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1DisplayList:-DrawCanvas@s1/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-FillRect@s4/e0 rect=[8,131 100x100] color=rgb(255, 165, 0) owner=BlockContainer<DIV>#card phase=background+L1 DrawCanvas@s1/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L2 FillRect@s4/e0 rect=[8,131 100x100] color=rgb(255, 165, 0) owner=BlockContainer<DIV>#card phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.txtnew file mode 100644index 00000000000..021f860367e--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.txt@@ -0,0 +1,16 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ effects:+ [e0 in s0] effects=[]+ [e1 in s1] effects=[filter=[crop([-70.4,-2 940.80005x120.00001] input=[offset(40,0 input=[crop([-70.4,-2 940.80005x120.00001])])])]] (BlockContainer<DIV>)+ [e2 in s1] effects=[backdrop-filter=[region=[8,8 100x100] filter=[drop-shadow(4,4,0,rgb(0, 0, 0))]]] (BlockContainer<DIV>)++Layers:+ [L0] single layer replaying the whole list: filter that moves what it filters is composited++DisplayList:+L0 FillRect@s1/e1 rect=[8,8 784x100] color=rgba(0, 0, 0, 0) owner=BlockContainer<DIV> phase=preamble+L0 BackdropFilterRegion@s1/e2 rect=[8,8 100x100] owner=BlockContainer<DIV> phase=background+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-opacity-group-over-canvas.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-opacity-group-over-canvas.txtindex 3030e264f66..0922f1b020c 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-opacity-group-over-canvas.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-in-opacity-group-over-canvas.txt@@ -8,9 +8,10 @@ AccumulatedVisualContext Tree:[e2 in s1] effects=[backdrop-filter=[region=[60,60 100x40] filter=[blur(4,4)]]] (BlockContainer<DIV>#frosted)Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 206x126] shown by the window server: clip=[0,0 800x600]- [L2] painted rect=[57,57 106x46]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1+ e2 is not composited: it reads only its own layerDisplayList:L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-canvas.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-canvas.txtindex cfd8dfc6fb4..5a8a659fe04 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-canvas.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-canvas.txt@@ -6,9 +6,13 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[backdrop-filter=[region=[60,60 100x40] filter=[blur(4,4)]]] (BlockContainer<DIV>#frosted)-Layers: none (canvas under a backdrop filter that reads the root group)+Layers:+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] replayed: under a layer the frame holds+ [L3] painted space=viewport inside e1+ composited e1 space=viewport reads=[33,33 154x94]: it reads what its own layer does not holdDisplayList:-DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-BackdropFilterRegion@s1/e1 rect=[60,60 100x40] owner=BlockContainer<DIV>#frosted phase=background+L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L3 BackdropFilterRegion@s1/e1 rect=[60,60 100x40] owner=BlockContainer<DIV>#frosted phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.txtindex 7875cc51539..845167dd19c 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.txt@@ -4,12 +4,16 @@ AccumulatedVisualContext Tree:[s1] scroll (Viewport<#document>)effects:[e0 in s0] effects=[]- [e1 in s1] effects=[backdrop-filter=[region=[300,120 60x40] filter=[Grayscale(1)]]] (BlockContainer<DIV>#frosted)+ [e1 in s1] effects=[backdrop-filter=[region=[540,120 60x40] filter=[Grayscale(1)]]] (BlockContainer<DIV>#frosted)-Layers: none (canvas under a backdrop filter that reads the root group)+Layers:+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1+ e1 is not composited: it reads only its own layerDisplayList:-DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-FillRect@s1/e0 rect=[180,100 200x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-canvas phase=background-BackdropFilterRegion@s1/e1 rect=[300,120 60x40] owner=BlockContainer<DIV>#frosted phase=background+L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0,L2 FillRect@s1/e0 rect=[180,100 440x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-canvas phase=background+L0 BackdropFilterRegion@s1/e1 rect=[540,120 60x40] owner=BlockContainer<DIV>#frosted phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filters-beside-canvases.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filters-beside-canvases.txtindex cafa91f875c..709a2608055 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filters-beside-canvases.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-backdrop-filters-beside-canvases.txt@@ -8,12 +8,17 @@ AccumulatedVisualContext Tree:[e2 in s1] effects=[backdrop-filter=[region=[610,60 100x40] filter=[blur(8,8)]]] (BlockContainer<DIV>#blur-reaching-into-right.frosted)Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L3] canvas #0 space=viewport region=[397,17 206x126] replayed: under a layer the frame holds+ [L5] painted space=viewport inside e1+ [L7] painted space=viewport inside e2+ composited e1 space=viewport reads=[237,57 106x46]: it reads what its own layer does not hold+ composited e2 space=viewport reads=[559,9 202x142]: it reads what its own layer does not holdDisplayList:L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#left phase=foreground-L0 DrawCanvas@s1/e0 dst_rect=[400,20 200x120] canvas_id=canvas2 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#right phase=foreground-L0 BackdropFilterRegion@s1/e1 rect=[240,60 100x40] owner=BlockContainer<DIV>#grayscale-beside-left.frosted phase=background-L0 BackdropFilterRegion@s1/e2 rect=[610,60 100x40] owner=BlockContainer<DIV>#blur-reaching-into-right.frosted phase=background+L3 DrawCanvas@s1/e0 dst_rect=[400,20 200x120] canvas_id=canvas2 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#right phase=foreground+L5 BackdropFilterRegion@s1/e1 rect=[240,60 100x40] owner=BlockContainer<DIV>#grayscale-beside-left.frosted phase=background+L7 BackdropFilterRegion@s1/e2 rect=[610,60 100x40] owner=BlockContainer<DIV>#blur-reaching-into-right.frosted phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-box-scaled-up-from-nothing.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-box-scaled-up-from-nothing.txtnew file mode 100644index 00000000000..a9653642f48--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-box-scaled-up-from-nothing.txt@@ -0,0 +1 @@+The compositor drew 30 frames of the animationdiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-filter-that-moves-it.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-filter-that-moves-it.txtnew file mode 100644index 00000000000..ed3a85d555c--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-filter-that-moves-it.txt@@ -0,0 +1,22 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ effects:+ [e0 in s0] effects=[]+ [e1 in s1] effects=[filter=[crop([-70.4,-4.3 940.80005x147.6] input=[offset(40,0 input=[crop([-70.4,-4.3 940.80005x147.6])])])]] (BlockContainer<DIV>)+ [e2 in s1] effects=[filter=[drop-shadow(10,10,0,rgb(0, 0, 0))]] (BlockContainer<DIV>)++Layers:+ [L0] base space=viewport+ [L2] canvas #0 space=viewport inside e2 region=[5,128 216x136] replayed: inside an effect the compositor composites+ composited e2 space=viewport: it holds a canvas with a layer of its own+ no layer for canvas: inside a filter that moves what it filters++DisplayList:+L0 FillRect@s1/e1 rect=[8,8 784x123] color=rgba(0, 0, 0, 0) owner=BlockContainer<DIV> phase=preamble+L0 DrawCanvas@s1/e1 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#moved phase=foreground+L0 DrawGlyphRun@s1/e1 font_id=font1 glyphs=1 rect=[208,115 8x16] glyph_bounding_rect=[208,116 13x15] translation=[208,128] color=rgb(0, 0, 0) text=" " owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e1 font_id=font1 glyphs=20 rect=[66,115 172x16] glyph_bounding_rect=[66,116 176x15] translation=[66,128] color=rgb(0, 0, 0) text="text over the canvas" owner=InlineNode<SPAN> phase=text-fragment+L2 DrawCanvas@s1/e2 dst_rect=[8,131 200x120] canvas_id=canvas2 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#shadowed phase=foreground+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-nested-scroller.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-nested-scroller.txtnew file mode 100644index 00000000000..7043d7610eb--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-nested-scroller.txt@@ -0,0 +1,30 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ [s2] scroll (BlockContainer<DIV>#scroller)+ clips:+ [c0 in s1] clip=[20,300 300x200] (BlockContainer<DIV>#scroller)+ effects:+ [e0 in s0] effects=[]++ScrollNodes:+ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1413] is_viewport=true+ScrollNode scroll_node_index=s2 parent_scroll_node_index=s1 scrollport_rect=[20,300 300x200] min_scroll_offset=[0,0] max_scroll_offset=[0,1200] is_viewport=false++Layers:+ [L0] base space=viewport+ [L3] canvas #0 space=scroller@s2 in document region=[20,697 203x126] composited within [20,300 300x200] of document shown by the window server: clip=[20,300 300x200]+ [L4] painted space=scroller@s2 in document above L3 composited within [20,300 300x200] of document++DisplayList:+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s1 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,0 800x2013] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s1 rect=[0,13 800x2000] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[20,300 300x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[20,700 300x1000] owner=BlockContainer<DIV>#content phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[20,700 200x120] owner=CanvasBox<CANVAS>#canvas phase=scroll-metadata+L3 DrawCanvas@s2/c0/e0 dst_rect=[20,700 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[30,720 100x40] owner=BlockContainer<DIV>#over-canvas phase=scroll-metadata+L4 FillRect@s2/c0/e0 rect=[30,720 100x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-canvas phase=background+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-opacity-group.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-opacity-group.txtindex d9aa4a0ec4d..1a404087f8d 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-opacity-group.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-opacity-group.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[opacity=0.5] (BlockContainer<DIV>)-Layers: none (canvas inside a group effect)+Layers:+ [L0] base space=viewport+ [L2] canvas #0 space=viewport inside e1 region=[5,5 206x126] replayed: inside an effect the compositor composites+ composited e1 space=viewport: it holds a canvas with a layer of its ownDisplayList:-DrawCanvas@s1/e1 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L2 DrawCanvas@s1/e1 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-scrolling-document.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-scrolling-document.txtnew file mode 100644index 00000000000..93deb2bcef6--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-scrolling-document.txt@@ -0,0 +1,23 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ effects:+ [e0 in s0] effects=[]++ScrollNodes:+ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1413] is_viewport=true++Layers:+ [L0] base space=viewport+ [L2] canvas #0 space=document region=[17,897 206x126] shown by the window server: clip=[0,0 800x600]+ [L3] painted space=document above L2+ [L4] painted space=viewport above band 0 of document+ [L5] painted space=document band=1++DisplayList:+L2 DrawCanvas@s1/e0 dst_rect=[20,900 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L3 FillRect@s1/e0 rect=[100,940 100x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-canvas phase=background+L4 FillRect@s0/e0 rect=[0,0 800x40] color=rgb(0, 0, 128) owner=BlockContainer<DIV>#fixed-header phase=background+L5 FillRect@s1/e0 rect=[300,1500 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#after-header phase=background+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-outside-viewport.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-outside-viewport.txtindex 2d694701fb3..874b5479095 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-outside-viewport.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-outside-viewport.txt@@ -5,8 +5,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]-Layers: none (canvas draws nothing visible)+Layers:+ [L0] base space=viewport+ no layer for canvas: draws nothing visibleDisplayList:-DrawCanvas@s1/e0 dst_rect=[-1000,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0 DrawCanvas@s1/e0 dst_rect=[-1000,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txtindex 23c41619a52..a940d1efa41 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt@@ -8,8 +8,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[67,27 106x106] replayed: clipped by a path+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[67,27 106x106] replayed: clipped by a pathDisplayList:L1 DrawCanvas@s1/c0/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-perspective-transform.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-perspective-transform.txtindex 5af8a9e5cc4..f8dd576062c 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-perspective-transform.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-perspective-transform.txt@@ -6,8 +6,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]-Layers: none (canvas under a transform that is not 2D affine)+Layers:+ [L0] base space=viewport+ no layer for canvas: under a transform that is not 2D affineDisplayList:-DrawCanvas@s2/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0 DrawCanvas@s2/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-translucent-box.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-translucent-box.txtindex 70f38d4d408..db616e0f010 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-translucent-box.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-translucent-box.txt@@ -6,14 +6,14 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 206x126] shown by the window server: clip=[20,20 200x120] rounded=[20,20 200x120] radius=12- [L2] painted rect=[57,57 106x46]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[20,20 200x120] rounded=[20,20 200x120] radius=12+ [L2] painted space=viewport above L1DisplayList:L0 DrawRepeatedTile@s1/e0 dst_rect=[0,0 800x13] clip_rect=[0,0 800x600] tile_size=[800x13] tile_step=[800x13] scaling_mode=Bilinear repeat={x=true y=true} inline_clips=[clip=[0,0 800x600]] owner=BlockContainer<HTML> phase=backgroundPaintLinearGradient@s1/e0 gradient_rect=[0,0 800x13] gradient_angle=90 color_stops=[rgb(238, 238, 255) 0, rgb(255, 238, 238) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=backgroundL1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear inline_clips=[clip=[20,20 200x120] radii=(12,12,12,12)] owner=CanvasBox<CANVAS>#canvas phase=foreground-L2 FillRect@s1/e0 rect=[60,60 100x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over phase=background-L0 FillRect@s1/e0 rect=[300,300 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#elsewhere phase=background+L0,L2 FillRect@s1/e0 rect=[60,60 100x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over phase=background+L0,L2 FillRect@s1/e0 rect=[600,300 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#elsewhere phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-fixed-header-over-scrolling-text.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-fixed-header-over-scrolling-text.txtnew file mode 100644index 00000000000..57907011444--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-fixed-header-over-scrolling-text.txt@@ -0,0 +1,18 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ effects:+ [e0 in s0] effects=[]++ScrollNodes:+ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,1420] is_viewport=true++Layers:+ [L1] base space=document+ [L2] painted space=viewport above band 0 of document++DisplayList:+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=20 rect=[0,30 400x20] glyph_bounding_rect=[0,30 400x20] translation=[0,46] color=rgb(0, 0, 0) text="Text of the document" owner=BlockContainer<P> phase=foreground+L2 FillRect@s0/e0 rect=[0,0 800x40] color=rgb(0, 0, 128) owner=BlockContainer<DIV>#fixed-header phase=background+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-and-canvas.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-and-canvas.txtindex c6f87a53246..bc3dda4c193 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-and-canvas.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-and-canvas.txt@@ -6,10 +6,11 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] composited context rect=[17,17 206x126]- [L2] canvas rect=[297,17 206x126] shown by the window server: clip=[0,0 800x600]- [L3] painted rect=[97,57 306x46]+ [L0] base space=viewport+ [L1] composited context #0 space=viewport region=[17,17 206x126]+ [L2] painted space=viewport above L1+ [L3] canvas #0 space=viewport region=[517,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L4] painted space=viewport above L3DisplayList:L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata@@ -17,8 +18,8 @@ L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800xL0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[20,20 200x120] owner=NavigableContainerViewport<IFRAME>#frame phase=scroll-metadataL1 DrawCompositedContext@s1/e0 dst_rect=[20,20 200x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[20,20 200x120]] owner=NavigableContainerViewport<IFRAME>#frame phase=foregroundL0 CompositorNestedContextWheelRegion@s1/e0 rect=[20,20 200x120] child_context_id=context1 owner=NavigableContainerViewport<IFRAME>#frame phase=foreground-L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[300,20 200x120] owner=CanvasBox<CANVAS>#canvas phase=scroll-metadata-L2 DrawCanvas@s1/e0 dst_rect=[300,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[100,60 300x40] owner=BlockContainer<DIV>#over-both phase=scroll-metadata-L3 FillRect@s1/e0 rect=[100,60 300x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-both phase=background+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[520,20 200x120] owner=CanvasBox<CANVAS>#canvas phase=scroll-metadata+L3 DrawCanvas@s1/e0 dst_rect=[520,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[100,60 600x40] owner=BlockContainer<DIV>#over-both phase=scroll-metadata+L2,L4 FillRect@s1/e0 rect=[100,60 600x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-both phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-in-opacity-group.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-in-opacity-group.txtindex 96c93300c9f..19763462c6c 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-in-opacity-group.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-in-opacity-group.txt@@ -6,14 +6,17 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[opacity=0.5] (BlockContainer<DIV>#group)-Layers: none (composited context inside a group effect)+Layers:+ [L0] base space=viewport+ [L2] composited context #0 space=viewport inside e1 region=[0,0 203x123]+ composited e1 space=viewport: it holds a composited context with a layer of its ownDisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x136] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x123] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e1 target_scroll_node_index=s0 rect=[0,0 800x123] owner=BlockContainer<DIV>#group phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e1 target_scroll_node_index=s0 rect=[0,0 200x120] owner=NavigableContainerViewport<IFRAME>#frame phase=scroll-metadata-DrawCompositedContext@s1/e1 dst_rect=[0,0 200x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[0,0 200x120]] owner=NavigableContainerViewport<IFRAME>#frame phase=foreground-CompositorNestedContextWheelRegion@s1/e1 rect=[0,0 200x120] child_context_id=context1 owner=NavigableContainerViewport<IFRAME>#frame phase=foreground+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x136] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x123] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e1 target_scroll_node_index=s0 rect=[0,0 800x123] owner=BlockContainer<DIV>#group phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e1 target_scroll_node_index=s0 rect=[0,0 200x120] owner=NavigableContainerViewport<IFRAME>#frame phase=scroll-metadata+L2 DrawCompositedContext@s1/e1 dst_rect=[0,0 200x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[0,0 200x120]] owner=NavigableContainerViewport<IFRAME>#frame phase=foreground+L0 CompositorNestedContextWheelRegion@s1/e1 rect=[0,0 200x120] child_context_id=context1 owner=NavigableContainerViewport<IFRAME>#frame phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-under-content.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-under-content.txtindex d8514366d0a..22b9aa42c7b 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-under-content.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-iframe-under-content.txt@@ -6,9 +6,9 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] composited context rect=[17,17 206x126]- [L2] painted rect=[97,57 206x46]+ [L0] base space=viewport+ [L1] composited context #0 space=viewport region=[17,17 206x126]+ [L2] painted space=viewport above L1DisplayList:L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata@@ -17,7 +17,7 @@ L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[20,20 20L1 DrawCompositedContext@s1/e0 dst_rect=[20,20 200x120] child_context_id=context1 scaling_mode=NearestNeighbor spatial_node_index=s1 snap_origin_if_untransformed=true inline_clips=[clip=[20,20 200x120]] owner=NavigableContainerViewport<IFRAME>#frame phase=foregroundL0 CompositorNestedContextWheelRegion@s1/e0 rect=[20,20 200x120] child_context_id=context1 owner=NavigableContainerViewport<IFRAME>#frame phase=foregroundL0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[100,60 200x40] owner=BlockContainer<DIV>#over-iframe phase=scroll-metadata-L2 FillRect@s1/e0 rect=[100,60 200x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-iframe phase=background-L2 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[400,300 50x20] owner=BlockContainer<DIV>#elsewhere phase=scroll-metadata-L0 FillRect@s1/e0 rect=[400,300 50x20] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#elsewhere phase=background+L0,L2 FillRect@s1/e0 rect=[100,60 200x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-iframe phase=background+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[600,300 50x20] owner=BlockContainer<DIV>#elsewhere phase=scroll-metadata+L0,L2 FillRect@s1/e0 rect=[600,300 50x20] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#elsewhere phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-root-blend-mode.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-root-blend-mode.txtindex ff2bc05c1c8..ab37389df81 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-root-blend-mode.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-root-blend-mode.txt@@ -6,9 +6,13 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[blend_mode=Multiply] (BlockContainer<DIV>)-Layers: none (blend mode reads the root group)+Layers:+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[5,5 206x126] replayed: under a layer the frame holds+ [L3] painted space=viewport inside e1+ composited e1 space=viewport reads=[5,128 56x56]: it reads what its own layer does not holdDisplayList:-DrawCanvas@s1/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-FillRect@s1/e1 rect=[8,131 50x50] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=background+L1 DrawCanvas@s1/e0 dst_rect=[8,8 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L3 FillRect@s1/e1 rect=[8,131 50x50] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-rotated-video.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-rotated-video.txtindex 5123714051a..b8bdc336524 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-rotated-video.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-rotated-video.txt@@ -7,8 +7,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] video rect=[167,27 186x326] shown by the window server: transform=[0,1,-1,0,450,-70] clip=[0,0 800x600]+ [L0] base space=viewport+ [L1] video #0 space=viewport region=[167,27 186x326] shown by the window server: transform=[0,1,-1,0,450,-70] clip=[0,0 800x600]DisplayList:L1 DrawVideoFrame@s2/e0 dst_rect=[100,100 320x180] video_sink_handle=video1 scaling_mode=BilinearMipmap inline_clips=[clip=[100,100 320x180]] owner=VideoBox<VIDEO>#video phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-rounded-canvas-in-rounded-scroller.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-rounded-canvas-in-rounded-scroller.txtindex 87d41e13606..4bae4487afe 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-rounded-canvas-in-rounded-scroller.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-rounded-canvas-in-rounded-scroller.txt@@ -12,9 +12,9 @@ ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[20,20 180x100] min_scroll_offset=[0,0] max_scroll_offset=[20,320] is_viewport=falseLayers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 186x106] replayed: more than one rounded clip- [L2] painted rect=[17,17 186x106]+ [L0] base space=viewport+ [L2] canvas #0 space=scroller@s2 in viewport region=[20,20 200x123] composited within [20,20 180x100] radii=(20,20,20,20) of viewport replayed: more than one rounded clip+ [L4] painted space=viewport above band 0 of scroller@s2 in viewportDisplayList:L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata@@ -22,9 +22,9 @@ L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800xL0 CompositorWheelHitTestTargetWithCornerRadii@s1/e0 target_scroll_node_index=s2 rect=[20,20 180x100] corner_radii=[20x20,20x20,20x20,20x20] owner=BlockContainer<DIV>#scroller phase=scroll-metadataL0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[20,140 180x300] owner=BlockContainer<DIV>#spacer phase=scroll-metadataL0 CompositorWheelHitTestTargetWithCornerRadii@s2/c0/e0 target_scroll_node_index=s2 rect=[20,20 200x120] corner_radii=[8x8,8x8,8x8,8x8] owner=CanvasBox<CANVAS>#canvas phase=scroll-metadata-L1 DrawCanvas@s2/c0/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear inline_clips=[clip=[20,20 200x120] radii=(8,8,8,8)] owner=CanvasBox<CANVAS>#canvas phase=foreground+L2 DrawCanvas@s2/c0/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear inline_clips=[clip=[20,20 200x120] radii=(8,8,8,8)] owner=CanvasBox<CANVAS>#canvas phase=foregroundL0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[191,22 7x24] track_rect=[191,20 9x100] expanded_gutter_rect=[185,20 15x100] expanded_thumb_rect=[187,22 11x24] scroll_size=0.225 expanded_scroll_size=0.225 max_scroll_offset=320 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-L2 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,22 7x24] track_rect=[191,20 9x100] expanded_gutter_rect=[185,20 15x100] scroll_size=0.225 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L4 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[191,22 7x24] track_rect=[191,20 9x100] expanded_gutter_rect=[185,20 15x100] scroll_size=0.225 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlayL0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[22,111 145x7] track_rect=[20,111 165x9] expanded_gutter_rect=[20,105 165x15] expanded_thumb_rect=[22,107 145x11] scroll_size=0.80546875 expanded_scroll_size=0.80546875 max_scroll_offset=20 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay-L2 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[22,111 145x7] track_rect=[20,111 165x9] expanded_gutter_rect=[20,105 165x15] scroll_size=0.80546875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlay+L4 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[22,111 145x7] track_rect=[20,111 165x9] expanded_gutter_rect=[20,105 165x15] scroll_size=0.80546875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.txtnew file mode 100644index 00000000000..81a67e5a1d0--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.txt@@ -0,0 +1,74 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ [s2] scroll (BlockContainer<DIV>.clipped)+ [s3] scroll (BlockContainer<DIV>.clipped)+ [s4] scroll (BlockContainer<DIV>.clipped)+ [s5] scroll (BlockContainer<DIV>.clipped)+ [s6] scroll (BlockContainer<DIV>.clipped)+ [s7] scroll (BlockContainer<DIV>.clipped)+ [s8] scroll (BlockContainer<DIV>.clipped)+ [s9] scroll (BlockContainer<DIV>.clipped)+ [s10] scroll (BlockContainer<DIV>#clipping-wrapper)+ [s11] scroll (BlockContainer<DIV>#scroller)+ clips:+ [c0 in s1] clip=[0,0 20x20] (BlockContainer<DIV>.clipped)+ [c1 in s1] clip=[0,20 20x20] (BlockContainer<DIV>.clipped)+ [c2 in s1] clip=[0,40 20x20] (BlockContainer<DIV>.clipped)+ [c3 in s1] clip=[0,60 20x20] (BlockContainer<DIV>.clipped)+ [c4 in s1] clip=[0,80 20x20] (BlockContainer<DIV>.clipped)+ [c5 in s1] clip=[0,100 20x20] (BlockContainer<DIV>.clipped)+ [c6 in s1] clip=[0,120 20x20] (BlockContainer<DIV>.clipped)+ [c7 in s1] clip=[0,140 20x20] (BlockContainer<DIV>.clipped)+ [c8 in s1] clip=[0,160 400x300] (BlockContainer<DIV>#clipping-wrapper)+ [c9 in s10] clip=[0,170 300x200] (BlockContainer<DIV>#scroller)+ effects:+ [e0 in s0] effects=[]++ScrollNodes:+ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[0,0 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[0,20 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s4 parent_scroll_node_index=s0 scrollport_rect=[0,40 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s5 parent_scroll_node_index=s0 scrollport_rect=[0,60 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s6 parent_scroll_node_index=s0 scrollport_rect=[0,80 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s7 parent_scroll_node_index=s0 scrollport_rect=[0,100 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s8 parent_scroll_node_index=s0 scrollport_rect=[0,120 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s9 parent_scroll_node_index=s0 scrollport_rect=[0,140 20x20] min_scroll_offset=[0,0] max_scroll_offset=[80,80] is_viewport=false+ScrollNode scroll_node_index=s10 parent_scroll_node_index=s0 scrollport_rect=[0,160 400x300] min_scroll_offset=[0,0] max_scroll_offset=[1600,0] is_viewport=false+ScrollNode scroll_node_index=s11 parent_scroll_node_index=s10 scrollport_rect=[0,170 300x200] min_scroll_offset=[0,0] max_scroll_offset=[0,850] is_viewport=false++Layers:+ [L0] base space=viewport+ [L2] painted space=scroller@s11 in scroller@s10 in viewport composited within [0,160 400x300] of viewport composited within [0,170 300x200] of scroller@s10 in viewport+ [L3] canvas #0 space=scroller@s11 in scroller@s10 in viewport region=[0,217 203x126] composited within [0,160 400x300] of viewport composited within [0,170 300x200] of scroller@s10 in viewport shown by the window server: clip=[0,170 300x200]++DisplayList:+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x473] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x460] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s3 rect=[0,20 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s3/c1/e0 target_scroll_node_index=s3 rect=[0,20 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s4 rect=[0,40 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s4/c2/e0 target_scroll_node_index=s4 rect=[0,40 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s5 rect=[0,60 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s5/c3/e0 target_scroll_node_index=s5 rect=[0,60 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s6 rect=[0,80 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s6/c4/e0 target_scroll_node_index=s6 rect=[0,80 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s7 rect=[0,100 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s7/c5/e0 target_scroll_node_index=s7 rect=[0,100 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s8 rect=[0,120 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s8/c6/e0 target_scroll_node_index=s8 rect=[0,120 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s9 rect=[0,140 20x20] owner=BlockContainer<DIV>.clipped phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s9/c7/e0 target_scroll_node_index=s9 rect=[0,140 100x100] owner=BlockContainer<DIV> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s10 rect=[0,160 400x300] owner=BlockContainer<DIV>#clipping-wrapper phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s10/c8/e0 target_scroll_node_index=s10 rect=[0,160 2000x10] owner=BlockContainer<DIV>#wide phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s10/c8/e0 target_scroll_node_index=s11 rect=[0,170 300x200] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s11/c9/e0 target_scroll_node_index=s11 rect=[0,220 300x1000] owner=BlockContainer<DIV>#content phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s11/c9/e0 target_scroll_node_index=s11 rect=[0,280 100x40] owner=BlockContainer<DIV>#over-canvas phase=scroll-metadata+L2 FillRect@s11/c9/e0 rect=[0,280 100x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-canvas phase=background+L0 CompositorWheelHitTestTarget@s11/c9/e0 target_scroll_node_index=s11 rect=[0,220 200x120] owner=CanvasBox<CANVAS>#canvas phase=scroll-metadata+L3 DrawCanvas@s11/c9/e0 dst_rect=[0,220 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-transformed-boxes-beside-canvas.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-transformed-boxes-beside-canvas.txtindex 47bf5c187d5..25d0fd48343 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-transformed-boxes-beside-canvas.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-transformed-boxes-beside-canvas.txt@@ -2,22 +2,22 @@ AccumulatedVisualContext Tree:spatial:[s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)[s1] scroll (Viewport<#document>)- [s2] transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(255,175) bounds=[225,145 60x60] (BlockContainer<DIV>#rotated-with-only-bounding-box-on-canvas)- [s3] transform=[3,0,0,3,0,0] origin=(270,80) bounds=[250,60 40x40] (BlockContainer<DIV>#scaled-onto-canvas)+ [s2] transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(535,175) bounds=[505,145 60x60] (BlockContainer<DIV>#rotated-with-only-bounding-box-on-canvas)+ [s3] transform=[3,0,0,3,0,0] origin=(550,80) bounds=[530,60 40x40] (BlockContainer<DIV>#scaled-onto-canvas)[s4] transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(630,430) bounds=[600,400 60x60] (BlockContainer<DIV>#rotated-clear-of-canvas)- [s5] transform=[3,0,0,3,0,0] origin=(120,470) bounds=[100,450 40x40] (BlockContainer<DIV>#scaled-clear-of-canvas)+ [s5] transform=[3,0,0,3,0,0] origin=(720,540) bounds=[700,520 40x40] (BlockContainer<DIV>#scaled-clear-of-canvas)effects:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 206x126] shown by the window server: clip=[0,0 800x600]- [L2] painted rect=[207,17 126x204]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[297,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1DisplayList:-L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-L2 FillRect@s2/e0 rect=[225,145 60x60] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#rotated-with-only-bounding-box-on-canvas phase=background-L2 FillRect@s3/e0 rect=[250,60 40x40] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#scaled-onto-canvas phase=background+L1 DrawCanvas@s1/e0 dst_rect=[300,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+L0,L2 FillRect@s2/e0 rect=[505,145 60x60] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#rotated-with-only-bounding-box-on-canvas phase=background+L0,L2 FillRect@s3/e0 rect=[530,60 40x40] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#scaled-onto-canvas phase=backgroundL0 FillRect@s4/e0 rect=[600,400 60x60] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#rotated-clear-of-canvas phase=background-L0 FillRect@s5/e0 rect=[100,450 40x40] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#scaled-clear-of-canvas phase=background+L0 FillRect@s5/e0 rect=[700,520 40x40] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#scaled-clear-of-canvas phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-two-canvases.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-two-canvases.txtindex a5635e526d8..a876e04589c 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-two-canvases.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-two-canvases.txt@@ -6,14 +6,15 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] canvas rect=[17,17 206x126] shown by the window server: clip=[0,0 800x600]- [L2] canvas rect=[297,17 206x126] shown by the window server: clip=[0,0 800x600]- [L3] painted rect=[97,57 356x66]+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1+ [L3] canvas #0 space=viewport region=[517,17 206x126] shown by the window server: clip=[0,0 800x600]+ [L4] painted space=viewport above L3DisplayList:L1 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#left phase=foreground-L2 DrawCanvas@s1/e0 dst_rect=[300,20 200x120] canvas_id=canvas2 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#right phase=foreground-L3 FillRect@s1/e0 rect=[100,60 300x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-both phase=background-L3 FillRect@s1/e0 rect=[400,100 50x20] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#over-right phase=background+L3 DrawCanvas@s1/e0 dst_rect=[520,20 200x120] canvas_id=canvas2 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#right phase=foreground+L2,L4 FillRect@s1/e0 rect=[100,60 600x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over-both phase=background+L2,L4 FillRect@s1/e0 rect=[620,100 50x20] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#over-right phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-in-rotated-overflow-box.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-in-rotated-overflow-box.txtindex b6c7aada544..330c36c7c92 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-in-rotated-overflow-box.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-in-rotated-overflow-box.txt@@ -13,8 +13,8 @@ ScrollNodes:ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[100,100 200x150] min_scroll_offset=[0,0] max_scroll_offset=[120,33] is_viewport=falseLayers:- [L0] base rect=[0,0 800x600]- [L1] video rect=[85,80 230x190] replayed: clipped in a rotated or skewed space+ [L0] base space=viewport+ [L1] video #0 space=viewport region=[85,80 230x190] replayed: clipped in a rotated or skewed spaceDisplayList:L1 DrawVideoFrame@s3/c0/e0 dst_rect=[100,100 320x180] video_sink_handle=video1 scaling_mode=BilinearMipmap inline_clips=[clip=[100,100 320x180]] owner=VideoBox<VIDEO>#video phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-under-captions.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-under-captions.txtindex 457a3d33e10..0e6e2b978fc 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-under-captions.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-under-captions.txt@@ -6,9 +6,9 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] video rect=[7,37 326x186] shown by the window server: clip=[0,0 800x600]- [L2] painted rect=[27,197 209x30]+ [L0] base space=viewport+ [L1] video #0 space=viewport region=[7,37 326x186] shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1DisplayList:L1 DrawVideoFrame@s1/e0 dst_rect=[10,40 320x180] video_sink_handle=video1 scaling_mode=BilinearMipmap inline_clips=[clip=[10,10 320x240], clip=[10,10 320x240] radii=(16,16,16,16)] owner=VideoBox<VIDEO>#video phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-with-differing-corner-radii.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-with-differing-corner-radii.txtindex 34ed0c76a14..88adced5474 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-with-differing-corner-radii.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-video-with-differing-corner-radii.txt@@ -6,8 +6,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] video rect=[7,7 326x246] replayed: rounded corners of differing radii+ [L0] base space=viewport+ [L1] video #0 space=viewport region=[7,7 326x246] replayed: rounded corners of differing radiiDisplayList:L1 DrawVideoFrame@s1/e0 dst_rect=[10,10 320x240] video_sink_handle=video1 scaling_mode=BilinearMipmap inline_clips=[clip=[10,10 320x240], clip=[10,10 320x240] radii=(4,16,4,16)] owner=VideoBox<VIDEO>#video phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/contenteditable-caret.txt b/Tests/LibWeb/Text/expected/display_list/contenteditable-caret.txtindex c78967fb4c8..e511a3b54eb 100644--- a/Tests/LibWeb/Text/expected/display_list/contenteditable-caret.txt+++ b/Tests/LibWeb/Text/expected/display_list/contenteditable-caret.txt@@ -5,7 +5,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintCaret@s1/e0 rect=[8,8 1x16] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[6,6 104x24] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=BlockContainer<DIV> phase=outline+L0 PaintCaret@s1/e0 rect=[8,8 1x16] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[6,6 104x24] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=BlockContainer<DIV> phase=outlinediff --git a/Tests/LibWeb/Text/expected/display_list/css-clip-property.txt b/Tests/LibWeb/Text/expected/display_list/css-clip-property.txtindex 0df5a1fc577..4aa62eb6352 100644--- a/Tests/LibWeb/Text/expected/display_list/css-clip-property.txt+++ b/Tests/LibWeb/Text/expected/display_list/css-clip-property.txt@@ -7,8 +7,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,13 150x150] color=rgb(128, 0, 128) owner=BlockContainer<DIV>.clipped phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=8 rect=[8,13 71x16] glyph_bounding_rect=[8,14 75x15] translation=[8,26] color=rgb(0, 0, 0) text="CSS Clip" owner=BlockContainer<DIV>.clipped phase=foreground-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=8 rect=[8,29 72x16] glyph_bounding_rect=[8,30 78x15] translation=[8,42] color=rgb(0, 0, 0) text="Property" owner=BlockContainer<DIV>.clipped phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,13 150x150] color=rgb(128, 0, 128) owner=BlockContainer<DIV>.clipped phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=8 rect=[8,13 71x16] glyph_bounding_rect=[8,14 75x15] translation=[8,26] color=rgb(0, 0, 0) text="CSS Clip" owner=BlockContainer<DIV>.clipped phase=foreground+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=8 rect=[8,29 72x16] glyph_bounding_rect=[8,30 78x15] translation=[8,42] color=rgb(0, 0, 0) text="Property" owner=BlockContainer<DIV>.clipped phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/dashed-border-with-border-radius.txt b/Tests/LibWeb/Text/expected/display_list/dashed-border-with-border-radius.txtindex c05c0c9e3fe..ec511c644b8 100644--- a/Tests/LibWeb/Text/expected/display_list/dashed-border-with-border-radius.txt+++ b/Tests/LibWeb/Text/expected/display_list/dashed-border-with-border-radius.txt@@ -5,17 +5,20 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-StrokePath@s1/e0 dash_array=[19.817476, 19.817476] dash_offset=29.726215 path_bounding_rect=[8,8 120x80] path_data=[curved path: 135 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV> phase=border-StrokePath@s1/e0 dash_array=[29.634956, 29.634956] dash_offset=14.817478 path_bounding_rect=[110.677666,95.322334 17.322334x65.35534] path_data=[curved path: 34 commands] color=rgb(0, 0, 255) thickness=10 inline_clips=[clip_path=[bounds: [112,96 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[24.817474, 24.817474] dash_offset=12.408737 path_bounding_rect=[15.322332,150.67767 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,152 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[29.634954, 29.634954] dash_offset=14.817477 path_bounding_rect=[7.999999,95.322334 17.322334x65.35534] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,96 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[24.817476, 24.817476] dash_offset=12.408738 path_bounding_rect=[15.322332,88 105.35533x17.322334] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,88 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[20.622234, 20.622234] dash_offset=30.933352 path_bounding_rect=[8,168 120x80] path_data=[curved path: 39 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.touching-corners phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.817476] dash_offset=9.908738 path_bounding_rect=[8,248 120x80] path_data=[curved path: 135 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.dotted phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.75664] dash_offset=9.87832 path_bounding_rect=[110.677666,335.32233 17.322334x65.35535] path_data=[curved path: 34 commands] color=rgb(0, 0, 255) thickness=10 inline_clips=[clip_path=[bounds: [112,336 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.85398] dash_offset=9.92699 path_bounding_rect=[15.322332,390.67767 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,392 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.75664] dash_offset=9.87832 path_bounding_rect=[7.999999,335.32233 17.322334x65.35535] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,336 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.85398] dash_offset=9.92699 path_bounding_rect=[15.322332,328 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,328 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 20.622234] dash_offset=10.311117 path_bounding_rect=[8,408 120x80] path_data=[curved path: 39 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.dotted.touching-corners phase=border+L0 StrokePath@s1/e0 dash_array=[19.817476, 19.817476] dash_offset=29.726215 path_bounding_rect=[8,8 120x80] path_data=[curved path: 135 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV> phase=border+L0 StrokePath@s1/e0 dash_array=[29.634956, 29.634956] dash_offset=14.817478 path_bounding_rect=[110.677666,95.322334 17.322334x65.35534] path_data=[curved path: 34 commands] color=rgb(0, 0, 255) thickness=10 inline_clips=[clip_path=[bounds: [112,96 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[24.817474, 24.817474] dash_offset=12.408737 path_bounding_rect=[15.322332,150.67767 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,152 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[29.634954, 29.634954] dash_offset=14.817477 path_bounding_rect=[7.999999,95.322334 17.322334x65.35534] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,96 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[24.817476, 24.817476] dash_offset=12.408738 path_bounding_rect=[15.322332,88 105.35533x17.322334] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,88 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[20.622234, 20.622234] dash_offset=30.933352 path_bounding_rect=[8,168 120x80] path_data=[curved path: 39 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.touching-corners phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.817476] dash_offset=9.908738 path_bounding_rect=[8,248 120x80] path_data=[curved path: 135 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.dotted phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.75664] dash_offset=9.87832 path_bounding_rect=[110.677666,335.32233 17.322334x65.35535] path_data=[curved path: 34 commands] color=rgb(0, 0, 255) thickness=10 inline_clips=[clip_path=[bounds: [112,336 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.85398] dash_offset=9.92699 path_bounding_rect=[15.322332,390.67767 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,392 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.75664] dash_offset=9.87832 path_bounding_rect=[7.999999,335.32233 17.322334x65.35535] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,336 16x64], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 19.85398] dash_offset=9.92699 path_bounding_rect=[15.322332,328 105.35533x17.322327] path_data=[curved path: 34 commands] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [16,328 104x16], curved path: 68 commands] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted.mixed-colors phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 20.622234] dash_offset=10.311117 path_bounding_rect=[8,408 120x80] path_data=[curved path: 39 commands] color=rgb(255, 0, 0) thickness=10 owner=BlockContainer<DIV>.dotted.touching-corners phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/deep-branching-tree.txt b/Tests/LibWeb/Text/expected/display_list/deep-branching-tree.txtindex 30448ae41cf..7e7e348170f 100644--- a/Tests/LibWeb/Text/expected/display_list/deep-branching-tree.txt+++ b/Tests/LibWeb/Text/expected/display_list/deep-branching-tree.txt@@ -13,16 +13,19 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 404x204] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.root phase=border-FillRoundedRectRing@s1/c0/e0 rect=[10,10 195x200] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.branch phase=border-FillRoundedRectRing@s1/c0/e0 rect=[215,10 195x200] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.branch phase=border-FillRect@s2/c1/e0 rect=[16,16 150x80] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.leaf.leaf-a phase=background-DrawGlyphRun@s2/c1/e0 font_id=font1 glyphs=1 rect=[16,16 15x16] glyph_bounding_rect=[16,16 13x15] translation=[16,29] color=rgb(0, 0, 0) text="A" owner=BlockContainer<DIV>.leaf.leaf-a phase=foreground-FillRect@s3/c1/e0 rect=[16,101 150x80] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.leaf.leaf-b phase=background-DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=1 rect=[16,101 10x16] glyph_bounding_rect=[16,102 13x15] translation=[16,114] color=rgb(0, 0, 0) text="B" owner=BlockContainer<DIV>.leaf.leaf-b phase=foreground-FillRect@s4/c2/e0 rect=[221,16 150x80] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.leaf.leaf-c phase=background-DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=1 rect=[221,16 11x16] glyph_bounding_rect=[221,16 13x15] translation=[221,29] color=rgb(0, 0, 0) text="C" owner=BlockContainer<DIV>.leaf.leaf-c phase=foreground-FillRect@s5/c2/e0 rect=[221,101 150x80] color=rgb(255, 165, 0) owner=BlockContainer<DIV>.leaf.leaf-d phase=background-DrawGlyphRun@s5/c2/e0 font_id=font1 glyphs=1 rect=[221,101 12x16] glyph_bounding_rect=[221,102 13x15] translation=[221,114] color=rgb(0, 0, 0) text="D" owner=BlockContainer<DIV>.leaf.leaf-d phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[8,8 404x204] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.root phase=border+L0 FillRoundedRectRing@s1/c0/e0 rect=[10,10 195x200] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.branch phase=border+L0 FillRoundedRectRing@s1/c0/e0 rect=[215,10 195x200] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.branch phase=border+L0 FillRect@s2/c1/e0 rect=[16,16 150x80] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.leaf.leaf-a phase=background+L0 DrawGlyphRun@s2/c1/e0 font_id=font1 glyphs=1 rect=[16,16 15x16] glyph_bounding_rect=[16,16 13x15] translation=[16,29] color=rgb(0, 0, 0) text="A" owner=BlockContainer<DIV>.leaf.leaf-a phase=foreground+L0 FillRect@s3/c1/e0 rect=[16,101 150x80] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.leaf.leaf-b phase=background+L0 DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=1 rect=[16,101 10x16] glyph_bounding_rect=[16,102 13x15] translation=[16,114] color=rgb(0, 0, 0) text="B" owner=BlockContainer<DIV>.leaf.leaf-b phase=foreground+L0 FillRect@s4/c2/e0 rect=[221,16 150x80] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.leaf.leaf-c phase=background+L0 DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=1 rect=[221,16 11x16] glyph_bounding_rect=[221,16 13x15] translation=[221,29] color=rgb(0, 0, 0) text="C" owner=BlockContainer<DIV>.leaf.leaf-c phase=foreground+L0 FillRect@s5/c2/e0 rect=[221,101 150x80] color=rgb(255, 165, 0) owner=BlockContainer<DIV>.leaf.leaf-d phase=background+L0 DrawGlyphRun@s5/c2/e0 font_id=font1 glyphs=1 rect=[221,101 12x16] glyph_bounding_rect=[221,102 13x15] translation=[221,114] color=rgb(0, 0, 0) text="D" owner=BlockContainer<DIV>.leaf.leaf-d phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/double-border-with-asymmetric-radii.txt b/Tests/LibWeb/Text/expected/display_list/double-border-with-asymmetric-radii.txtindex 6430a178291..31b204f7f5b 100644--- a/Tests/LibWeb/Text/expected/display_list/double-border-with-asymmetric-radii.txt+++ b/Tests/LibWeb/Text/expected/display_list/double-border-with-asymmetric-radii.txt@@ -5,13 +5,16 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s1/e0 path_bounding_rect=[192.04163,10.928932 15.958374x135.35535] path_data=[curved path: 48 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[182.14214,22 11.857864x114.38478] path_data=[curved path: 37 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[10.928932,142.04163 185.35535x15.958374] path_data=[curved path: 48 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[22,132.14214 164.38478x11.857864] path_data=[curved path: 37 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[7.9999967,19.715729 15.958374x135.35535] path_data=[curved path: 48 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[22,29.615223 11.857864x114.38478] path_data=[curved path: 37 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[19.715729,7.9999967 185.35535x15.958374] path_data=[curved path: 48 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[29.615223,22 164.38478x11.857864] path_data=[curved path: 37 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[192.04163,10.928932 15.958374x135.35535] path_data=[curved path: 48 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[182.14214,22 11.857864x114.38478] path_data=[curved path: 37 commands] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[10.928932,142.04163 185.35535x15.958374] path_data=[curved path: 48 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[22,132.14214 164.38478x11.857864] path_data=[curved path: 37 commands] color=rgb(0, 128, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[7.9999967,19.715729 15.958374x135.35535] path_data=[curved path: 48 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[22,29.615223 11.857864x114.38478] path_data=[curved path: 37 commands] color=rgb(255, 165, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[19.715729,7.9999967 185.35535x15.958374] path_data=[curved path: 48 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[29.615223,22 164.38478x11.857864] path_data=[curved path: 37 commands] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/fieldset-background-with-legend.txt b/Tests/LibWeb/Text/expected/display_list/fieldset-background-with-legend.txtindex 1801888d313..59f2605268a 100644--- a/Tests/LibWeb/Text/expected/display_list/fieldset-background-with-legend.txt+++ b/Tests/LibWeb/Text/expected/display_list/fieldset-background-with-legend.txt@@ -5,16 +5,19 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[10,8 780x50] color=rgb(0, 0, 255) inline_clips=[clip=[10,15 780x43]] owner=FieldSetBox<FIELDSET> phase=background-FillPath@s1/e0 path_bounding_rect=[10,15 780x1] path_data=[path: M10 15L10 15L11 16L789 16L790 15L790 15] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[11,16 778x1] path_data=[path: M11 16L11 16L12 17L788 17L789 16L789 16] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[789,15 1x43] path_data=[path: M790 15L790 15L789 16L789 57L790 58L790 58] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[788,16 1x41] path_data=[path: M789 16L789 16L788 17L788 56L789 57L789 57] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[10,57 780x1] path_data=[path: M790 58L790 58L789 57L11 57L10 58L10 58] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[11,56 778x1] path_data=[path: M789 57L789 57L788 56L12 56L11 57L11 57] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[10,15 1x43] path_data=[path: M10 58L10 58L11 57L11 16L10 15L10 15] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-FillPath@s1/e0 path_bounding_rect=[11,16 1x41] path_data=[path: M11 57L11 57L12 56L12 17L11 16L11 16] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[26,8 54x16] glyph_bounding_rect=[26,8 59x15] translation=[26,21] color=rgb(0, 0, 0) text="Legend" owner=LegendBox<LEGEND> phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[24,29 63x17] glyph_bounding_rect=[24,30 69x15] translation=[24,42.59375] color=rgb(0, 0, 0) text="Content" owner=BlockContainer(anonymous) phase=foreground+L0 FillRect@s1/e0 rect=[10,8 780x50] color=rgb(0, 0, 255) inline_clips=[clip=[10,15 780x43]] owner=FieldSetBox<FIELDSET> phase=background+L0 FillPath@s1/e0 path_bounding_rect=[10,15 780x1] path_data=[path: M10 15L10 15L11 16L789 16L790 15L790 15] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[11,16 778x1] path_data=[path: M11 16L11 16L12 17L788 17L789 16L789 16] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[789,15 1x43] path_data=[path: M790 15L790 15L789 16L789 57L790 58L790 58] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[788,16 1x41] path_data=[path: M789 16L789 16L788 17L788 56L789 57L789 57] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[10,57 780x1] path_data=[path: M790 58L790 58L789 57L11 57L10 58L10 58] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[11,56 778x1] path_data=[path: M789 57L789 57L788 56L12 56L11 57L11 57] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[10,15 1x43] path_data=[path: M10 58L10 58L11 57L11 16L10 15L10 15] color=rgb(154, 154, 154) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[11,16 1x41] path_data=[path: M11 57L11 57L12 56L12 17L11 16L11 16] color=rgb(239, 239, 239) winding_rule=EvenOdd inline_clips=[clip=[24,15 57x2] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[26,8 54x16] glyph_bounding_rect=[26,8 59x15] translation=[26,21] color=rgb(0, 0, 0) text="Legend" owner=LegendBox<LEGEND> phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[24,29 63x17] glyph_bounding_rect=[24,30 69x15] translation=[24,42.59375] color=rgb(0, 0, 0) text="Content" owner=BlockContainer(anonymous) phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/fieldset-legend-rounded-dashed-border.txt b/Tests/LibWeb/Text/expected/display_list/fieldset-legend-rounded-dashed-border.txtindex 4228d9ac980..2bdae6b4441 100644--- a/Tests/LibWeb/Text/expected/display_list/fieldset-legend-rounded-dashed-border.txt+++ b/Tests/LibWeb/Text/expected/display_list/fieldset-legend-rounded-dashed-border.txt@@ -5,8 +5,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-StrokePath@s1/e0 dash_array=[6.0229473, 6.0229473] dash_offset=9.034421 path_bounding_rect=[10,15 230x44] path_data=[curved path: 135 commands] color=rgb(0, 0, 255) thickness=3 inline_clips=[clip=[25,15 57x3] mode=difference] owner=FieldSetBox<FIELDSET> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[27,8 54x16] glyph_bounding_rect=[27,8 59x15] translation=[27,21] color=rgb(0, 0, 0) text="Legend" owner=LegendBox<LEGEND> phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[25,29 63x17] glyph_bounding_rect=[25,30 69x15] translation=[25,42.59375] color=rgb(0, 0, 0) text="Content" owner=BlockContainer(anonymous) phase=foreground+L0 StrokePath@s1/e0 dash_array=[6.0229473, 6.0229473] dash_offset=9.034421 path_bounding_rect=[10,15 230x44] path_data=[curved path: 135 commands] color=rgb(0, 0, 255) thickness=3 inline_clips=[clip=[25,15 57x3] mode=difference] owner=FieldSetBox<FIELDSET> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[27,8 54x16] glyph_bounding_rect=[27,8 59x15] translation=[27,21] color=rgb(0, 0, 0) text="Legend" owner=LegendBox<LEGEND> phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[25,29 63x17] glyph_bounding_rect=[25,30 69x15] translation=[25,42.59375] color=rgb(0, 0, 0) text="Content" owner=BlockContainer(anonymous) phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/fixed-position.txt b/Tests/LibWeb/Text/expected/display_list/fixed-position.txtindex 23f8d4fed92..2fba46e2bb7 100644--- a/Tests/LibWeb/Text/expected/display_list/fixed-position.txt+++ b/Tests/LibWeb/Text/expected/display_list/fixed-position.txt@@ -7,9 +7,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c0/e0 rect=[8,8 150x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.normal phase=background-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=6 rect=[8,8 56x16] glyph_bounding_rect=[8,8 64x15] translation=[8,21] color=rgb(0, 0, 0) text="Normal" owner=BlockContainer<DIV>.normal phase=foreground-FillRect@s0/e0 rect=[10,10 80x40] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.fixed phase=background-DrawGlyphRun@s0/e0 font_id=font1 glyphs=5 rect=[10,10 44x16] glyph_bounding_rect=[10,10 49x15] translation=[10,23] color=rgb(0, 0, 0) text="Fixed" owner=BlockContainer<DIV>.fixed phase=foreground+L0 FillRect@s1/c0/e0 rect=[8,8 150x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.normal phase=background+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=6 rect=[8,8 56x16] glyph_bounding_rect=[8,8 64x15] translation=[8,21] color=rgb(0, 0, 0) text="Normal" owner=BlockContainer<DIV>.normal phase=foreground+L0 FillRect@s0/e0 rect=[10,10 80x40] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.fixed phase=background+L0 DrawGlyphRun@s0/e0 font_id=font1 glyphs=5 rect=[10,10 44x16] glyph_bounding_rect=[10,10 49x15] translation=[10,23] color=rgb(0, 0, 0) text="Fixed" owner=BlockContainer<DIV>.fixed phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/form-control-devolved-borders.txt b/Tests/LibWeb/Text/expected/display_list/form-control-devolved-borders.txtindex faade5bef4e..2d2a7d3c723 100644--- a/Tests/LibWeb/Text/expected/display_list/form-control-devolved-borders.txt+++ b/Tests/LibWeb/Text/expected/display_list/form-control-devolved-borders.txt@@ -1,6 +1,6 @@-FillRoundedRectRing@s1/e0 rect=[0,0 58x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border-FillRoundedRectRing@s1/e0 rect=[66,0 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border-FillPath@s1/e0 path_bounding_rect=[0,20 74x20] path_data=[path: M74 20L74 20L72 22L72 38L74 40L74 40M74 40L74 40L72 38L2 38L0 40L0 40] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON>.none phase=border-FillPath@s1/e0 path_bounding_rect=[0,20 74x20] path_data=[path: M0 40L0 40L2 38L2 22L0 20L0 20M0 20L0 20L2 22L72 22L74 20L74 20] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON>.none phase=border-FillPath@s1/e0 path_bounding_rect=[82,20 178x20] path_data=[path: M260 20L260 20L258 22L258 38L260 40L260 40M260 40L260 40L258 38L84 38L82 40L82 40] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<INPUT>.none phase=border-FillPath@s1/e0 path_bounding_rect=[82,20 178x20] path_data=[path: M82 40L82 40L84 38L84 22L82 20L82 20M82 20L82 20L84 22L258 22L260 20L260 20] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<INPUT>.none phase=border+L0 FillRoundedRectRing@s1/e0 rect=[0,0 58x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border+L0 FillRoundedRectRing@s1/e0 rect=[66,0 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,20 74x20] path_data=[path: M74 20L74 20L72 22L72 38L74 40L74 40M74 40L74 40L72 38L2 38L0 40L0 40] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON>.none phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,20 74x20] path_data=[path: M0 40L0 40L2 38L2 22L0 20L0 20M0 20L0 20L2 22L72 22L74 20L74 20] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON>.none phase=border+L0 FillPath@s1/e0 path_bounding_rect=[82,20 178x20] path_data=[path: M260 20L260 20L258 22L258 38L260 40L260 40M260 40L260 40L258 38L84 38L82 40L82 40] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<INPUT>.none phase=border+L0 FillPath@s1/e0 path_bounding_rect=[82,20 178x20] path_data=[path: M82 40L82 40L84 38L84 22L82 20L82 20M82 20L82 20L84 22L258 22L260 20L260 20] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<INPUT>.none phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/form-control-native-appearance-corners.txt b/Tests/LibWeb/Text/expected/display_list/form-control-native-appearance-corners.txtindex cd6b00ecbb4..736a4dccc96 100644--- a/Tests/LibWeb/Text/expected/display_list/form-control-native-appearance-corners.txt+++ b/Tests/LibWeb/Text/expected/display_list/form-control-native-appearance-corners.txt@@ -10,33 +10,36 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 58x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON>#native phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 58x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON>#native phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[9,3 40x14] glyph_bounding_rect=[9,4 44x12] translation=[9,14] color=rgb(0, 0, 0) text="Native" owner=BlockContainer(anonymous) phase=foreground-FillRectWithRoundedCorners@s1/e0 rect=[0,30 130x24] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background-FillRoundedRectRing@s1/e0 rect=[0,30 130x24] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=17 rect=[5,35 120x14] glyph_bounding_rect=[5,36 124x12] translation=[5,46] color=rgb(0, 128, 0) text="Padding and color" owner=BlockContainer(anonymous) phase=foreground-FillRectWithRoundedCorners@s1/e0 rect=[0,60 129x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON>#revert phase=background-FillRoundedRectRing@s1/e0 rect=[0,60 129x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON>#revert phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=15 rect=[9,63 112x14] glyph_bounding_rect=[9,64 115x12] translation=[9,74] color=rgb(0, 0, 0) text="Reverted border" owner=BlockContainer(anonymous) phase=foreground-FillRect@s1/e0 rect=[0,90 92x20] color=rgb(0, 255, 0) owner=BlockContainer<BUTTON> phase=background-FillPath@s1/e0 path_bounding_rect=[0,90 92x20] path_data=[path: M92 90L92 90L90 92L90 108L92 110L92 110M92 110L92 110L90 108L2 108L0 110L0 110] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-FillPath@s1/e0 path_bounding_rect=[0,90 92x20] path_data=[path: M0 110L0 110L2 108L2 92L0 90L0 90M0 90L0 90L2 92L90 92L92 90L92 90] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[9,93 75x14] glyph_bounding_rect=[9,94 79x12] translation=[9,104] color=rgb(0, 0, 0) text="Background" owner=BlockContainer(anonymous) phase=foreground-FillRect@s1/e0 rect=[0,120 63x20] color=rgb(239, 239, 239) owner=BlockContainer<BUTTON> phase=background-FillPath@s1/e0 path_bounding_rect=[0,120 63x20] path_data=[path: M63 120L63 120L61 122L61 138L63 140L63 140M63 140L63 140L61 138L2 138L0 140L0 140] color=rgb(170, 0, 0) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-FillPath@s1/e0 path_bounding_rect=[0,120 63x20] path_data=[path: M0 140L0 140L2 138L2 122L0 120L0 120M0 120L0 120L2 122L61 122L63 120L63 120] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[9,123 45x14] glyph_bounding_rect=[9,124 49x12] translation=[9,134] color=rgb(0, 0, 0) text="Border" owner=BlockContainer(anonymous) phase=foreground-FillRect@s1/e0 rect=[0,150 137x20] color=rgb(239, 239, 239) owner=BlockContainer<BUTTON> phase=background-FillPath@s1/e0 path_bounding_rect=[0,150 137x20] path_data=[path: M137 150L137 150L135 152L135 168L137 170L137 170M137 170L137 170L135 168L2 168L0 170L0 170] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-FillPath@s1/e0 path_bounding_rect=[0,150 137x20] path_data=[path: M0 170L0 170L2 168L2 152L0 150L0 150M0 150L0 150L2 152L135 152L137 150L137 150] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=15 rect=[9,153 119x14] glyph_bounding_rect=[9,154 123x12] translation=[9,164] color=rgb(0, 0, 0) text="Appearance none" owner=BlockContainer(anonymous) phase=foreground-FillRectWithRoundedCorners@s1/e0 rect=[0,180 178x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT> phase=background-FillRoundedRectRing@s1/e0 rect=[0,180 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border-DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=4 rect=[5,183 32x14] glyph_bounding_rect=[5,184 37x12] translation=[5,194] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV> phase=foreground-FillRect@s1/e0 rect=[0,210 180x22] color=rgb(255, 255, 255) owner=TextInputBox<INPUT> phase=background-FillPath@s1/e0 path_bounding_rect=[0,210 180x22] path_data=[path: M180 210L180 210L177 213L177 229L180 232L180 232M180 232L180 232L177 229L3 229L0 232L0 232] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=TextInputBox<INPUT> phase=border-FillPath@s1/e0 path_bounding_rect=[0,210 180x22] path_data=[path: M0 232L0 232L3 229L3 213L0 210L0 210M0 210L0 210L3 213L177 213L180 210L180 210] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=TextInputBox<INPUT> phase=border-DrawGlyphRun@s1/c3/e0 font_id=font1 glyphs=8 rect=[6,214 59x14] glyph_bounding_rect=[6,215 63x12] translation=[6,225] color=rgb(0, 0, 0) text="Bordered" owner=BlockContainer<DIV> phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 58x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON>#native phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 58x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON>#native phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[9,3 40x14] glyph_bounding_rect=[9,4 44x12] translation=[9,14] color=rgb(0, 0, 0) text="Native" owner=BlockContainer(anonymous) phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,30 130x24] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,30 130x24] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=17 rect=[5,35 120x14] glyph_bounding_rect=[5,36 124x12] translation=[5,46] color=rgb(0, 128, 0) text="Padding and color" owner=BlockContainer(anonymous) phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,60 129x20] color=rgb(239, 239, 239) corner_radii=[4x4,4x4,4x4,4x4] owner=BlockContainer<BUTTON>#revert phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,60 129x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=BlockContainer<BUTTON>#revert phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=15 rect=[9,63 112x14] glyph_bounding_rect=[9,64 115x12] translation=[9,74] color=rgb(0, 0, 0) text="Reverted border" owner=BlockContainer(anonymous) phase=foreground+L0 FillRect@s1/e0 rect=[0,90 92x20] color=rgb(0, 255, 0) owner=BlockContainer<BUTTON> phase=background+L0 FillPath@s1/e0 path_bounding_rect=[0,90 92x20] path_data=[path: M92 90L92 90L90 92L90 108L92 110L92 110M92 110L92 110L90 108L2 108L0 110L0 110] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,90 92x20] path_data=[path: M0 110L0 110L2 108L2 92L0 90L0 90M0 90L0 90L2 92L90 92L92 90L92 90] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[9,93 75x14] glyph_bounding_rect=[9,94 79x12] translation=[9,104] color=rgb(0, 0, 0) text="Background" owner=BlockContainer(anonymous) phase=foreground+L0 FillRect@s1/e0 rect=[0,120 63x20] color=rgb(239, 239, 239) owner=BlockContainer<BUTTON> phase=background+L0 FillPath@s1/e0 path_bounding_rect=[0,120 63x20] path_data=[path: M63 120L63 120L61 122L61 138L63 140L63 140M63 140L63 140L61 138L2 138L0 140L0 140] color=rgb(170, 0, 0) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,120 63x20] path_data=[path: M0 140L0 140L2 138L2 122L0 120L0 120M0 120L0 120L2 122L61 122L63 120L63 120] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[9,123 45x14] glyph_bounding_rect=[9,124 49x12] translation=[9,134] color=rgb(0, 0, 0) text="Border" owner=BlockContainer(anonymous) phase=foreground+L0 FillRect@s1/e0 rect=[0,150 137x20] color=rgb(239, 239, 239) owner=BlockContainer<BUTTON> phase=background+L0 FillPath@s1/e0 path_bounding_rect=[0,150 137x20] path_data=[path: M137 150L137 150L135 152L135 168L137 170L137 170M137 170L137 170L135 168L2 168L0 170L0 170] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,150 137x20] path_data=[path: M0 170L0 170L2 168L2 152L0 150L0 150M0 150L0 150L2 152L135 152L137 150L137 150] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=BlockContainer<BUTTON> phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=15 rect=[9,153 119x14] glyph_bounding_rect=[9,154 123x12] translation=[9,164] color=rgb(0, 0, 0) text="Appearance none" owner=BlockContainer(anonymous) phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,180 178x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,180 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border+L0 DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=4 rect=[5,183 32x14] glyph_bounding_rect=[5,184 37x12] translation=[5,194] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV> phase=foreground+L0 FillRect@s1/e0 rect=[0,210 180x22] color=rgb(255, 255, 255) owner=TextInputBox<INPUT> phase=background+L0 FillPath@s1/e0 path_bounding_rect=[0,210 180x22] path_data=[path: M180 210L180 210L177 213L177 229L180 232L180 232M180 232L180 232L177 229L3 229L0 232L0 232] color=rgb(118, 118, 118) winding_rule=EvenOdd owner=TextInputBox<INPUT> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[0,210 180x22] path_data=[path: M0 232L0 232L3 229L3 213L0 210L0 210M0 210L0 210L3 213L177 213L180 210L180 210] color=rgb(33, 33, 33) winding_rule=EvenOdd owner=TextInputBox<INPUT> phase=border+L0 DrawGlyphRun@s1/c3/e0 font_id=font1 glyphs=8 rect=[6,214 59x14] glyph_bounding_rect=[6,215 63x12] translation=[6,225] color=rgb(0, 0, 0) text="Bordered" owner=BlockContainer<DIV> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/grid-gap-rounding.txt b/Tests/LibWeb/Text/expected/display_list/grid-gap-rounding.txtindex 4fefc417be7..843fd247f87 100644--- a/Tests/LibWeb/Text/expected/display_list/grid-gap-rounding.txt+++ b/Tests/LibWeb/Text/expected/display_list/grid-gap-rounding.txt@@ -5,10 +5,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background-FillRect@s1/e0 rect=[38,8 28x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background-FillRect@s1/e0 rect=[67,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background-FillRect@s1/e0 rect=[97,8 28x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background-FillRect@s1/e0 rect=[126,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background+L0 FillRect@s1/e0 rect=[8,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background+L0 FillRect@s1/e0 rect=[38,8 28x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background+L0 FillRect@s1/e0 rect=[67,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background+L0 FillRect@s1/e0 rect=[97,8 28x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=background+L0 FillRect@s1/e0 rect=[126,8 29x30] color=rgb(0, 0, 0) owner=BlockContainer<DIV>.b phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/iframe-compositor-surface.txt b/Tests/LibWeb/Text/expected/display_list/iframe-compositor-surface.txtindex 472fbd2f8ce..ae94d84eb76 100644--- a/Tests/LibWeb/Text/expected/display_list/iframe-compositor-surface.txt+++ b/Tests/LibWeb/Text/expected/display_list/iframe-compositor-surface.txt@@ -6,8 +6,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers:- [L0] base rect=[0,0 800x600]- [L1] composited context rect=[0,0 123x83]+ [L0] base space=viewport+ [L1] composited context #0 space=viewport region=[0,0 123x83]DisplayList:L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadatadiff --git a/Tests/LibWeb/Text/expected/display_list/iframe-in-svg-mask-and-pattern.txt b/Tests/LibWeb/Text/expected/display_list/iframe-in-svg-mask-and-pattern.txtindex b9757c3f1bf..e197d5e7f25 100644--- a/Tests/LibWeb/Text/expected/display_list/iframe-in-svg-mask-and-pattern.txt+++ b/Tests/LibWeb/Text/expected/display_list/iframe-in-svg-mask-and-pattern.txt@@ -10,11 +10,14 @@ AccumulatedVisualContext Tree:[e1 in s2 out=c0] mask=[0,0 100x100] kind=luminance origin=svg-mask (SVGGeometryBox<rect>)[e2 in s2 out=c0] mask=[200,0 100x100] kind=luminance origin=svg-mask (SVGGeometryBox<rect>)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s2/c0/e1 rect=[0,0 100x100] effect=e1 owner=SVGSVGBox<svg> phase=svg-FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground-FillPath@s2/c0/e0 path_bounding_rect=[100,0 100x100] path_data=[path: M100 0L200 0L200 100L100 100L100 0Z] paint_kind=PaintStyle color=rgba(0, 0, 0, 0) paint_style={paint_style_type=Pattern pattern_tile_rect=[0,0 50x50]} owner=SVGGeometryBox<rect> phase=foreground- PatternTile:-DeclareMaskContent@s2/c0/e2 rect=[200,0 100x100] effect=e2 owner=SVGSVGBox<svg> phase=svg-FillPath@s2/c0/e2 path_bounding_rect=[200,0 100x100] path_data=[path: M200 0L300 0L300 100L200 100L200 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 DeclareMaskContent@s2/c0/e1 rect=[0,0 100x100] effect=e1 owner=SVGSVGBox<svg> phase=svg+L0 FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s2/c0/e0 path_bounding_rect=[100,0 100x100] path_data=[path: M100 0L200 0L200 100L100 100L100 0Z] paint_kind=PaintStyle color=rgba(0, 0, 0, 0) paint_style={paint_style_type=Pattern pattern_tile_rect=[0,0 50x50]} owner=SVGGeometryBox<rect> phase=foreground+ PatternTile:+L0 DeclareMaskContent@s2/c0/e2 rect=[200,0 100x100] effect=e2 owner=SVGSVGBox<svg> phase=svg+L0 FillPath@s2/c0/e2 path_bounding_rect=[200,0 100x100] path_data=[path: M200 0L300 0L300 100L200 100L200 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/image-object-fit-cover-clip.txt b/Tests/LibWeb/Text/expected/display_list/image-object-fit-cover-clip.txtindex b6b240438bc..8139c25ae61 100644--- a/Tests/LibWeb/Text/expected/display_list/image-object-fit-cover-clip.txt+++ b/Tests/LibWeb/Text/expected/display_list/image-object-fit-cover-clip.txt@@ -5,6 +5,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawScaledDecodedImageFrame@s1/e0 dst_rect=[0,-20 40x80] frame_id=image1 scaling_mode=BilinearMipmap inline_clips=[clip=[0,0 40x40]] owner=ImageBox<IMG> phase=foreground+L0 DrawScaledDecodedImageFrame@s1/e0 dst_rect=[0,-20 40x80] frame_id=image1 scaling_mode=BilinearMipmap inline_clips=[clip=[0,0 40x40]] owner=ImageBox<IMG> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/input-caret.txt b/Tests/LibWeb/Text/expected/display_list/input-caret.txtindex 0085000c4fa..d58e7e08b52 100644--- a/Tests/LibWeb/Text/expected/display_list/input-caret.txt+++ b/Tests/LibWeb/Text/expected/display_list/input-caret.txt@@ -8,10 +8,13 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,8 110x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT> phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 110x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border-DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=5 rect=[13,11 31x14] glyph_bounding_rect=[13,12 33x12] translation=[13,22] color=rgb(0, 0, 0) text="hello" owner=BlockContainer<DIV> phase=foreground-PaintCaret@s1/c1/e0 rect=[13,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[6,6 114x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT> phase=outline+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,8 110x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 110x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT> phase=border+L0 DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=5 rect=[13,11 31x14] glyph_bounding_rect=[13,12 33x12] translation=[13,22] color=rgb(0, 0, 0) text="hello" owner=BlockContainer<DIV> phase=foreground+L0 PaintCaret@s1/c1/e0 rect=[13,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[6,6 114x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT> phase=outlinediff --git a/Tests/LibWeb/Text/expected/display_list/input-focus-switch-selection-and-caret.txt b/Tests/LibWeb/Text/expected/display_list/input-focus-switch-selection-and-caret.txtindex b19d4d1d57b..99552ddc419 100644--- a/Tests/LibWeb/Text/expected/display_list/input-focus-switch-selection-and-caret.txt+++ b/Tests/LibWeb/Text/expected/display_list/input-focus-switch-selection-and-caret.txt@@ -10,14 +10,17 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,8 178x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT>#foo phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT>#foo phase=border-DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=3 rect=[13,11 23x14] glyph_bounding_rect=[13,12 25x12] translation=[13,22] color=rgb(0, 0, 0) text="foo" owner=BlockContainer<DIV> phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=1 rect=[185,9 9x16] glyph_bounding_rect=[186,10 13x15] translation=[185.6875,22] color=rgb(0, 0, 0) text=" " owner=BlockContainer(anonymous) phase=text-fragment-FillRectWithRoundedCorners@s1/e0 rect=[194,8 177x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT>#bar phase=background-FillRoundedRectRing@s1/e0 rect=[194,8 177x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT>#bar phase=border-DrawGlyphRun@s1/c3/e0 font_id=font1 glyphs=3 rect=[198,11 24x14] glyph_bounding_rect=[199,12 27x12] translation=[198.6875,22] color=rgb(0, 0, 0) text="bar" owner=BlockContainer<DIV> phase=foreground-PaintCaret@s1/c3/e0 rect=[199,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[192,6 181x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT>#bar phase=outline+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,8 178x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT>#foo phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 178x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT>#foo phase=border+L0 DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=3 rect=[13,11 23x14] glyph_bounding_rect=[13,12 25x12] translation=[13,22] color=rgb(0, 0, 0) text="foo" owner=BlockContainer<DIV> phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=1 rect=[185,9 9x16] glyph_bounding_rect=[186,10 13x15] translation=[185.6875,22] color=rgb(0, 0, 0) text=" " owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRectWithRoundedCorners@s1/e0 rect=[194,8 177x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextInputBox<INPUT>#bar phase=background+L0 FillRoundedRectRing@s1/e0 rect=[194,8 177x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextInputBox<INPUT>#bar phase=border+L0 DrawGlyphRun@s1/c3/e0 font_id=font1 glyphs=3 rect=[198,11 24x14] glyph_bounding_rect=[199,12 27x12] translation=[198.6875,22] color=rgb(0, 0, 0) text="bar" owner=BlockContainer<DIV> phase=foreground+L0 PaintCaret@s1/c3/e0 rect=[199,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[192,6 181x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT>#bar phase=outlinediff --git a/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt b/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txtindex 9565475a404..a5034c6cc6b 100644--- a/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt+++ b/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt@@ -1,15 +1,16 @@-types: {"header":1,"node":5,"layer":2,"chunk":1,"record":6}+types: {"header":1,"node":5,"layer":3,"chunk":1,"record":6}header: ladybird-display-list-dump version 1 viewport [0,0,800,600] print-order 6 recordsrecord ids count up from 1: true{"type":"node","kind":"spatial","name":"s0","raw":0,"depth":0,"description":"transform=[1,0,0,1,0,0] origin=(0,0)","owner":"Viewport<#document>"}{"type":"node","kind":"spatial","name":"s1","raw":1,"depth":1,"parent":"s0","description":"scroll","owner":"Viewport<#document>"}-{"type":"node","kind":"spatial","name":"s2","raw":2,"depth":2,"parent":"s1","description":"transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(325,45) bounds=[300,20 50x50]","owner":"BlockContainer<DIV>#transformed"}+{"type":"node","kind":"spatial","name":"s2","raw":2,"depth":2,"parent":"s1","description":"transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(625,45) bounds=[600,20 50x50]","owner":"BlockContainer<DIV>#transformed"}{"type":"node","kind":"effect","name":"e0","raw":0,"depth":0,"space":"s0","description":"effects=[]"}-{"type":"node","kind":"effect","name":"e1","raw":1,"depth":1,"parent":"e0","space":"s1","description":"mask=[400,20 50x50] kind=alpha origin=css-mask-layers","owner":"BlockContainer<DIV>#masked"}-{"type":"layer","name":"L0","kind":"base","rect":[0,0,800,600],"records":[[2,6]]}-{"type":"layer","name":"L1","kind":"canvas","rect":[17,17,206,126],"records":[[1,1]],"shown_by_the_window_server":"clip=[0,0 800x600]"}-{"type":"record","id":2,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s2","raw":2},"effect":{"name":"e0","raw":0}},"fields":{"rect":[300,20,50,50],"color":"#008000ff"},"owner":"BlockContainer<DIV>#transformed","phase":"background"}-{"type":"record","id":3,"op":"DeclareMaskContent","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"effect":{"name":"e1","raw":1}},"owner":"BlockContainer<DIV>#masked","phase":"preamble"}-{"type":"record","id":4,"op":"PaintLinearGradient","depth":1,"parent":3,"role":"mask-content","layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"gradient_rect":[400,20,50,50],"gradient_angle":180,"color_stops":[{"color":"#000000ff","position":0},{"color":"#00000000","position":1}],"repeat_length":1,"interpolation_method":{"rectangular_color_space":"Srgb"}},"inline_clips":[{"kind":"Rect","rect":[400,20,50,50]}],"owner":"BlockContainer<DIV>#masked","phase":"preamble"}-{"type":"record","id":5,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"color":"#0000ffff"},"owner":"BlockContainer<DIV>#masked","phase":"background"}+{"type":"node","kind":"effect","name":"e1","raw":1,"depth":1,"parent":"e0","space":"s1","description":"mask=[700,20 50x50] kind=alpha origin=css-mask-layers","owner":"BlockContainer<DIV>#masked"}+{"type":"layer","name":"L0","line":"[L0] base space=viewport","records":[[2,5]]}+{"type":"layer","name":"L1","line":"[L1] canvas #0 space=viewport region=[17,17 206x126] shown by the window server: clip=[0,0 800x600]","records":[[1,1]]}+{"type":"layer","name":"L2","line":"[L2] painted space=viewport above L1","records":[[6,6]]}+{"type":"record","id":2,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s2","raw":2},"effect":{"name":"e0","raw":0}},"fields":{"rect":[600,20,50,50],"color":"#008000ff"},"owner":"BlockContainer<DIV>#transformed","phase":"background"}+{"type":"record","id":3,"op":"DeclareMaskContent","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[700,20,50,50],"effect":{"name":"e1","raw":1}},"owner":"BlockContainer<DIV>#masked","phase":"preamble"}+{"type":"record","id":4,"op":"PaintLinearGradient","depth":1,"parent":3,"role":"mask-content","layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"gradient_rect":[700,20,50,50],"gradient_angle":180,"color_stops":[{"color":"#000000ff","position":0},{"color":"#00000000","position":1}],"repeat_length":1,"interpolation_method":{"rectangular_color_space":"Srgb"}},"inline_clips":[{"kind":"Rect","rect":[700,20,50,50]}],"owner":"BlockContainer<DIV>#masked","phase":"preamble"}+{"type":"record","id":5,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[700,20,50,50],"color":"#0000ffff"},"owner":"BlockContainer<DIV>#masked","phase":"background"}{"id":6,"text":"some text","has_font":true,"owner":"BlockContainer<P>","phase":"foreground"}diff --git a/Tests/LibWeb/Text/expected/display_list/mask-image-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/mask-image-invalidation.txtindex 5f04b6a507b..696982446ef 100644--- a/Tests/LibWeb/Text/expected/display_list/mask-image-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/mask-image-invalidation.txt@@ -7,11 +7,14 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] mask=[8,8 100x100] kind=alpha origin=css-mask-layers (BlockContainer<DIV>#box.box)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s1/e1 rect=[8,8 100x100] effect=e1 owner=BlockContainer<DIV>#box.box phase=preamble- PaintLinearGradient@s1/e1 gradient_rect=[8,8 100x100] gradient_angle=180 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x100]] owner=BlockContainer<DIV>#box.box phase=preamble-FillRect@s1/e1 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e1 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 DeclareMaskContent@s1/e1 rect=[8,8 100x100] effect=e1 owner=BlockContainer<DIV>#box.box phase=preamble+ PaintLinearGradient@s1/e1 gradient_rect=[8,8 100x100] gradient_angle=180 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x100]] owner=BlockContainer<DIV>#box.box phase=preamble+L0 FillRect@s1/e1 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e1 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter mask-image removal:AccumulatedVisualContext Tree:@@ -21,9 +24,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 FillRect@s1/e0 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregroundAfter mask-image reinstatement:AccumulatedVisualContext Tree:@@ -34,9 +40,12 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] mask=[8,8 100x100] kind=alpha origin=css-mask-layers (BlockContainer<DIV>#box.box)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s1/e1 rect=[8,8 100x100] effect=e1 owner=BlockContainer<DIV>#box.box phase=preamble- PaintLinearGradient@s1/e1 gradient_rect=[8,8 100x100] gradient_angle=90 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x100]] owner=BlockContainer<DIV>#box.box phase=preamble-FillRect@s1/e1 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background-DrawGlyphRun@s1/e1 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foreground+L0 DeclareMaskContent@s1/e1 rect=[8,8 100x100] effect=e1 owner=BlockContainer<DIV>#box.box phase=preamble+ PaintLinearGradient@s1/e1 gradient_rect=[8,8 100x100] gradient_angle=90 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[8,8 100x100]] owner=BlockContainer<DIV>#box.box phase=preamble+L0 FillRect@s1/e1 rect=[8,8 100x100] color=rgb(173, 216, 230) owner=BlockContainer<DIV>#box.box phase=background+L0 DrawGlyphRun@s1/e1 font_id=font1 glyphs=3 rect=[8,8 30x16] glyph_bounding_rect=[8,8 33x15] translation=[8,21] color=rgb(0, 0, 0) text="Box" owner=BlockContainer<DIV>#box.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/mask-type-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/mask-type-invalidation.txtindex 5ae00d63da1..dbfa77c66eb 100644--- a/Tests/LibWeb/Text/expected/display_list/mask-type-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/mask-type-invalidation.txt@@ -10,10 +10,13 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s2 out=c0] mask=[-10,-10 120x120] kind=alpha origin=svg-mask (SVGGeometryBox<rect>)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg- FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x50] path_data=[path: M0 0L100 0L100 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground-FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg+ FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x50] path_data=[path: M0 0L100 0L100 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foregroundAfter switching to mask-type luminance:AccumulatedVisualContext Tree:@@ -27,8 +30,11 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s2 out=c0] mask=[-10,-10 120x120] kind=luminance origin=svg-mask (SVGGeometryBox<rect>)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg- FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x50] path_data=[path: M0 0L100 0L100 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground-FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg+ FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x50] path_data=[path: M0 0L100 0L100 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/mix-blend-mode-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/mix-blend-mode-invalidation.txtindex 0a65ad5c10b..9e1e9084f69 100644--- a/Tests/LibWeb/Text/expected/display_list/mix-blend-mode-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/mix-blend-mode-invalidation.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgroundAfter mix-blend-mode change:AccumulatedVisualContext Tree:@@ -18,6 +21,10 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[blend_mode=Multiply] (BlockContainer<DIV>#box)+Layers:+ [L0] base space=viewport+ e1 is not composited: it reads only its own layer+DisplayList:-FillRect@s1/e1 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s1/e1 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/mixed-sibling-contexts.txt b/Tests/LibWeb/Text/expected/display_list/mixed-sibling-contexts.txtindex fe128b307d3..6370d572082 100644--- a/Tests/LibWeb/Text/expected/display_list/mixed-sibling-contexts.txt+++ b/Tests/LibWeb/Text/expected/display_list/mixed-sibling-contexts.txt@@ -12,10 +12,15 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[119,9 100x100] min_scroll_offset=[0,0] max_scroll_offset=[50,50] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [119,9 100x100] of viewport+ [L2] painted space=viewport above band 0 of scroller@s2 in viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[118,8 102x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.clipped phase=border-FillRect@s2/c0/e0 rect=[119,9 150x150] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.inner phase=background-DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=7 rect=[119,9 55x16] glyph_bounding_rect=[119,10 60x15] translation=[119,22] color=rgb(0, 0, 0) text="Clipped" owner=BlockContainer<DIV>.inner phase=foreground-FillRect@s3/e0 rect=[8,8 100x100] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.transformed phase=background-DrawGlyphRun@s3/e0 font_id=font1 glyphs=9 rect=[8,8 88x16] glyph_bounding_rect=[8,8 88x15] translation=[8,21] color=rgb(0, 0, 0) text="Transform" owner=BlockContainer<DIV>.transformed phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[118,8 102x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.clipped phase=border+L1 FillRect@s2/c0/e0 rect=[119,9 150x150] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.inner phase=background+L1 DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=7 rect=[119,9 55x16] glyph_bounding_rect=[119,10 60x15] translation=[119,22] color=rgb(0, 0, 0) text="Clipped" owner=BlockContainer<DIV>.inner phase=foreground+L2 FillRect@s3/e0 rect=[8,8 100x100] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.transformed phase=background+L2 DrawGlyphRun@s3/e0 font_id=font1 glyphs=9 rect=[8,8 88x16] glyph_bounding_rect=[8,8 88x15] translation=[8,21] color=rgb(0, 0, 0) text="Transform" owner=BlockContainer<DIV>.transformed phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/multiline-inline-color-change-inside-opacity.txt b/Tests/LibWeb/Text/expected/display_list/multiline-inline-color-change-inside-opacity.txtindex f611df4dcd3..8f7372ae61a 100644--- a/Tests/LibWeb/Text/expected/display_list/multiline-inline-color-change-inside-opacity.txt+++ b/Tests/LibWeb/Text/expected/display_list/multiline-inline-color-change-inside-opacity.txt@@ -7,12 +7,15 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[opacity=0.5] (InlineNode<SPAN>#outer)+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[8,85 46x13] glyph_bounding_rect=[8,85 53x12] translation=[8,95] color=rgb(0, 0, 0) text="Before:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 255) text="This span" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 255) text="spans" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 255) text="multiple" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 255) text="lines" owner=InlineNode<SPAN>#outer phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[8,85 46x13] glyph_bounding_rect=[8,85 53x12] translation=[8,95] color=rgb(0, 0, 0) text="Before:" owner=BlockContainer<PRE>#out phase=foreground+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 255) text="This span" owner=InlineNode<SPAN>#outer phase=text-fragment+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 255) text="spans" owner=InlineNode<SPAN>#outer phase=text-fragment+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 255) text="multiple" owner=InlineNode<SPAN>#outer phase=text-fragment+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 255) text="lines" owner=InlineNode<SPAN>#outer phase=text-fragmentAfter:AccumulatedVisualContext Tree:@@ -24,26 +27,31 @@ AccumulatedVisualContext Tree:[e1 in s1] effects=[opacity=0.5] (InlineNode<SPAN>#outer)ScrollNodes:-ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[539.8594,0] is_viewport=true+ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[562.9844,0] is_viewport=true++Layers:+ [L1] base space=documentDisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[8,85 46x13] glyph_bounding_rect=[8,85 53x12] translation=[8,95] color=rgb(0, 0, 0) text="Before:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=30 rect=[8,98 214x13] glyph_bounding_rect=[8,98 221x12] translation=[8,108] color=rgb(0, 0, 0) text="AccumulatedVisualContext Tree:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[8,111 60x13] glyph_bounding_rect=[8,111 67x12] translation=[8,121] color=rgb(0, 0, 0) text=" spatial:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=67 rect=[8,124 440x13] glyph_bounding_rect=[8,124 446x12] translation=[8,134] color=rgb(0, 0, 0) text=" [s0] transform=[1,0,0,1,0,0] origin=…" text_length=67 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=39 rect=[8,137 264x13] glyph_bounding_rect=[8,137 271x12] translation=[8,147] color=rgb(0, 0, 0) text=" [s1] scroll (Viewport<#document>)" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[8,150 62x13] glyph_bounding_rect=[8,150 69x12] translation=[8,160] color=rgb(0, 0, 0) text=" effects:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=25 rect=[8,163 162x13] glyph_bounding_rect=[8,163 166x12] translation=[8,173] color=rgb(0, 0, 0) text=" [e0 in s0] effects=[]" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=63 rect=[8,176 417x13] glyph_bounding_rect=[8,176 423x12] translation=[8,186] color=rgb(0, 0, 0) text=" [e1 in s1] effects=[opacity=0.5] (…" text_length=63 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=12 rect=[8,202 74x13] glyph_bounding_rect=[8,202 81x12] translation=[8,212] color=rgb(0, 0, 0) text="DisplayList:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=192 rect=[8,215 1307x13] glyph_bounding_rect=[8,215 1311x12] translation=[8,225] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e0 font_id=font1 glyphs=…" text_length=192 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=196 rect=[8,228 1332x13] glyph_bounding_rect=[8,228 1337x12] translation=[8,238] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=196 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=194 rect=[8,241 1315x13] glyph_bounding_rect=[8,241 1319x12] translation=[8,251] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=194 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=197 rect=[8,254 1330x13] glyph_bounding_rect=[8,254 1335x12] translation=[8,264] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=197 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=194 rect=[8,267 1309x13] glyph_bounding_rect=[8,267 1314x12] translation=[8,277] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=194 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,293 40x13] glyph_bounding_rect=[8,293 47x12] translation=[8,303] color=rgb(0, 0, 0) text="After:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(255, 0, 0) text="This span" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(255, 0, 0) text="spans" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(255, 0, 0) text="multiple" owner=InlineNode<SPAN>#outer phase=text-fragment-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(255, 0, 0) text="lines" owner=InlineNode<SPAN>#outer phase=text-fragment+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[8,85 46x13] glyph_bounding_rect=[8,85 53x12] translation=[8,95] color=rgb(0, 0, 0) text="Before:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=30 rect=[8,98 214x13] glyph_bounding_rect=[8,98 221x12] translation=[8,108] color=rgb(0, 0, 0) text="AccumulatedVisualContext Tree:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[8,111 60x13] glyph_bounding_rect=[8,111 67x12] translation=[8,121] color=rgb(0, 0, 0) text=" spatial:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=67 rect=[8,124 440x13] glyph_bounding_rect=[8,124 446x12] translation=[8,134] color=rgb(0, 0, 0) text=" [s0] transform=[1,0,0,1,0,0] origin=…" text_length=67 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=39 rect=[8,137 264x13] glyph_bounding_rect=[8,137 271x12] translation=[8,147] color=rgb(0, 0, 0) text=" [s1] scroll (Viewport<#document>)" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=10 rect=[8,150 62x13] glyph_bounding_rect=[8,150 69x12] translation=[8,160] color=rgb(0, 0, 0) text=" effects:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=25 rect=[8,163 162x13] glyph_bounding_rect=[8,163 166x12] translation=[8,173] color=rgb(0, 0, 0) text=" [e0 in s0] effects=[]" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=63 rect=[8,176 417x13] glyph_bounding_rect=[8,176 423x12] translation=[8,186] color=rgb(0, 0, 0) text=" [e1 in s1] effects=[opacity=0.5] (…" text_length=63 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[8,202 48x13] glyph_bounding_rect=[8,202 55x12] translation=[8,212] color=rgb(0, 0, 0) text="Layers:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=26 rect=[8,215 183x13] glyph_bounding_rect=[8,215 188x12] translation=[8,225] color=rgb(0, 0, 0) text=" [L0] base space=viewport" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=12 rect=[8,241 74x13] glyph_bounding_rect=[8,241 81x12] translation=[8,251] color=rgb(0, 0, 0) text="DisplayList:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=195 rect=[8,254 1330x13] glyph_bounding_rect=[8,254 1334x12] translation=[8,264] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e0 font_id=font1 glyp…" text_length=195 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=199 rect=[8,267 1355x13] glyph_bounding_rect=[8,267 1360x12] translation=[8,277] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=199 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=197 rect=[8,280 1338x13] glyph_bounding_rect=[8,280 1342x12] translation=[8,290] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=197 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=200 rect=[8,293 1353x13] glyph_bounding_rect=[8,293 1358x12] translation=[8,303] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=200 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=197 rect=[8,306 1332x13] glyph_bounding_rect=[8,306 1337x12] translation=[8,316] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=197 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,332 40x13] glyph_bounding_rect=[8,332 47x12] translation=[8,342] color=rgb(0, 0, 0) text="After:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(255, 0, 0) text="This span" owner=InlineNode<SPAN>#outer phase=text-fragment+L1 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(255, 0, 0) text="spans" owner=InlineNode<SPAN>#outer phase=text-fragment+L1 DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(255, 0, 0) text="multiple" owner=InlineNode<SPAN>#outer phase=text-fragment+L1 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(255, 0, 0) text="lines" owner=InlineNode<SPAN>#outer phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/multiline-inline-opacity.txt b/Tests/LibWeb/Text/expected/display_list/multiline-inline-opacity.txtindex fb7a12c24bf..ca211f28826 100644--- a/Tests/LibWeb/Text/expected/display_list/multiline-inline-opacity.txt+++ b/Tests/LibWeb/Text/expected/display_list/multiline-inline-opacity.txt@@ -7,16 +7,19 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s1] effects=[opacity=0.5] (InlineNode<SPAN>#target)+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=13 rect=[8,85 83x13] glyph_bounding_rect=[8,85 91x12] translation=[8,95] color=rgb(0, 0, 0) text="With opacity:" owner=BlockContainer<PRE>#out phase=foreground-FillRect@s1/e1 rect=[8,8 81x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece-DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 0) text="This span" owner=InlineNode<SPAN>#target phase=text-fragment-FillRect@s1/e1 rect=[8,24 47x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 0) text="spans" owner=InlineNode<SPAN>#target phase=text-fragment-FillRect@s1/e1 rect=[8,40 60x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece-DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 0) text="multiple" owner=InlineNode<SPAN>#target phase=text-fragment-FillRect@s1/e1 rect=[8,56 36x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece-DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 0) text="lines" owner=InlineNode<SPAN>#target phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=13 rect=[8,85 83x13] glyph_bounding_rect=[8,85 91x12] translation=[8,95] color=rgb(0, 0, 0) text="With opacity:" owner=BlockContainer<PRE>#out phase=foreground+L0 FillRect@s1/e1 rect=[8,8 81x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 0) text="This span" owner=InlineNode<SPAN>#target phase=text-fragment+L0 FillRect@s1/e1 rect=[8,24 47x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 0) text="spans" owner=InlineNode<SPAN>#target phase=text-fragment+L0 FillRect@s1/e1 rect=[8,40 60x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 0) text="multiple" owner=InlineNode<SPAN>#target phase=text-fragment+L0 FillRect@s1/e1 rect=[8,56 36x16] color=rgb(255, 165, 0) owner=InlineNode<SPAN>#target phase=inline-piece+L0 DrawGlyphRun@s1/e1 font_id=font2 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 0) text="lines" owner=InlineNode<SPAN>#target phase=text-fragmentWithout opacity:AccumulatedVisualContext Tree:@@ -27,34 +30,39 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]ScrollNodes:-ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[557.0625,0] is_viewport=true+ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[580.1875,0] is_viewport=true++Layers:+ [L1] base space=documentDisplayList:-FillRect@s1/e0 rect=[8,8 81x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 0) text="This span" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,24 47x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 0) text="spans" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,40 60x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 0) text="multiple" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,56 36x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 0) text="lines" owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font2 glyphs=13 rect=[8,85 83x13] glyph_bounding_rect=[8,85 91x12] translation=[8,95] color=rgb(0, 0, 0) text="With opacity:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=30 rect=[8,98 214x13] glyph_bounding_rect=[8,98 221x12] translation=[8,108] color=rgb(0, 0, 0) text="AccumulatedVisualContext Tree:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=10 rect=[8,111 60x13] glyph_bounding_rect=[8,111 67x12] translation=[8,121] color=rgb(0, 0, 0) text=" spatial:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=67 rect=[8,124 440x13] glyph_bounding_rect=[8,124 446x12] translation=[8,134] color=rgb(0, 0, 0) text=" [s0] transform=[1,0,0,1,0,0] origin=…" text_length=67 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=39 rect=[8,137 264x13] glyph_bounding_rect=[8,137 271x12] translation=[8,147] color=rgb(0, 0, 0) text=" [s1] scroll (Viewport<#document>)" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=10 rect=[8,150 62x13] glyph_bounding_rect=[8,150 69x12] translation=[8,160] color=rgb(0, 0, 0) text=" effects:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=25 rect=[8,163 162x13] glyph_bounding_rect=[8,163 166x12] translation=[8,173] color=rgb(0, 0, 0) text=" [e0 in s0] effects=[]" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=64 rect=[8,176 419x13] glyph_bounding_rect=[8,176 426x12] translation=[8,186] color=rgb(0, 0, 0) text=" [e1 in s1] effects=[opacity=0.5] (…" text_length=64 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=12 rect=[8,202 74x13] glyph_bounding_rect=[8,202 81x12] translation=[8,212] color=rgb(0, 0, 0) text="DisplayList:" owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=199 rect=[8,215 1350x13] glyph_bounding_rect=[8,215 1354x12] translation=[8,225] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e0 font_id=font1 glyphs=…" text_length=199 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=103 rect=[8,228 686x13] glyph_bounding_rect=[8,228 690x12] translation=[8,238] color=rgb(0, 0, 0) text="FillRect@s1/e1 rect=[8,8 81x16] color=rg…" text_length=103 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=195 rect=[8,241 1322x13] glyph_bounding_rect=[8,241 1327x12] translation=[8,251] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=195 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=104 rect=[8,254 693x13] glyph_bounding_rect=[8,254 696x12] translation=[8,264] color=rgb(0, 0, 0) text="FillRect@s1/e1 rect=[8,24 47x16] color=r…" text_length=104 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=193 rect=[8,267 1304x13] glyph_bounding_rect=[8,267 1309x12] translation=[8,277] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=193 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=104 rect=[8,280 695x13] glyph_bounding_rect=[8,280 698x12] translation=[8,290] color=rgb(0, 0, 0) text="FillRect@s1/e1 rect=[8,40 60x16] color=r…" text_length=104 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=196 rect=[8,293 1320x13] glyph_bounding_rect=[8,293 1324x12] translation=[8,303] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=196 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=104 rect=[8,306 694x13] glyph_bounding_rect=[8,306 698x12] translation=[8,316] color=rgb(0, 0, 0) text="FillRect@s1/e1 rect=[8,56 36x16] color=r…" text_length=104 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=193 rect=[8,319 1299x13] glyph_bounding_rect=[8,319 1304x12] translation=[8,329] color=rgb(0, 0, 0) text="DrawGlyphRun@s1/e1 font_id=font2 glyphs=…" text_length=193 owner=BlockContainer<PRE>#out phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=16 rect=[8,345 105x13] glyph_bounding_rect=[8,345 113x12] translation=[8,355] color=rgb(0, 0, 0) text="Without opacity:" owner=BlockContainer<PRE>#out phase=foreground+L1 FillRect@s1/e0 rect=[8,8 81x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 82x16] glyph_bounding_rect=[8,8 85x15] translation=[8,21] color=rgb(0, 0, 0) text="This span" owner=BlockContainer<DIV> phase=text-fragment+L1 FillRect@s1/e0 rect=[8,24 47x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 0) text="spans" owner=BlockContainer<DIV> phase=text-fragment+L1 FillRect@s1/e0 rect=[8,40 60x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 0) text="multiple" owner=BlockContainer<DIV> phase=text-fragment+L1 FillRect@s1/e0 rect=[8,56 36x16] color=rgb(255, 165, 0) owner=BlockContainer<DIV> phase=inline-piece+L1 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 0) text="lines" owner=BlockContainer<DIV> phase=text-fragment+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=13 rect=[8,85 83x13] glyph_bounding_rect=[8,85 91x12] translation=[8,95] color=rgb(0, 0, 0) text="With opacity:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=30 rect=[8,98 214x13] glyph_bounding_rect=[8,98 221x12] translation=[8,108] color=rgb(0, 0, 0) text="AccumulatedVisualContext Tree:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=10 rect=[8,111 60x13] glyph_bounding_rect=[8,111 67x12] translation=[8,121] color=rgb(0, 0, 0) text=" spatial:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=67 rect=[8,124 440x13] glyph_bounding_rect=[8,124 446x12] translation=[8,134] color=rgb(0, 0, 0) text=" [s0] transform=[1,0,0,1,0,0] origin=…" text_length=67 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=39 rect=[8,137 264x13] glyph_bounding_rect=[8,137 271x12] translation=[8,147] color=rgb(0, 0, 0) text=" [s1] scroll (Viewport<#document>)" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=10 rect=[8,150 62x13] glyph_bounding_rect=[8,150 69x12] translation=[8,160] color=rgb(0, 0, 0) text=" effects:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=25 rect=[8,163 162x13] glyph_bounding_rect=[8,163 166x12] translation=[8,173] color=rgb(0, 0, 0) text=" [e0 in s0] effects=[]" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=64 rect=[8,176 419x13] glyph_bounding_rect=[8,176 426x12] translation=[8,186] color=rgb(0, 0, 0) text=" [e1 in s1] effects=[opacity=0.5] (…" text_length=64 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=7 rect=[8,202 48x13] glyph_bounding_rect=[8,202 55x12] translation=[8,212] color=rgb(0, 0, 0) text="Layers:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=26 rect=[8,215 183x13] glyph_bounding_rect=[8,215 188x12] translation=[8,225] color=rgb(0, 0, 0) text=" [L0] base space=viewport" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=12 rect=[8,241 74x13] glyph_bounding_rect=[8,241 81x12] translation=[8,251] color=rgb(0, 0, 0) text="DisplayList:" owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=202 rect=[8,254 1373x13] glyph_bounding_rect=[8,254 1377x12] translation=[8,264] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e0 font_id=font1 glyp…" text_length=202 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=106 rect=[8,267 709x13] glyph_bounding_rect=[8,267 713x12] translation=[8,277] color=rgb(0, 0, 0) text="L0 FillRect@s1/e1 rect=[8,8 81x16] color…" text_length=106 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=198 rect=[8,280 1345x13] glyph_bounding_rect=[8,280 1350x12] translation=[8,290] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=198 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=107 rect=[8,293 716x13] glyph_bounding_rect=[8,293 719x12] translation=[8,303] color=rgb(0, 0, 0) text="L0 FillRect@s1/e1 rect=[8,24 47x16] colo…" text_length=107 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=196 rect=[8,306 1328x13] glyph_bounding_rect=[8,306 1332x12] translation=[8,316] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=196 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=107 rect=[8,319 718x13] glyph_bounding_rect=[8,319 721x12] translation=[8,329] color=rgb(0, 0, 0) text="L0 FillRect@s1/e1 rect=[8,40 60x16] colo…" text_length=107 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=199 rect=[8,332 1343x13] glyph_bounding_rect=[8,332 1348x12] translation=[8,342] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=199 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=107 rect=[8,345 717x13] glyph_bounding_rect=[8,345 721x12] translation=[8,355] color=rgb(0, 0, 0) text="L0 FillRect@s1/e1 rect=[8,56 36x16] colo…" text_length=107 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=196 rect=[8,358 1322x13] glyph_bounding_rect=[8,358 1327x12] translation=[8,368] color=rgb(0, 0, 0) text="L0 DrawGlyphRun@s1/e1 font_id=font2 glyp…" text_length=196 owner=BlockContainer<PRE>#out phase=foreground+L1 DrawGlyphRun@s1/e0 font_id=font2 glyphs=16 rect=[8,384 105x13] glyph_bounding_rect=[8,384 113x12] translation=[8,394] color=rgb(0, 0, 0) text="Without opacity:" owner=BlockContainer<PRE>#out phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/multiline-inline-paint-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/multiline-inline-paint-invalidation.txtindex 251b854f041..256c32fcb4b 100644--- a/Tests/LibWeb/Text/expected/display_list/multiline-inline-paint-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/multiline-inline-paint-invalidation.txt@@ -6,15 +6,18 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 70x16] glyph_bounding_rect=[8,8 75x15] translation=[8,21] color=rgb(0, 0, 255) text="This link" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,23 70x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 255) text="spans" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,39 47x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 255) text="multiple" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,55 60x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 255) text="lines" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,71 36x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 70x16] glyph_bounding_rect=[8,8 75x15] translation=[8,21] color=rgb(0, 0, 255) text="This link" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,23 70x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(0, 0, 255) text="spans" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,39 47x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(0, 0, 255) text="multiple" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,55 60x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(0, 0, 255) text="lines" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,71 36x2] color=rgb(0, 0, 255) owner=BlockContainer<DIV> phase=text-fragmentAfter:AccumulatedVisualContext Tree:@@ -24,13 +27,16 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 70x16] glyph_bounding_rect=[8,8 75x15] translation=[8,21] color=rgb(255, 0, 0) text="This link" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,23 70x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(255, 0, 0) text="spans" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,39 47x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(255, 0, 0) text="multiple" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,55 60x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(255, 0, 0) text="lines" owner=BlockContainer<DIV> phase=text-fragment-FillRect@s1/e0 rect=[8,71 36x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,8 70x16] glyph_bounding_rect=[8,8 75x15] translation=[8,21] color=rgb(255, 0, 0) text="This link" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,23 70x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,24 48x16] glyph_bounding_rect=[8,24 51x15] translation=[8,37] color=rgb(255, 0, 0) text="spans" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,39 47x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[8,40 60x16] glyph_bounding_rect=[8,40 65x15] translation=[8,53] color=rgb(255, 0, 0) text="multiple" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,55 60x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,56 37x16] glyph_bounding_rect=[8,56 40x15] translation=[8,69] color=rgb(255, 0, 0) text="lines" owner=BlockContainer<DIV> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,71 36x2] color=rgb(255, 0, 0) owner=BlockContainer<DIV> phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/nested-branches.txt b/Tests/LibWeb/Text/expected/display_list/nested-branches.txtindex 2c2ea1790ec..ca9ee7cae3d 100644--- a/Tests/LibWeb/Text/expected/display_list/nested-branches.txt+++ b/Tests/LibWeb/Text/expected/display_list/nested-branches.txt@@ -13,16 +13,19 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 324x274] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.level1 phase=border-FillRoundedRectRing@s1/c0/e0 rect=[20,20 145x250] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.level2 phase=border-FillRoundedRectRing@s1/c0/e0 rect=[175,20 145x250] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.level2 phase=border-FillRect@s2/c1/e0 rect=[26,26 133x40] color=rgb(255, 136, 136) owner=BlockContainer<DIV>.level3.t1 phase=background-DrawGlyphRun@s2/c1/e0 font_id=font1 glyphs=3 rect=[26,26 20x16] glyph_bounding_rect=[26,26 26x15] translation=[26,39] color=rgb(0, 0, 0) text="1-1" owner=BlockContainer<DIV>.level3.t1 phase=foreground-FillRect@s3/c1/e0 rect=[26,71 133x40] color=rgb(136, 255, 136) owner=BlockContainer<DIV>.level3.t2 phase=background-DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=3 rect=[26,71 22x16] glyph_bounding_rect=[26,72 26x15] translation=[26,84] color=rgb(0, 0, 0) text="1-2" owner=BlockContainer<DIV>.level3.t2 phase=foreground-FillRect@s4/c2/e0 rect=[181,26 133x40] color=rgb(136, 136, 255) owner=BlockContainer<DIV>.level3.t3 phase=background-DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=3 rect=[181,26 22x16] glyph_bounding_rect=[181,26 29x15] translation=[181,39] color=rgb(0, 0, 0) text="2-1" owner=BlockContainer<DIV>.level3.t3 phase=foreground-FillRect@s5/c2/e0 rect=[181,71 133x40] color=rgb(255, 255, 136) owner=BlockContainer<DIV>.level3.t4 phase=background-DrawGlyphRun@s5/c2/e0 font_id=font1 glyphs=3 rect=[181,71 25x16] glyph_bounding_rect=[181,72 29x15] translation=[181,84] color=rgb(0, 0, 0) text="2-2" owner=BlockContainer<DIV>.level3.t4 phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[8,8 324x274] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.level1 phase=border+L0 FillRoundedRectRing@s1/c0/e0 rect=[20,20 145x250] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.level2 phase=border+L0 FillRoundedRectRing@s1/c0/e0 rect=[175,20 145x250] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(128, 128, 128) owner=BlockContainer<DIV>.level2 phase=border+L0 FillRect@s2/c1/e0 rect=[26,26 133x40] color=rgb(255, 136, 136) owner=BlockContainer<DIV>.level3.t1 phase=background+L0 DrawGlyphRun@s2/c1/e0 font_id=font1 glyphs=3 rect=[26,26 20x16] glyph_bounding_rect=[26,26 26x15] translation=[26,39] color=rgb(0, 0, 0) text="1-1" owner=BlockContainer<DIV>.level3.t1 phase=foreground+L0 FillRect@s3/c1/e0 rect=[26,71 133x40] color=rgb(136, 255, 136) owner=BlockContainer<DIV>.level3.t2 phase=background+L0 DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=3 rect=[26,71 22x16] glyph_bounding_rect=[26,72 26x15] translation=[26,84] color=rgb(0, 0, 0) text="1-2" owner=BlockContainer<DIV>.level3.t2 phase=foreground+L0 FillRect@s4/c2/e0 rect=[181,26 133x40] color=rgb(136, 136, 255) owner=BlockContainer<DIV>.level3.t3 phase=background+L0 DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=3 rect=[181,26 22x16] glyph_bounding_rect=[181,26 29x15] translation=[181,39] color=rgb(0, 0, 0) text="2-1" owner=BlockContainer<DIV>.level3.t3 phase=foreground+L0 FillRect@s5/c2/e0 rect=[181,71 133x40] color=rgb(255, 255, 136) owner=BlockContainer<DIV>.level3.t4 phase=background+L0 DrawGlyphRun@s5/c2/e0 font_id=font1 glyphs=3 rect=[181,71 25x16] glyph_bounding_rect=[181,72 29x15] translation=[181,84] color=rgb(0, 0, 0) text="2-2" owner=BlockContainer<DIV>.level3.t4 phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/nested-overflow-containers.txt b/Tests/LibWeb/Text/expected/display_list/nested-overflow-containers.txtindex 12446bebf51..f9c351ed77a 100644--- a/Tests/LibWeb/Text/expected/display_list/nested-overflow-containers.txt+++ b/Tests/LibWeb/Text/expected/display_list/nested-overflow-containers.txt@@ -14,20 +14,27 @@ ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[10,10 200x150] min_scroll_offset=[0,0] max_scroll_offset=[102,0] is_viewport=falseScrollNode scroll_node_index=s3 parent_scroll_node_index=s2 scrollport_rect=[11,11 300x100] min_scroll_offset=[0,0] max_scroll_offset=[100,0] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [10,10 200x150] of viewport+ [L2] painted space=scroller@s3 in scroller@s2 in viewport composited within [10,10 200x150] of viewport composited within [11,11 300x100] of scroller@s2 in viewport+ [L3] painted space=scroller@s2 in viewport above band 0 of scroller@s3 in scroller@s2 in viewport composited within [10,10 200x150] of viewport+ [L4] painted space=viewport above band 0 of scroller@s2 in viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x175] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x154] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[8,8 204x154] owner=BlockContainer<DIV>.outer-scroll phase=scroll-metadata-FillRoundedRectRing@s1/e0 rect=[8,8 204x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.outer-scroll phase=border-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s3 rect=[10,10 302x102] owner=BlockContainer<DIV>.inner-scroll phase=scroll-metadata-FillRect@s2/c0/e0 rect=[10,10 302x102] color=rgb(255, 255, 224) owner=BlockContainer<DIV>.inner-scroll phase=background-FillRoundedRectRing@s2/c0/e0 rect=[10,10 302x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.inner-scroll phase=border-CompositorWheelHitTestTarget@s3/c1/e0 target_scroll_node_index=s3 rect=[11,11 400x80] owner=BlockContainer<DIV>.content phase=scroll-metadata-FillRect@s3/c1/e0 rect=[11,11 400x80] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.content phase=background-DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=21 rect=[11,11 178x16] glyph_bounding_rect=[11,12 184x15] translation=[11,24] color=rgb(0, 0, 0) text="Deeply nested content" owner=BlockContainer<DIV>.content phase=foreground-CompositorScrollbar@s2/c0/e0 scroll_node_index=s3 thumb_rect=[13,102 222x7] track_rect=[11,102 300x9] expanded_gutter_rect=[11,96 300x15] expanded_thumb_rect=[13,98 222x11] scroll_size=0.74 expanded_scroll_size=0.74 max_scroll_offset=100 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.inner-scroll phase=overlay-PaintScrollBar@s2/c0/e0 scroll_node_index=s3 thumb_rect=[13,102 222x7] track_rect=[11,102 300x9] expanded_gutter_rect=[11,96 300x15] scroll_size=0.74 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.inner-scroll phase=overlay-CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[12,151 130x7] track_rect=[10,151 200x9] expanded_gutter_rect=[10,145 200x15] expanded_thumb_rect=[12,147 130x11] scroll_size=0.6490502450980392 expanded_scroll_size=0.6490502450980392 max_scroll_offset=102 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.outer-scroll phase=overlay-PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[12,151 130x7] track_rect=[10,151 200x9] expanded_gutter_rect=[10,145 200x15] scroll_size=0.6490502450980392 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.outer-scroll phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x175] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x154] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[8,8 204x154] owner=BlockContainer<DIV>.outer-scroll phase=scroll-metadata+L0 FillRoundedRectRing@s1/e0 rect=[8,8 204x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.outer-scroll phase=border+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s3 rect=[10,10 302x102] owner=BlockContainer<DIV>.inner-scroll phase=scroll-metadata+L1 FillRect@s2/c0/e0 rect=[10,10 302x102] color=rgb(255, 255, 224) owner=BlockContainer<DIV>.inner-scroll phase=background+L1 FillRoundedRectRing@s2/c0/e0 rect=[10,10 302x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.inner-scroll phase=border+L0 CompositorWheelHitTestTarget@s3/c1/e0 target_scroll_node_index=s3 rect=[11,11 400x80] owner=BlockContainer<DIV>.content phase=scroll-metadata+L2 FillRect@s3/c1/e0 rect=[11,11 400x80] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.content phase=background+L2 DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=21 rect=[11,11 178x16] glyph_bounding_rect=[11,12 184x15] translation=[11,24] color=rgb(0, 0, 0) text="Deeply nested content" owner=BlockContainer<DIV>.content phase=foreground+L0 CompositorScrollbar@s2/c0/e0 scroll_node_index=s3 thumb_rect=[13,102 222x7] track_rect=[11,102 300x9] expanded_gutter_rect=[11,96 300x15] expanded_thumb_rect=[13,98 222x11] scroll_size=0.74 expanded_scroll_size=0.74 max_scroll_offset=100 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.inner-scroll phase=overlay+L3 PaintScrollBar@s2/c0/e0 scroll_node_index=s3 thumb_rect=[13,102 222x7] track_rect=[11,102 300x9] expanded_gutter_rect=[11,96 300x15] scroll_size=0.74 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.inner-scroll phase=overlay+L0 CompositorScrollbar@s1/e0 scroll_node_index=s2 thumb_rect=[12,151 130x7] track_rect=[10,151 200x9] expanded_gutter_rect=[10,145 200x15] expanded_thumb_rect=[12,147 130x11] scroll_size=0.6490502450980392 expanded_scroll_size=0.6490502450980392 max_scroll_offset=102 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.outer-scroll phase=overlay+L4 PaintScrollBar@s1/e0 scroll_node_index=s2 thumb_rect=[12,151 130x7] track_rect=[10,151 200x9] expanded_gutter_rect=[10,145 200x15] scroll_size=0.6490502450980392 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.outer-scroll phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/opaque-background-image-blend.txt b/Tests/LibWeb/Text/expected/display_list/opaque-background-image-blend.txtindex db4283be55a..5a4fe1bf572 100644--- a/Tests/LibWeb/Text/expected/display_list/opaque-background-image-blend.txt+++ b/Tests/LibWeb/Text/expected/display_list/opaque-background-image-blend.txt@@ -5,7 +5,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[0,0 40x40] color=rgb(45, 22, 0) owner=BlockContainer<DIV>#target phase=background-DrawScaledDecodedImageFrame@s1/e0 dst_rect=[0,0 40x40] src_rect=[0,0 40x40] frame_id=image1 scaling_mode=Bilinear compositing_and_blending_operator=Multiply isolated_backdrop_color=rgb(45, 22, 0) inline_clips=[clip=[0,0 40x40]] owner=BlockContainer<DIV>#target phase=background+L0 FillRect@s1/e0 rect=[0,0 40x40] color=rgb(45, 22, 0) owner=BlockContainer<DIV>#target phase=background+L0 DrawScaledDecodedImageFrame@s1/e0 dst_rect=[0,0 40x40] src_rect=[0,0 40x40] frame_id=image1 scaling_mode=Bilinear compositing_and_blending_operator=Multiply isolated_backdrop_color=rgb(45, 22, 0) inline_clips=[clip=[0,0 40x40]] owner=BlockContainer<DIV>#target phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/page-focus-rendering.txt b/Tests/LibWeb/Text/expected/display_list/page-focus-rendering.txtindex d4025e1dfc4..ed1205191f3 100644--- a/Tests/LibWeb/Text/expected/display_list/page-focus-rendering.txt+++ b/Tests/LibWeb/Text/expected/display_list/page-focus-rendering.txt@@ -8,21 +8,24 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground-FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-FillRect@s1/e0 rect=[0,23 23x16] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV>#txt phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground+L0 FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 FillRect@s1/e0 rect=[0,23 23x16] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV>#txt phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground-- unfocused --AccumulatedVisualContext Tree:@@ -34,20 +37,23 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground-FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(16, 16, 16, 0.667) owner=BlockContainer<DIV> phase=foreground-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-FillRect@s1/e0 rect=[0,23 23x16] color=rgba(16, 16, 16, 0.667) owner=BlockContainer<DIV>#txt phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground+L0 FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(16, 16, 16, 0.667) owner=BlockContainer<DIV> phase=foreground+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 FillRect@s1/e0 rect=[0,23 23x16] color=rgba(16, 16, 16, 0.667) owner=BlockContainer<DIV>#txt phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground-- focused again --AccumulatedVisualContext Tree:@@ -59,21 +65,24 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground-FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-FillRect@s1/e0 rect=[0,23 23x16] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV>#txt phase=foreground-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[3,4 8x12]] text="a" owner=BlockContainer<DIV> phase=foreground+L0 FillRect@s1/c0/e0 rect=[11,3 15x14] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) inline_clips=[clip=[11,4 15x12]] text="bc" owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 FillRect@s1/e0 rect=[0,23 23x16] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV>#txt phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground-- caret, focused --AccumulatedVisualContext Tree:@@ -85,19 +94,22 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground-PaintCaret@s1/c0/e0 rect=[19,3 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground+L0 PaintCaret@s1/c0/e0 rect=[19,3 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground-- caret, unfocused --AccumulatedVisualContext Tree:@@ -109,17 +121,20 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground-- caret, focused again --AccumulatedVisualContext Tree:@@ -131,17 +146,20 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background-FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground-PaintCaret@s1/c0/e0 rect=[19,3 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay-DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foreground+L0 FillRectWithRoundedCorners@s1/e0 rect=[0,0 70x20] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA>#ta phase=background+L0 FillRoundedRectRing@s1/e0 rect=[0,0 70x20] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA>#ta phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=3 rect=[3,3 24x14] glyph_bounding_rect=[3,4 27x12] translation=[3,14] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground+L0 PaintCaret@s1/c0/e0 rect=[19,3 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[-2,-2 74x24] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA>#ta phase=outline+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[65,17] to=[67,15] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[64,17] to=[67,14] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[62,17] to=[67,12] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[61,17] to=[67,11] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[59,17] to=[67,9] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[58,17] to=[67,8] thickness=1 owner=TextAreaBox<TEXTAREA>#ta phase=overlay+L0 DrawGlyphRun@s1/e0 font_id=font2 glyphs=3 rect=[0,23 24x16] glyph_bounding_rect=[0,24 30x15] translation=[0,36] color=rgb(0, 0, 0) text="def" owner=BlockContainer<DIV>#txt phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/patterned-border-on-a-short-side.txt b/Tests/LibWeb/Text/expected/display_list/patterned-border-on-a-short-side.txtindex 0c5befeb070..81ee468f0ba 100644--- a/Tests/LibWeb/Text/expected/display_list/patterned-border-on-a-short-side.txt+++ b/Tests/LibWeb/Text/expected/display_list/patterned-border-on-a-short-side.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s1/e0 path_bounding_rect=[8,31 40x40] path_data=[path: M8 31L8 31L28 51L28 51L48 31L48 31M48 31L48 31L28 51L28 51L48 71L48 71M48 71L48 71L28 51L28 51L8 71L8 71M8 71L8 71L28 51L28 51L8 31L8 31] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[8,71 40x40] path_data=[path: M8 71L8 71L28 91L28 91L48 71L48 71M48 71L48 71L28 91L28 91L48 111L48 111M48 111L48 111L28 91L28 91L8 111L8 111M8 111L8 111L28 91L28 91L8 71L8 71] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.dotted phase=border-FillPath@s1/e0 path_bounding_rect=[8,8 40x20] path_data=[path: M8 8L8 8L28 28L28 28L48 8L48 8] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<SPAN> phase=border-FillPath@s1/e0 path_bounding_rect=[48,8 40x20] path_data=[path: M48 8L48 8L68 28L68 28L88 8L88 8] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<SPAN>.dotted-top phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,31 40x40] path_data=[path: M8 31L8 31L28 51L28 51L48 31L48 31M48 31L48 31L28 51L28 51L48 71L48 71M48 71L48 71L28 51L28 51L8 71L8 71M8 71L8 71L28 51L28 51L8 31L8 31] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,71 40x40] path_data=[path: M8 71L8 71L28 91L28 91L48 71L48 71M48 71L48 71L28 91L28 91L48 111L48 111M48 111L48 111L28 91L28 91L8 111L8 111M8 111L8 111L28 91L28 91L8 71L8 71] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.dotted phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,8 40x20] path_data=[path: M8 8L8 8L28 28L28 28L48 8L48 8] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<SPAN> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[48,8 40x20] path_data=[path: M48 8L48 8L68 28L68 28L88 8L88 8] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<SPAN>.dotted-top phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/patterned-border-sharing-corners.txt b/Tests/LibWeb/Text/expected/display_list/patterned-border-sharing-corners.txtindex 78bcc28a091..8e59b63fa47 100644--- a/Tests/LibWeb/Text/expected/display_list/patterned-border-sharing-corners.txt+++ b/Tests/LibWeb/Text/expected/display_list/patterned-border-sharing-corners.txt@@ -5,16 +5,19 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,8 160x20] path_data=[path: M8 18L148 18] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,8 140x20], path: M8 8L8 8L28 28L128 28L148 8L148 8] winding_rule=EvenOdd] owner=BlockContainer<DIV> phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,28 160x20] path_data=[path: M8 38L148 38] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,28 140x20], path: M8 28L8 28L28 48L128 48L148 28L148 28] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted phase=border-StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[128,38 20x120] path_data=[path: M138 48L138 148] color=rgb(0, 0, 255) thickness=20 inline_clips=[clip_path=[bounds: [128,48 20x100], path: M148 48L148 48L128 68L128 128L148 148L148 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,128 160x20] path_data=[path: M148 138L8 138] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,128 140x20], path: M148 148L148 148L128 128L28 128L8 148L8 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[8,38 20x120] path_data=[path: M18 148L18 48] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,48 20x100], path: M8 148L8 148L28 128L28 68L8 48L8 48] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,48 160x20] path_data=[path: M8 58L148 58] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,48 140x20], path: M8 48L8 48L28 68L128 68L148 48L148 48] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 33.333332] dash_offset=16.666666 path_bounding_rect=[128,138 20x120] path_data=[path: M138 148L138 248] color=rgb(0, 0, 255) thickness=20 inline_clips=[clip_path=[bounds: [128,148 20x100], path: M148 148L148 148L128 168L128 228L148 248L148 248] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,228 160x20] path_data=[path: M148 238L8 238] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,228 140x20], path: M148 248L148 248L128 228L28 228L8 248L8 248] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 33.333332] dash_offset=16.666666 path_bounding_rect=[8,138 20x120] path_data=[path: M18 248L18 148] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,148 20x100], path: M8 248L8 248L28 228L28 168L8 148L8 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border-StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,148 160x20] path_data=[path: M8 158L148 158] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,148 140x20], path: M8 148L8 148L28 168L128 168L148 148L148 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border-StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[-2,248 120x20] path_data=[path: M108 258L8 258] color=rgb(255, 0, 0) thickness=20 owner=BlockContainer<DIV>.no-neighbours phase=border+L0 StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,8 160x20] path_data=[path: M8 18L148 18] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,8 140x20], path: M8 8L8 8L28 28L128 28L148 8L148 8] winding_rule=EvenOdd] owner=BlockContainer<DIV> phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,28 160x20] path_data=[path: M8 38L148 38] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,28 140x20], path: M8 28L8 28L28 48L128 48L148 28L148 28] winding_rule=EvenOdd] owner=BlockContainer<DIV>.dotted phase=border+L0 StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[128,38 20x120] path_data=[path: M138 48L138 148] color=rgb(0, 0, 255) thickness=20 inline_clips=[clip_path=[bounds: [128,48 20x100], path: M148 48L148 48L128 68L128 128L148 148L148 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,128 160x20] path_data=[path: M148 138L8 138] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,128 140x20], path: M148 148L148 148L128 128L28 128L8 148L8 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[8,38 20x120] path_data=[path: M18 148L18 48] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,48 20x100], path: M8 148L8 148L28 128L28 68L8 48L8 48] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 dash_array=[35, 35] dash_offset=17.5 path_bounding_rect=[-2,48 160x20] path_data=[path: M8 58L148 58] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,48 140x20], path: M8 48L8 48L28 68L128 68L148 48L148 48] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 33.333332] dash_offset=16.666666 path_bounding_rect=[128,138 20x120] path_data=[path: M138 148L138 248] color=rgb(0, 0, 255) thickness=20 inline_clips=[clip_path=[bounds: [128,148 20x100], path: M148 148L148 148L128 168L128 228L148 248L148 248] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,228 160x20] path_data=[path: M148 238L8 238] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,228 140x20], path: M148 248L148 248L128 228L28 228L8 248L8 248] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 33.333332] dash_offset=16.666666 path_bounding_rect=[8,138 20x120] path_data=[path: M18 248L18 148] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,148 20x100], path: M8 248L8 248L28 228L28 168L8 148L8 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border+L0 StrokePath@s1/e0 cap_style=Round dash_array=[0, 35] dash_offset=17.5 path_bounding_rect=[-2,148 160x20] path_data=[path: M8 158L148 158] color=rgb(255, 0, 0) thickness=20 inline_clips=[clip_path=[bounds: [8,148 140x20], path: M8 148L8 148L28 168L128 168L148 148L148 148] winding_rule=EvenOdd] owner=BlockContainer<DIV>.mixed-colors.dotted phase=border+L0 StrokePath@s1/e0 dash_array=[50, 50] dash_offset=25 path_bounding_rect=[-2,248 120x20] path_data=[path: M108 258L8 258] color=rgb(255, 0, 0) thickness=20 owner=BlockContainer<DIV>.no-neighbours phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/perspective-basic.txt b/Tests/LibWeb/Text/expected/display_list/perspective-basic.txtindex 126ef0b107d..4c717ca0113 100644--- a/Tests/LibWeb/Text/expected/display_list/perspective-basic.txt+++ b/Tests/LibWeb/Text/expected/display_list/perspective-basic.txt@@ -7,7 +7,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s3/e0 rect=[8,8 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.rotated phase=background-DrawGlyphRun@s3/e0 font_id=font1 glyphs=2 rect=[8,8 21x16] glyph_bounding_rect=[8,8 22x15] translation=[8,21] color=rgb(0, 0, 0) text="3D" owner=BlockContainer<DIV>.rotated phase=foreground+L0 FillRect@s3/e0 rect=[8,8 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.rotated phase=background+L0 DrawGlyphRun@s3/e0 font_id=font1 glyphs=2 rect=[8,8 21x16] glyph_bounding_rect=[8,8 22x15] translation=[8,21] color=rgb(0, 0, 0) text="3D" owner=BlockContainer<DIV>.rotated phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/perspective-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/perspective-invalidation.txtindex 512bf4befd8..99d6d9c940f 100644--- a/Tests/LibWeb/Text/expected/display_list/perspective-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/perspective-invalidation.txt@@ -7,8 +7,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#child phase=background+L0 FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#child phase=backgroundAfter perspective change:AccumulatedVisualContext Tree:@@ -20,6 +23,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s3/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#child phase=background+L0 FillRect@s3/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#child phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/positioned-with-transformed-ancestor.txt b/Tests/LibWeb/Text/expected/display_list/positioned-with-transformed-ancestor.txtindex d2a4458e37a..2d09cb040c5 100644--- a/Tests/LibWeb/Text/expected/display_list/positioned-with-transformed-ancestor.txt+++ b/Tests/LibWeb/Text/expected/display_list/positioned-with-transformed-ancestor.txt@@ -6,9 +6,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 200x200] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.transformed-ancestor phase=background-FillRect@s2/e0 rect=[8,8 200x90] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.intermediate phase=background-FillRect@s2/e0 rect=[33,33 100x50] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.positioned phase=background-DrawGlyphRun@s2/e0 font_id=font1 glyphs=10 rect=[33,33 84x16] glyph_bounding_rect=[33,34 89x15] translation=[33,46] color=rgb(0, 0, 0) text="Positioned" owner=BlockContainer<DIV>.positioned phase=foreground+L0 FillRect@s2/e0 rect=[8,8 200x200] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.transformed-ancestor phase=background+L0 FillRect@s2/e0 rect=[8,8 200x90] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.intermediate phase=background+L0 FillRect@s2/e0 rect=[33,33 100x50] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.positioned phase=background+L0 DrawGlyphRun@s2/e0 font_id=font1 glyphs=10 rect=[33,33 84x16] glyph_bounding_rect=[33,34 89x15] translation=[33,46] color=rgb(0, 0, 0) text="Positioned" owner=BlockContainer<DIV>.positioned phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/record-ids-number-nested-records-and-name-layer-records.txt b/Tests/LibWeb/Text/expected/display_list/record-ids-number-nested-records-and-name-layer-records.txtindex b8e3f0f9c8f..fd6908db4b3 100644--- a/Tests/LibWeb/Text/expected/display_list/record-ids-number-nested-records-and-name-layer-records.txt+++ b/Tests/LibWeb/Text/expected/display_list/record-ids-number-nested-records-and-name-layer-records.txt@@ -1,13 +1,13 @@Layers:- [L0] base rect=[0,0 800x600] records=#1,#3-#5- [L1] canvas rect=[17,17 206x126] records=#2 shown by the window server: clip=[0,0 800x600]- [L2] painted rect=[97,57 306x46] records=#6+ [L0] base space=viewport records=#1,#3-#6+ [L1] canvas #0 space=viewport region=[17,17 206x126] records=#2 shown by the window server: clip=[0,0 800x600]+ [L2] painted space=viewport above L1 records=#6DisplayList:L0 #1 FillRect@s1/e0 rect=[0,0 300x10] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#below phase=backgroundL1 #2 DrawCanvas@s1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground-L0 #3 DeclareMaskContent@s1/e1 rect=[300,20 50x50] effect=e1 owner=BlockContainer<DIV>#masked phase=preamble- #4 PaintLinearGradient@s1/e1 gradient_rect=[300,20 50x50] gradient_angle=180 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[300,20 50x50]] owner=BlockContainer<DIV>#masked phase=preamble-L0 #5 FillRect@s1/e1 rect=[300,20 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#masked phase=background-L2 #6 FillRect@s1/e0 rect=[100,60 300x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over phase=background+L0 #3 DeclareMaskContent@s1/e1 rect=[600,20 50x50] effect=e1 owner=BlockContainer<DIV>#masked phase=preamble+ #4 PaintLinearGradient@s1/e1 gradient_rect=[600,20 50x50] gradient_angle=180 color_stops=[rgb(0, 0, 0) 0, rgba(0, 0, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} inline_clips=[clip=[600,20 50x50]] owner=BlockContainer<DIV>#masked phase=preamble+L0 #5 FillRect@s1/e1 rect=[600,20 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#masked phase=background+L0,L2 #6 FillRect@s1/e0 rect=[100,60 500x40] color=rgba(255, 255, 255, 0.5) owner=BlockContainer<DIV>#over phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/record-owners-and-phases.txt b/Tests/LibWeb/Text/expected/display_list/record-owners-and-phases.txtindex e1cd8761647..e9d4498dfde 100644--- a/Tests/LibWeb/Text/expected/display_list/record-owners-and-phases.txt+++ b/Tests/LibWeb/Text/expected/display_list/record-owners-and-phases.txt@@ -1,10 +1,10 @@DisplayList:-FillRect@s1/e0 rect=[8,8 104x34] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 104x34] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>#box phase=border-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[10,10 33x16] glyph_bounding_rect=[10,10 39x15] translation=[10,23] color=rgb(0, 0, 0) text="text" owner=BlockContainer<DIV>#box phase=foreground-FillRoundedRectRing@s1/e0 rect=[5,5 110x40] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(255, 0, 0) owner=BlockContainer<DIV>#box phase=outline-DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg- FillPath@s2/c0/e1 path_bounding_rect=[0,0 50x50] path_data=[path: M0 0L50 0L50 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground-FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect>#masked phase=foreground+L0 FillRect@s1/e0 rect=[8,8 104x34] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 104x34] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>#box phase=border+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[10,10 33x16] glyph_bounding_rect=[10,10 39x15] translation=[10,23] color=rgb(0, 0, 0) text="text" owner=BlockContainer<DIV>#box phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[5,5 110x40] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(255, 0, 0) owner=BlockContainer<DIV>#box phase=outline+L0 DeclareMaskContent@s2/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGSVGBox<svg> phase=svg+ FillPath@s2/c0/e1 path_bounding_rect=[0,0 50x50] path_data=[path: M0 0L50 0L50 50L0 50L0 0Z] color=rgb(255, 255, 255) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s2/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect>#masked phase=foregroundwithout owners, no record names its owner or phase: truediff --git a/Tests/LibWeb/Text/expected/display_list/relative-with-inline-transformed-intermediate.txt b/Tests/LibWeb/Text/expected/display_list/relative-with-inline-transformed-intermediate.txtindex e1e42896e82..37fc7609d93 100644--- a/Tests/LibWeb/Text/expected/display_list/relative-with-inline-transformed-intermediate.txt+++ b/Tests/LibWeb/Text/expected/display_list/relative-with-inline-transformed-intermediate.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 300x300] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.block-container phase=background-FillRect@s1/e0 rect=[8,8 100x16] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.block-container phase=inline-piece-FillRect@s1/e0 rect=[13,13 100x100] color=rgb(255, 127, 80) owner=BlockContainer<SPAN>.relative-child phase=background-DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[13,13 65x16] glyph_bounding_rect=[13,14 69x15] translation=[13,26] color=rgb(0, 0, 0) text="Relative" owner=BlockContainer<SPAN>.relative-child phase=foreground+L0 FillRect@s1/e0 rect=[8,8 300x300] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.block-container phase=background+L0 FillRect@s1/e0 rect=[8,8 100x16] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.block-container phase=inline-piece+L0 FillRect@s1/e0 rect=[13,13 100x100] color=rgb(255, 127, 80) owner=BlockContainer<SPAN>.relative-child phase=background+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=8 rect=[13,13 65x16] glyph_bounding_rect=[13,14 69x15] translation=[13,26] color=rgb(0, 0, 0) text="Relative" owner=BlockContainer<SPAN>.relative-child phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/repeated-svg-background-is-tile.txt b/Tests/LibWeb/Text/expected/display_list/repeated-svg-background-is-tile.txtindex 5e43ca2b7fc..652c0a24894 100644--- a/Tests/LibWeb/Text/expected/display_list/repeated-svg-background-is-tile.txt+++ b/Tests/LibWeb/Text/expected/display_list/repeated-svg-background-is-tile.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawRepeatedTile@s1/e0 dst_rect=[8,8 20x20] clip_rect=[8,8 120x80] tile_size=[20x20] tile_step=[20x20] scaling_mode=NearestNeighbor repeat={x=true y=true} inline_clips=[clip=[8,8 120x80], clip=[8,8 120x80]] owner=BlockContainer<DIV>#target phase=background- PaintVectorImage@s1/e0 vector_image_id=svg1 rect=[0,0 20x20] recorded_size=[20x20] owner=BlockContainer<DIV>#target phase=background- FillPath@s1/e0 path_bounding_rect=[0,0 20x20] path_data=[path: M0 0L20 0L20 20L0 20L0 0Z] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#target phase=background- FillPath@s1/e0 path_bounding_rect=[5,5 10x10] path_data=[curved path: 129 commands] color=rgb(255, 255, 255) owner=BlockContainer<DIV>#target phase=background+L0 DrawRepeatedTile@s1/e0 dst_rect=[8,8 20x20] clip_rect=[8,8 120x80] tile_size=[20x20] tile_step=[20x20] scaling_mode=NearestNeighbor repeat={x=true y=true} inline_clips=[clip=[8,8 120x80], clip=[8,8 120x80]] owner=BlockContainer<DIV>#target phase=background+ PaintVectorImage@s1/e0 vector_image_id=svg1 rect=[0,0 20x20] recorded_size=[20x20] owner=BlockContainer<DIV>#target phase=background+ FillPath@s1/e0 path_bounding_rect=[0,0 20x20] path_data=[path: M0 0L20 0L20 20L0 20L0 0Z] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#target phase=background+ FillPath@s1/e0 path_bounding_rect=[5,5 10x10] path_data=[curved path: 129 commands] color=rgb(255, 255, 255) owner=BlockContainer<DIV>#target phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/root-background-absolutely-positioned-overflow.txt b/Tests/LibWeb/Text/expected/display_list/root-background-absolutely-positioned-overflow.txtindex c8c6d57ca14..ff1a94de455 100644--- a/Tests/LibWeb/Text/expected/display_list/root-background-absolutely-positioned-overflow.txt+++ b/Tests/LibWeb/Text/expected/display_list/root-background-absolutely-positioned-overflow.txt@@ -8,7 +8,10 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,2400] is_viewport=true+Layers:+ [L1] base space=document+DisplayList:-DrawRepeatedTile@s1/e0 dst_rect=[0,0 50x50] clip_rect=[0,0 800x3000] tile_size=[50x50] tile_step=[50x50] scaling_mode=Bilinear repeat={x=true y=true} inline_clips=[clip=[0,0 800x3000]] owner=BlockContainer<HTML> phase=background- PaintLinearGradient@s1/e0 gradient_rect=[0,0 50x50] gradient_angle=180 repeating_color_stops=[rgb(0, 128, 0) 0, rgb(0, 128, 0) 0.5, rgb(0, 255, 0) 0.5, rgb(0, 255, 0) 1] repeat_length=0.99999994 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=background+L1 DrawRepeatedTile@s1/e0 dst_rect=[0,0 50x50] clip_rect=[0,0 800x3000] tile_size=[50x50] tile_step=[50x50] scaling_mode=Bilinear repeat={x=true y=true} inline_clips=[clip=[0,0 800x3000]] owner=BlockContainer<HTML> phase=background+ PaintLinearGradient@s1/e0 gradient_rect=[0,0 50x50] gradient_angle=180 repeating_color_stops=[rgb(0, 128, 0) 0, rgb(0, 128, 0) 0.5, rgb(0, 255, 0) 0.5, rgb(0, 255, 0) 1] repeat_length=0.99999994 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/root-background-propagation-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/root-background-propagation-invalidation.txtindex f3da030e66d..3a613245f69 100644--- a/Tests/LibWeb/Text/expected/display_list/root-background-propagation-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/root-background-propagation-invalidation.txt@@ -6,11 +6,14 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s0 rect=[0,0 800x600] color=rgb(0, 128, 0) phase=canvas-FillRect@s1/e0 rect=[0,0 800x600] color=rgb(0, 128, 0) owner=BlockContainer<HTML> phase=background-DrawRepeatedTile@s1/e0 dst_rect=[0,0 800x63] clip_rect=[0,0 800x600] tile_size=[800x63] tile_step=[800x63] scaling_mode=Bilinear compositing_and_blending_operator=Multiply repeat={x=true y=true} inline_clips=[clip=[0,0 800x600]] owner=BlockContainer<HTML> phase=background- PaintLinearGradient@s1/e0 gradient_rect=[0,0 800x63] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=background+L0 FillRect@s0 rect=[0,0 800x600] color=rgb(0, 128, 0) phase=canvas+L0 FillRect@s1/e0 rect=[0,0 800x600] color=rgb(0, 128, 0) owner=BlockContainer<HTML> phase=background+L0 DrawRepeatedTile@s1/e0 dst_rect=[0,0 800x63] clip_rect=[0,0 800x600] tile_size=[800x63] tile_step=[800x63] scaling_mode=Bilinear compositing_and_blending_operator=Multiply repeat={x=true y=true} inline_clips=[clip=[0,0 800x600]] owner=BlockContainer<HTML> phase=background+ PaintLinearGradient@s1/e0 gradient_rect=[0,0 800x63] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=backgroundPainted by the body:AccumulatedVisualContext Tree:@@ -20,11 +23,14 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s0 rect=[0,0 800x600] color=rgb(255, 255, 255) phase=canvas-FillRect@s1/e0 rect=[0,0 800x600] color=rgb(255, 255, 255) owner=BlockContainer<HTML> phase=background-FillRect@s1/e0 rect=[0,13 800x50] color=rgb(0, 128, 0) owner=BlockContainer<BODY> phase=background-PaintLinearGradient@s1/e0 gradient_rect=[0,13 800x50] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[0,13 800x50]] owner=BlockContainer<BODY> phase=background+L0 FillRect@s0 rect=[0,0 800x600] color=rgb(255, 255, 255) phase=canvas+L0 FillRect@s1/e0 rect=[0,0 800x600] color=rgb(255, 255, 255) owner=BlockContainer<HTML> phase=background+L0 FillRect@s1/e0 rect=[0,13 800x50] color=rgb(0, 128, 0) owner=BlockContainer<BODY> phase=background+L0 PaintLinearGradient@s1/e0 gradient_rect=[0,13 800x50] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} compositing_and_blending_operator=Multiply inline_clips=[clip=[0,13 800x50]] owner=BlockContainer<BODY> phase=backgroundPropagated to the root again:AccumulatedVisualContext Tree:@@ -34,9 +40,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s0 rect=[0,0 800x600] color=rgb(0, 128, 0) phase=canvas-FillRect@s1/e0 rect=[0,0 800x600] color=rgb(0, 128, 0) owner=BlockContainer<HTML> phase=background-DrawRepeatedTile@s1/e0 dst_rect=[0,0 800x63] clip_rect=[0,0 800x600] tile_size=[800x63] tile_step=[800x63] scaling_mode=Bilinear compositing_and_blending_operator=Multiply repeat={x=true y=true} inline_clips=[clip=[0,0 800x600]] owner=BlockContainer<HTML> phase=background- PaintLinearGradient@s1/e0 gradient_rect=[0,0 800x63] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=background+L0 FillRect@s0 rect=[0,0 800x600] color=rgb(0, 128, 0) phase=canvas+L0 FillRect@s1/e0 rect=[0,0 800x600] color=rgb(0, 128, 0) owner=BlockContainer<HTML> phase=background+L0 DrawRepeatedTile@s1/e0 dst_rect=[0,0 800x63] clip_rect=[0,0 800x600] tile_size=[800x63] tile_step=[800x63] scaling_mode=Bilinear compositing_and_blending_operator=Multiply repeat={x=true y=true} inline_clips=[clip=[0,0 800x600]] owner=BlockContainer<HTML> phase=background+ PaintLinearGradient@s1/e0 gradient_rect=[0,0 800x63] gradient_angle=180 color_stops=[rgb(255, 0, 0) 0, rgb(255, 0, 0) 1] repeat_length=1 interpolation_method={rectangular_color_space=Srgb} owner=BlockContainer<HTML> phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/scroll-node-of-box-with-nothing-to-scroll-that-keeps-its-scrolls.txt b/Tests/LibWeb/Text/expected/display_list/scroll-node-of-box-with-nothing-to-scroll-that-keeps-its-scrolls.txtindex fc2fb6016a2..928cfb889d7 100644--- a/Tests/LibWeb/Text/expected/display_list/scroll-node-of-box-with-nothing-to-scroll-that-keeps-its-scrolls.txt+++ b/Tests/LibWeb/Text/expected/display_list/scroll-node-of-box-with-nothing-to-scroll-that-keeps-its-scrolls.txt@@ -12,12 +12,15 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[0,0 100x100] min_scroll_offset=[0,0] max_scroll_offset=[0,0] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#keeps-its-scrolls phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 50x50] owner=BlockContainer<SPAN> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,100 100x100] owner=BlockContainer<DIV>#passes-its-scrolls-on phase=scroll-metadata-CompositorWheelHitTestTarget@s1/c1/e0 target_scroll_node_index=s0 rect=[0,100 50x50] owner=BlockContainer<SPAN> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x213] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x200] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s2 rect=[0,0 100x100] owner=BlockContainer<DIV>#keeps-its-scrolls phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[0,0 50x50] owner=BlockContainer<SPAN> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,100 100x100] owner=BlockContainer<DIV>#passes-its-scrolls-on phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/c1/e0 target_scroll_node_index=s0 rect=[0,100 50x50] owner=BlockContainer<SPAN> phase=scroll-metadatadiff --git a/Tests/LibWeb/Text/expected/display_list/scrollable-in-fixed.txt b/Tests/LibWeb/Text/expected/display_list/scrollable-in-fixed.txtindex 3d0f45d6702..9be153c6c75 100644--- a/Tests/LibWeb/Text/expected/display_list/scrollable-in-fixed.txt+++ b/Tests/LibWeb/Text/expected/display_list/scrollable-in-fixed.txt@@ -11,19 +11,24 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[33,33 180x100] min_scroll_offset=[0,0] max_scroll_offset=[120,100] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [33,33 180x100] of viewport+ [L2] painted space=viewport above band 0 of scroller@s2 in viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x13] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[20,20 204x154] owner=BlockContainer<DIV>.fixed-box phase=scroll-metadata-FillRect@s0/e0 rect=[20,20 204x154] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.fixed-box phase=background-FillRoundedRectRing@s0/e0 rect=[20,20 204x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.fixed-box phase=border-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s2 rect=[32,32 182x102] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata-FillRoundedRectRing@s0/e0 rect=[32,32 182x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[33,33 300x200] owner=BlockContainer<DIV>.scroll-content phase=scroll-metadata-FillRect@s2/c0/e0 rect=[33,33 300x200] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.scroll-content phase=background-DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=23 rect=[33,33 179x16] glyph_bounding_rect=[33,34 184x15] translation=[33,46] color=rgb(0, 0, 0) text="Scrollable inside fixed" owner=BlockContainer<DIV>.scroll-content phase=foreground-CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[204,35 7x48] track_rect=[204,33 9x100] expanded_gutter_rect=[198,33 15x100] expanded_thumb_rect=[200,35 11x48] scroll_size=0.48 expanded_scroll_size=0.48 max_scroll_offset=100 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[204,35 7x48] track_rect=[204,33 9x100] expanded_gutter_rect=[198,33 15x100] scroll_size=0.48 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[35,124 97x7] track_rect=[33,124 165x9] expanded_gutter_rect=[33,118 165x15] expanded_thumb_rect=[35,120 97x11] scroll_size=0.53671875 expanded_scroll_size=0.53671875 max_scroll_offset=120 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[35,124 97x7] track_rect=[33,124 165x9] expanded_gutter_rect=[33,118 165x15] scroll_size=0.53671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x13] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[20,20 204x154] owner=BlockContainer<DIV>.fixed-box phase=scroll-metadata+L0 FillRect@s0/e0 rect=[20,20 204x154] color=rgb(211, 211, 211) owner=BlockContainer<DIV>.fixed-box phase=background+L0 FillRoundedRectRing@s0/e0 rect=[20,20 204x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.fixed-box phase=border+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s2 rect=[32,32 182x102] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata+L0 FillRoundedRectRing@s0/e0 rect=[32,32 182x102] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[33,33 300x200] owner=BlockContainer<DIV>.scroll-content phase=scroll-metadata+L1 FillRect@s2/c0/e0 rect=[33,33 300x200] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.scroll-content phase=background+L1 DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=23 rect=[33,33 179x16] glyph_bounding_rect=[33,34 184x15] translation=[33,46] color=rgb(0, 0, 0) text="Scrollable inside fixed" owner=BlockContainer<DIV>.scroll-content phase=foreground+L0 CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[204,35 7x48] track_rect=[204,33 9x100] expanded_gutter_rect=[198,33 15x100] expanded_thumb_rect=[200,35 11x48] scroll_size=0.48 expanded_scroll_size=0.48 max_scroll_offset=100 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L2 PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[204,35 7x48] track_rect=[204,33 9x100] expanded_gutter_rect=[198,33 15x100] scroll_size=0.48 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[35,124 97x7] track_rect=[33,124 165x9] expanded_gutter_rect=[33,118 165x15] expanded_thumb_rect=[35,120 97x11] scroll_size=0.53671875 expanded_scroll_size=0.53671875 max_scroll_offset=120 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L2 PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[35,124 97x7] track_rect=[33,124 165x9] expanded_gutter_rect=[33,118 165x15] scroll_size=0.53671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/selection-highlight-painting-order.txt b/Tests/LibWeb/Text/expected/display_list/selection-highlight-painting-order.txtindex 3ddacbb4fb7..464962adaa0 100644--- a/Tests/LibWeb/Text/expected/display_list/selection-highlight-painting-order.txt+++ b/Tests/LibWeb/Text/expected/display_list/selection-highlight-painting-order.txt@@ -5,17 +5,20 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintTextShadow@s1/e0 font_id=font1 glyphs=1 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="a" owner=BlockContainer<P>#target phase=foreground-PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="bcd" owner=BlockContainer<P>#target phase=foreground-PaintTextShadow@s1/e0 font_id=font1 glyphs=1 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="e" owner=BlockContainer<P>#target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(1, 2, 3) inline_clips=[clip=[0,20 12x18]] text="a" owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[0,38 12x2] color=rgb(7, 8, 9) owner=BlockContainer<P>#target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(1, 2, 3) inline_clips=[clip=[44,20 11x18]] text="e" owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[44,38 11x2] color=rgb(7, 8, 9) owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[12,20 32x20] color=rgb(13, 14, 15) owner=BlockContainer<P>#target phase=foreground-PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[4,4] rounded_offset=[4,4] color=rgb(16, 17, 18)}] shadows_bounding_rect=[4,24 56x20] rect=[0,20 56x20] translation=[0,36] text="bcd" owner=BlockContainer<P>#target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(10, 11, 12) inline_clips=[clip=[12,20 32x18]] text="bcd" owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[12,38 32x2] color=rgb(10, 11, 12) owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[12,28 32x2] color=rgb(19, 20, 21) owner=BlockContainer<P>#target phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=1 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="a" owner=BlockContainer<P>#target phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="bcd" owner=BlockContainer<P>#target phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=1 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(4, 5, 6)}] shadows_bounding_rect=[2,22 56x20] rect=[0,20 56x20] translation=[0,36] text="e" owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(1, 2, 3) inline_clips=[clip=[0,20 12x18]] text="a" owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[0,38 12x2] color=rgb(7, 8, 9) owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(1, 2, 3) inline_clips=[clip=[44,20 11x18]] text="e" owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[44,38 11x2] color=rgb(7, 8, 9) owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[12,20 32x20] color=rgb(13, 14, 15) owner=BlockContainer<P>#target phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[4,4] rounded_offset=[4,4] color=rgb(16, 17, 18)}] shadows_bounding_rect=[4,24 56x20] rect=[0,20 56x20] translation=[0,36] text="bcd" owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[0,20 56x20] glyph_bounding_rect=[0,20 61x18] translation=[0,36] color=rgb(10, 11, 12) inline_clips=[clip=[12,20 32x18]] text="bcd" owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[12,38 32x2] color=rgb(10, 11, 12) owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[12,28 32x2] color=rgb(19, 20, 21) owner=BlockContainer<P>#target phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/selection-vertical-writing-mode.txt b/Tests/LibWeb/Text/expected/display_list/selection-vertical-writing-mode.txtindex a350280db80..3b0840c139c 100644--- a/Tests/LibWeb/Text/expected/display_list/selection-vertical-writing-mode.txt+++ b/Tests/LibWeb/Text/expected/display_list/selection-vertical-writing-mode.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,0 18x12]] text="a" owner=BlockContainer<P>#target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,44 18x11]] text="e" owner=BlockContainer<P>#target phase=foreground-FillRect@s1/e0 rect=[760,12 20x32] color=rgb(1, 2, 3) owner=BlockContainer<P>#target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,12 18x32]] text="bcd" owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,0 18x12]] text="a" owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,44 18x11]] text="e" owner=BlockContainer<P>#target phase=foreground+L0 FillRect@s1/e0 rect=[760,12 20x32] color=rgb(1, 2, 3) owner=BlockContainer<P>#target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[760,0 20x56] glyph_bounding_rect=[762,0 18x61] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical inline_clips=[clip=[762,12 18x32]] text="bcd" owner=BlockContainer<P>#target phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/sibling-overflow-containers.txt b/Tests/LibWeb/Text/expected/display_list/sibling-overflow-containers.txtindex 216502c6b59..eb65a163904 100644--- a/Tests/LibWeb/Text/expected/display_list/sibling-overflow-containers.txt+++ b/Tests/LibWeb/Text/expected/display_list/sibling-overflow-containers.txt@@ -14,11 +14,17 @@ ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[9,9 100x80] min_scroll_offset=[0,0] max_scroll_offset=[50,40] is_viewport=falseScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[131,9 100x80] min_scroll_offset=[0,0] max_scroll_offset=[50,40] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [9,9 100x80] of viewport+ [L2] painted space=viewport above band 0 of scroller@s2 in viewport+ [L3] painted space=scroller@s3 in viewport composited within [131,9 100x80] of viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 102x82] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.scroll-box phase=border-FillRect@s2/c0/e0 rect=[9,9 150x120] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.content.red phase=background-DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=13 rect=[9,9 110x16] glyph_bounding_rect=[9,10 111x15] translation=[9,22] color=rgb(0, 0, 0) text="Left overflow" owner=BlockContainer<DIV>.content.red phase=foreground-FillRoundedRectRing@s1/e0 rect=[130,8 102x82] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.scroll-box phase=border-FillRect@s3/c1/e0 rect=[131,9 150x120] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.content.green phase=background-DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=14 rect=[131,9 119x16] glyph_bounding_rect=[131,10 120x15] translation=[131,22] color=rgb(0, 0, 0) text="Right overflow" owner=BlockContainer<DIV>.content.green phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[8,8 102x82] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.scroll-box phase=border+L1 FillRect@s2/c0/e0 rect=[9,9 150x120] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.content.red phase=background+L1 DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=13 rect=[9,9 110x16] glyph_bounding_rect=[9,10 111x15] translation=[9,22] color=rgb(0, 0, 0) text="Left overflow" owner=BlockContainer<DIV>.content.red phase=foreground+L2 FillRoundedRectRing@s1/e0 rect=[130,8 102x82] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.scroll-box phase=border+L3 FillRect@s3/c1/e0 rect=[131,9 150x120] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.content.green phase=background+L3 DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=14 rect=[131,9 119x16] glyph_bounding_rect=[131,10 120x15] translation=[131,22] color=rgb(0, 0, 0) text="Right overflow" owner=BlockContainer<DIV>.content.green phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/sibling-scrollables-in-fixed.txt b/Tests/LibWeb/Text/expected/display_list/sibling-scrollables-in-fixed.txtindex a9ee619ce29..20483fbf4a1 100644--- a/Tests/LibWeb/Text/expected/display_list/sibling-scrollables-in-fixed.txt+++ b/Tests/LibWeb/Text/expected/display_list/sibling-scrollables-in-fixed.txt@@ -6,48 +6,57 @@ AccumulatedVisualContext Tree:[s3] scroll (BlockContainer<DIV>.scroll-container)[s4] scroll (BlockContainer<DIV>.scroll-container)clips:- [c0 in s0] clip=[23,23 91x150] (BlockContainer<DIV>.scroll-container)- [c1 in s0] clip=[126,23 92x150] (BlockContainer<DIV>.scroll-container)- [c2 in s0] clip=[230,23 91x150] (BlockContainer<DIV>.scroll-container)+ [c0 in s0] clip=[223,23 91x150] (BlockContainer<DIV>.scroll-container)+ [c1 in s0] clip=[326,23 92x150] (BlockContainer<DIV>.scroll-container)+ [c2 in s0] clip=[430,23 91x150] (BlockContainer<DIV>.scroll-container)effects:[e0 in s0] effects=[]ScrollNodes:-ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[23,23 91x150] min_scroll_offset=[0,0] max_scroll_offset=[108.671875,150] is_viewport=false-ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[126,23 92x150] min_scroll_offset=[0,0] max_scroll_offset=[108.65625,150] is_viewport=false-ScrollNode scroll_node_index=s4 parent_scroll_node_index=s0 scrollport_rect=[230,23 91x150] min_scroll_offset=[0,0] max_scroll_offset=[108.671875,150] is_viewport=false+ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[223,23 91x150] min_scroll_offset=[0,0] max_scroll_offset=[108.671875,150] is_viewport=false+ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[326,23 92x150] min_scroll_offset=[0,0] max_scroll_offset=[108.65625,150] is_viewport=false+ScrollNode scroll_node_index=s4 parent_scroll_node_index=s0 scrollport_rect=[430,23 91x150] min_scroll_offset=[0,0] max_scroll_offset=[108.671875,150] is_viewport=false++Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [223,23 91x150] of viewport+ [L2] painted space=viewport above band 0 of scroller@s2 in viewport+ [L3] painted space=scroller@s3 in viewport composited within [326,23 92x150] of viewport+ [L4] painted space=viewport above band 0 of scroller@s3 in viewport+ [L5] painted space=scroller@s4 in viewport composited within [430,23 91x150] of viewport+ [L6] painted space=viewport above band 0 of scroller@s4 in viewportDisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x13] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[10,10 324x224] owner=Box<DIV>.fixed-box phase=scroll-metadata-FillRect@s0/e0 rect=[10,10 324x224] color=rgb(211, 211, 211) owner=Box<DIV>.fixed-box phase=background-FillRoundedRectRing@s0/e0 rect=[10,10 324x224] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.fixed-box phase=border-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s2 rect=[22,22 93.328125x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata-FillRoundedRectRing@s0/e0 rect=[22,22 93x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[23,23 200x300] owner=BlockContainer<DIV>.scroll-content.red phase=scroll-metadata-FillRect@s2/c0/e0 rect=[23,23 200x300] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.scroll-content.red phase=background-DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=8 rect=[23,23 71x16] glyph_bounding_rect=[23,24 70x15] translation=[23,36] color=rgb(0, 0, 0) text="Scroll A" owner=BlockContainer<DIV>.scroll-content.red phase=foreground-CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[105,25 7x73] track_rect=[105,23 9x150] expanded_gutter_rect=[99,23 15x150] expanded_thumb_rect=[101,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[105,25 7x73] track_rect=[105,23 9x150] expanded_gutter_rect=[99,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[25,164 33x7] track_rect=[23,164 76x9] expanded_gutter_rect=[23,158 76x15] expanded_thumb_rect=[25,160 33x11] scroll_size=0.3617541337167505 expanded_scroll_size=0.3617541337167505 max_scroll_offset=108.671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[25,164 33x7] track_rect=[23,164 76x9] expanded_gutter_rect=[23,158 76x15] scroll_size=0.3617541337167505 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s3 rect=[125.328125,22 93.34375x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata-FillRoundedRectRing@s0/e0 rect=[125,22 94x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border-CompositorWheelHitTestTarget@s3/c1/e0 target_scroll_node_index=s3 rect=[126.328125,23 200x300] owner=BlockContainer<DIV>.scroll-content.green phase=scroll-metadata-FillRect@s3/c1/e0 rect=[126,23 200x300] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.scroll-content.green phase=background-DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=8 rect=[126,23 67x16] glyph_bounding_rect=[126,24 70x15] translation=[126.328125,36] color=rgb(0, 0, 0) text="Scroll B" owner=BlockContainer<DIV>.scroll-content.green phase=foreground-CompositorScrollbar@s0/e0 scroll_node_index=s3 thumb_rect=[209,25 7x73] track_rect=[209,23 9x150] expanded_gutter_rect=[203,23 15x150] expanded_thumb_rect=[205,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s3 thumb_rect=[209,25 7x73] track_rect=[209,23 9x150] expanded_gutter_rect=[203,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorScrollbar@s0/e0 scroll_node_index=s3 thumb_rect=[128,164 33x7] track_rect=[126,164 77x9] expanded_gutter_rect=[126,158 77x15] expanded_thumb_rect=[128,160 33x11] scroll_size=0.36180615473109 expanded_scroll_size=0.36180615473109 max_scroll_offset=108.65625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s3 thumb_rect=[128,164 33x7] track_rect=[126,164 77x9] expanded_gutter_rect=[126,158 77x15] scroll_size=0.36180615473109 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s4 rect=[228.67188,22 93.328125x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata-FillRoundedRectRing@s0/e0 rect=[229,22 93x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border-CompositorWheelHitTestTarget@s4/c2/e0 target_scroll_node_index=s4 rect=[229.67188,23 200x300] owner=BlockContainer<DIV>.scroll-content.blue phase=scroll-metadata-FillRect@s4/c2/e0 rect=[230,23 200x300] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.scroll-content.blue phase=background-DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=8 rect=[229,23 68x16] glyph_bounding_rect=[230,24 70x15] translation=[229.67188,36] color=rgb(0, 0, 0) text="Scroll C" owner=BlockContainer<DIV>.scroll-content.blue phase=foreground-CompositorScrollbar@s0/e0 scroll_node_index=s4 thumb_rect=[312,25 7x73] track_rect=[312,23 9x150] expanded_gutter_rect=[306,23 15x150] expanded_thumb_rect=[308,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s4 thumb_rect=[312,25 7x73] track_rect=[312,23 9x150] expanded_gutter_rect=[306,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay-CompositorScrollbar@s0/e0 scroll_node_index=s4 thumb_rect=[232,164 33x7] track_rect=[230,164 76x9] expanded_gutter_rect=[230,158 76x15] expanded_thumb_rect=[232,160 33x11] scroll_size=0.3617541337167505 expanded_scroll_size=0.3617541337167505 max_scroll_offset=108.671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay-PaintScrollBar@s0/e0 scroll_node_index=s4 thumb_rect=[232,164 33x7] track_rect=[230,164 76x9] expanded_gutter_rect=[230,158 76x15] scroll_size=0.3617541337167505 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x13] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[210,10 324x224] owner=Box<DIV>.fixed-box phase=scroll-metadata+L0 FillRect@s0/e0 rect=[210,10 324x224] color=rgb(211, 211, 211) owner=Box<DIV>.fixed-box phase=background+L0 FillRoundedRectRing@s0/e0 rect=[210,10 324x224] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=Box<DIV>.fixed-box phase=border+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s2 rect=[222,22 93.328125x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata+L0 FillRoundedRectRing@s0/e0 rect=[222,22 93x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s2 rect=[223,23 200x300] owner=BlockContainer<DIV>.scroll-content.red phase=scroll-metadata+L1 FillRect@s2/c0/e0 rect=[223,23 200x300] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.scroll-content.red phase=background+L1 DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=8 rect=[223,23 71x16] glyph_bounding_rect=[223,24 70x15] translation=[223,36] color=rgb(0, 0, 0) text="Scroll A" owner=BlockContainer<DIV>.scroll-content.red phase=foreground+L0 CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[305,25 7x73] track_rect=[305,23 9x150] expanded_gutter_rect=[299,23 15x150] expanded_thumb_rect=[301,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L2 PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[305,25 7x73] track_rect=[305,23 9x150] expanded_gutter_rect=[299,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorScrollbar@s0/e0 scroll_node_index=s2 thumb_rect=[225,164 33x7] track_rect=[223,164 76x9] expanded_gutter_rect=[223,158 76x15] expanded_thumb_rect=[225,160 33x11] scroll_size=0.3617541337167505 expanded_scroll_size=0.3617541337167505 max_scroll_offset=108.671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L2 PaintScrollBar@s0/e0 scroll_node_index=s2 thumb_rect=[225,164 33x7] track_rect=[223,164 76x9] expanded_gutter_rect=[223,158 76x15] scroll_size=0.3617541337167505 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s3 rect=[325.32812,22 93.34375x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata+L2 FillRoundedRectRing@s0/e0 rect=[325,22 94x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border+L0 CompositorWheelHitTestTarget@s3/c1/e0 target_scroll_node_index=s3 rect=[326.32812,23 200x300] owner=BlockContainer<DIV>.scroll-content.green phase=scroll-metadata+L3 FillRect@s3/c1/e0 rect=[326,23 200x300] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.scroll-content.green phase=background+L3 DrawGlyphRun@s3/c1/e0 font_id=font1 glyphs=8 rect=[326,23 67x16] glyph_bounding_rect=[326,24 70x15] translation=[326.32812,36] color=rgb(0, 0, 0) text="Scroll B" owner=BlockContainer<DIV>.scroll-content.green phase=foreground+L0 CompositorScrollbar@s0/e0 scroll_node_index=s3 thumb_rect=[409,25 7x73] track_rect=[409,23 9x150] expanded_gutter_rect=[403,23 15x150] expanded_thumb_rect=[405,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L4 PaintScrollBar@s0/e0 scroll_node_index=s3 thumb_rect=[409,25 7x73] track_rect=[409,23 9x150] expanded_gutter_rect=[403,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorScrollbar@s0/e0 scroll_node_index=s3 thumb_rect=[328,164 33x7] track_rect=[326,164 77x9] expanded_gutter_rect=[326,158 77x15] expanded_thumb_rect=[328,160 33x11] scroll_size=0.36180615473109 expanded_scroll_size=0.36180615473109 max_scroll_offset=108.65625 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L4 PaintScrollBar@s0/e0 scroll_node_index=s3 thumb_rect=[328,164 33x7] track_rect=[326,164 77x9] expanded_gutter_rect=[326,158 77x15] scroll_size=0.36180615473109 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s4 rect=[428.67188,22 93.328125x152] owner=BlockContainer<DIV>.scroll-container phase=scroll-metadata+L0,L4 FillRoundedRectRing@s0/e0 rect=[429,22 93x152] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.scroll-container phase=border+L0 CompositorWheelHitTestTarget@s4/c2/e0 target_scroll_node_index=s4 rect=[429.67188,23 200x300] owner=BlockContainer<DIV>.scroll-content.blue phase=scroll-metadata+L5 FillRect@s4/c2/e0 rect=[430,23 200x300] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.scroll-content.blue phase=background+L5 DrawGlyphRun@s4/c2/e0 font_id=font1 glyphs=8 rect=[429,23 68x16] glyph_bounding_rect=[430,24 70x15] translation=[429.67188,36] color=rgb(0, 0, 0) text="Scroll C" owner=BlockContainer<DIV>.scroll-content.blue phase=foreground+L0 CompositorScrollbar@s0/e0 scroll_node_index=s4 thumb_rect=[512,25 7x73] track_rect=[512,23 9x150] expanded_gutter_rect=[506,23 15x150] expanded_thumb_rect=[508,25 11x73] scroll_size=0.4866666666666667 expanded_scroll_size=0.4866666666666667 max_scroll_offset=150 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L6 PaintScrollBar@s0/e0 scroll_node_index=s4 thumb_rect=[512,25 7x73] track_rect=[512,23 9x150] expanded_gutter_rect=[506,23 15x150] scroll_size=0.4866666666666667 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>.scroll-container phase=overlay+L0 CompositorScrollbar@s0/e0 scroll_node_index=s4 thumb_rect=[432,164 33x7] track_rect=[430,164 76x9] expanded_gutter_rect=[430,158 76x15] expanded_thumb_rect=[432,160 33x11] scroll_size=0.3617541337167505 expanded_scroll_size=0.3617541337167505 max_scroll_offset=108.671875 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlay+L6 PaintScrollBar@s0/e0 scroll_node_index=s4 thumb_rect=[432,164 33x7] track_rect=[430,164 76x9] expanded_gutter_rect=[430,158 76x15] scroll_size=0.3617541337167505 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) owner=BlockContainer<DIV>.scroll-container phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/sibling-transforms.txt b/Tests/LibWeb/Text/expected/display_list/sibling-transforms.txtindex c02e4ba5847..f6b74b93f5a 100644--- a/Tests/LibWeb/Text/expected/display_list/sibling-transforms.txt+++ b/Tests/LibWeb/Text/expected/display_list/sibling-transforms.txt@@ -7,9 +7,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 80x80] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.box.left phase=background-DrawGlyphRun@s2/e0 font_id=font1 glyphs=1 rect=[8,8 15x16] glyph_bounding_rect=[8,8 13x15] translation=[8,21] color=rgb(0, 0, 0) text="A" owner=BlockContainer<DIV>.box.left phase=foreground-FillRect@s3/e0 rect=[98,8 80x80] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box.right phase=background-DrawGlyphRun@s3/e0 font_id=font1 glyphs=1 rect=[98,8 10x16] glyph_bounding_rect=[98,8 13x15] translation=[98,21] color=rgb(0, 0, 0) text="B" owner=BlockContainer<DIV>.box.right phase=foreground+L0 FillRect@s2/e0 rect=[8,8 80x80] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.box.left phase=background+L0 DrawGlyphRun@s2/e0 font_id=font1 glyphs=1 rect=[8,8 15x16] glyph_bounding_rect=[8,8 13x15] translation=[8,21] color=rgb(0, 0, 0) text="A" owner=BlockContainer<DIV>.box.left phase=foreground+L0 FillRect@s3/e0 rect=[98,8 80x80] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box.right phase=background+L0 DrawGlyphRun@s3/e0 font_id=font1 glyphs=1 rect=[98,8 10x16] glyph_bounding_rect=[98,8 13x15] translation=[98,21] color=rgb(0, 0, 0) text="B" owner=BlockContainer<DIV>.box.right phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/simple-overflow-hidden.txt b/Tests/LibWeb/Text/expected/display_list/simple-overflow-hidden.txtindex 2cf35f1e933..55bc079bfef 100644--- a/Tests/LibWeb/Text/expected/display_list/simple-overflow-hidden.txt+++ b/Tests/LibWeb/Text/expected/display_list/simple-overflow-hidden.txt@@ -11,8 +11,12 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[10,10 200x100] min_scroll_offset=[0,0] max_scroll_offset=[100,50] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [10,10 200x100] of viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 204x104] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.container phase=border-FillRect@s2/c0/e0 rect=[10,10 300x150] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.inner-box phase=background-DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=4 rect=[10,10 38x16] glyph_bounding_rect=[10,10 44x15] translation=[10,23] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>.inner-box phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[8,8 204x104] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.container phase=border+L1 FillRect@s2/c0/e0 rect=[10,10 300x150] color=rgb(240, 128, 128) owner=BlockContainer<DIV>.inner-box phase=background+L1 DrawGlyphRun@s2/c0/e0 font_id=font1 glyphs=4 rect=[10,10 38x16] glyph_bounding_rect=[10,10 44x15] translation=[10,23] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>.inner-box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/solid-border-edge-before-a-groove-edge.txt b/Tests/LibWeb/Text/expected/display_list/solid-border-edge-before-a-groove-edge.txtindex 9fc2a192b05..8efbfae7f8a 100644--- a/Tests/LibWeb/Text/expected/display_list/solid-border-edge-before-a-groove-edge.txt+++ b/Tests/LibWeb/Text/expected/display_list/solid-border-edge-before-a-groove-edge.txt@@ -5,12 +5,15 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s1/e0 path_bounding_rect=[8,8 140x20] path_data=[path: M8 8L8 8L28 28L128 28L148 8L148 8] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[138,8 10x100] path_data=[path: M148 8L148 8L138 18L138 98L148 108L148 108] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[128,18 10x80] path_data=[path: M138 18L138 18L128 28L128 88L138 98L138 98] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[8,98 140x10] path_data=[path: M148 108L148 108L138 98L18 98L8 108L8 108] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[18,88 120x10] path_data=[path: M138 98L138 98L128 88L28 88L18 98L18 98] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[8,8 10x100] path_data=[path: M8 108L8 108L18 98L18 18L8 8L8 8] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border-FillPath@s1/e0 path_bounding_rect=[18,18 10x80] path_data=[path: M18 98L18 98L28 88L28 28L18 18L18 18] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,8 140x20] path_data=[path: M8 8L8 8L28 28L128 28L148 8L148 8] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[138,8 10x100] path_data=[path: M148 8L148 8L138 18L138 98L148 108L148 108] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[128,18 10x80] path_data=[path: M138 18L138 18L128 28L128 88L138 98L138 98] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,98 140x10] path_data=[path: M148 108L148 108L138 98L18 98L8 108L8 108] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[18,88 120x10] path_data=[path: M138 98L138 98L128 88L28 88L18 98L18 98] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,8 10x100] path_data=[path: M8 108L8 108L18 98L18 18L8 8L8 8] color=rgb(48, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=border+L0 FillPath@s1/e0 path_bounding_rect=[18,18 10x80] path_data=[path: M18 98L18 98L28 88L28 28L18 18L18 18] color=rgb(133, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV> phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/solid-border-edges-with-a-dashed-edge.txt b/Tests/LibWeb/Text/expected/display_list/solid-border-edges-with-a-dashed-edge.txtindex 5815a8e8680..a14dc02e2bd 100644--- a/Tests/LibWeb/Text/expected/display_list/solid-border-edges-with-a-dashed-edge.txt+++ b/Tests/LibWeb/Text/expected/display_list/solid-border-edges-with-a-dashed-edge.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s1/e0 path_bounding_rect=[8,8 120x80] path_data=[path: M8 8L8 8L18 18L118 18L128 8L128 8M128 8L128 8L118 18L118 78L128 88L128 88M128 88L128 88L118 78L18 78L8 88L8 88] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.last-edge-dashed phase=border-StrokePath@s1/e0 dash_array=[20, 20] dash_offset=10 path_bounding_rect=[8,3 10x90] path_data=[path: M13 88L13 8] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,8 10x80], path: M8 88L8 88L18 78L18 18L8 8L8 8] winding_rule=EvenOdd] owner=BlockContainer<DIV>.last-edge-dashed phase=border-StrokePath@s1/e0 dash_array=[20, 20] dash_offset=10 path_bounding_rect=[3,88 130x10] path_data=[path: M8 93L128 93] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,88 120x10], path: M8 88L8 88L18 98L118 98L128 88L128 88] winding_rule=EvenOdd] owner=BlockContainer<DIV>.first-edge-dashed phase=border-FillPath@s1/e0 path_bounding_rect=[8,88 120x80] path_data=[path: M128 88L128 88L118 98L118 158L128 168L128 168M128 168L128 168L118 158L18 158L8 168L8 168M8 168L8 168L18 158L18 98L8 88L8 88] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.first-edge-dashed phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,8 120x80] path_data=[path: M8 8L8 8L18 18L118 18L128 8L128 8M128 8L128 8L118 18L118 78L128 88L128 88M128 88L128 88L118 78L18 78L8 88L8 88] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.last-edge-dashed phase=border+L0 StrokePath@s1/e0 dash_array=[20, 20] dash_offset=10 path_bounding_rect=[8,3 10x90] path_data=[path: M13 88L13 8] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,8 10x80], path: M8 88L8 88L18 78L18 18L8 8L8 8] winding_rule=EvenOdd] owner=BlockContainer<DIV>.last-edge-dashed phase=border+L0 StrokePath@s1/e0 dash_array=[20, 20] dash_offset=10 path_bounding_rect=[3,88 130x10] path_data=[path: M8 93L128 93] color=rgb(255, 0, 0) thickness=10 inline_clips=[clip_path=[bounds: [8,88 120x10], path: M8 88L8 88L18 98L118 98L128 88L128 88] winding_rule=EvenOdd] owner=BlockContainer<DIV>.first-edge-dashed phase=border+L0 FillPath@s1/e0 path_bounding_rect=[8,88 120x80] path_data=[path: M128 88L128 88L118 98L118 158L128 168L128 168M128 168L128 168L118 158L18 158L8 168L8 168M8 168L8 168L18 158L18 98L8 88L8 88] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.first-edge-dashed phase=borderdiff --git a/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-mask-after-relayout.txt b/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-mask-after-relayout.txtindex 46fd5f097b5..85f5e7eef2f 100644--- a/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-mask-after-relayout.txt+++ b/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-mask-after-relayout.txt@@ -11,8 +11,11 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s3 out=c0] mask=[-10,-10 120x120] kind=luminance origin=svg-mask (SVGForeignObjectBox<foreignObject>#fo)+Layers:+ [L0] base space=viewport+DisplayList:-DeclareMaskContent@s3/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGForeignObjectBox<foreignObject>#fo phase=preamble- FillPath@s3/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[curved path: 129 commands] color=rgb(255, 255, 255) owner=SVGGeometryBox<circle> phase=foreground-FillRect@s3/c1/e1 rect=[0,0 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=background+L0 DeclareMaskContent@s3/c0/e1 rect=[-10,-10 120x120] effect=e1 owner=SVGForeignObjectBox<foreignObject>#fo phase=preamble+ FillPath@s3/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[curved path: 129 commands] color=rgb(255, 255, 255) owner=SVGGeometryBox<circle> phase=foreground+L0 FillRect@s3/c1/e1 rect=[0,0 100x100] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-scroller-after-relayout.txt b/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-scroller-after-relayout.txtindex 3024185a2bf..74f17682f87 100644--- a/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-scroller-after-relayout.txt+++ b/Tests/LibWeb/Text/expected/display_list/svg-foreignobject-scroller-after-relayout.txt@@ -14,17 +14,20 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[0,0 80x80] min_scroll_offset=[0,0] max_scroll_offset=[0,220] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x124] owner=BlockContainer<HTML> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x103] owner=BlockContainer<BODY> phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x103] owner=BlockContainer(anonymous) phase=scroll-metadata-CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 100x100] owner=SVGSVGBox<svg> phase=scroll-metadata-StrokePath@s2/c0/e0 path_bounding_rect=[9.5,9.5 81x81] path_data=[path: M10 10L90 90] color=rgb(0, 0, 0) thickness=1 owner=SVGGeometryBox<path>#p phase=foreground-CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s0 rect=[0,0 100x100] owner=SVGForeignObjectBox<foreignObject> phase=scroll-metadata-CompositorWheelHitTestTarget@s2/c1/e0 target_scroll_node_index=s3 rect=[0,0 80x80] owner=BlockContainer<DIV>#scroller phase=scroll-metadata-CompositorWheelHitTestTarget@s3/c2/e0 target_scroll_node_index=s3 rect=[0,0 80x300] owner=BlockContainer<DIV> phase=scroll-metadata-FillRect@s3/c2/e0 rect=[0,0 80x300] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=background-CompositorScrollbar@s2/c1/e0 scroll_node_index=s3 thumb_rect=[71,2 7x24] track_rect=[71,0 9x80] expanded_gutter_rect=[65,0 15x80] expanded_thumb_rect=[67,2 11x24] scroll_size=0.23636363636363636 expanded_scroll_size=0.23636363636363636 max_scroll_offset=220 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay-PaintScrollBar@s2/c1/e0 scroll_node_index=s3 thumb_rect=[71,2 7x24] track_rect=[71,0 9x80] expanded_gutter_rect=[65,0 15x80] scroll_size=0.23636363636363636 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 CompositorWheelHitTestTarget@s0/e0 target_scroll_node_index=s0 rect=[0,0 800x600] owner=Viewport<#document> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[0,0 800x124] owner=BlockContainer<HTML> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x103] owner=BlockContainer<BODY> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 784x103] owner=BlockContainer(anonymous) phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s1/e0 target_scroll_node_index=s0 rect=[8,8 100x100] owner=SVGSVGBox<svg> phase=scroll-metadata+L0 StrokePath@s2/c0/e0 path_bounding_rect=[9.5,9.5 81x81] path_data=[path: M10 10L90 90] color=rgb(0, 0, 0) thickness=1 owner=SVGGeometryBox<path>#p phase=foreground+L0 CompositorWheelHitTestTarget@s2/c0/e0 target_scroll_node_index=s0 rect=[0,0 100x100] owner=SVGForeignObjectBox<foreignObject> phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s2/c1/e0 target_scroll_node_index=s3 rect=[0,0 80x80] owner=BlockContainer<DIV>#scroller phase=scroll-metadata+L0 CompositorWheelHitTestTarget@s3/c2/e0 target_scroll_node_index=s3 rect=[0,0 80x300] owner=BlockContainer<DIV> phase=scroll-metadata+L0 FillRect@s3/c2/e0 rect=[0,0 80x300] color=rgb(0, 0, 0) owner=BlockContainer<DIV> phase=background+L0 CompositorScrollbar@s2/c1/e0 scroll_node_index=s3 thumb_rect=[71,2 7x24] track_rect=[71,0 9x80] expanded_gutter_rect=[65,0 15x80] expanded_thumb_rect=[67,2 11x24] scroll_size=0.23636363636363636 expanded_scroll_size=0.23636363636363636 max_scroll_offset=220 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlay+L0 PaintScrollBar@s2/c1/e0 scroll_node_index=s3 thumb_rect=[71,2 7x24] track_rect=[71,0 9x80] expanded_gutter_rect=[65,0 15x80] scroll_size=0.23636363636363636 thumb_color=rgba(0, 0, 0, 0.5) thumb_outline_color=rgba(255, 255, 255, 0.25) track_color=rgba(0, 0, 0, 0.098) vertical=true owner=BlockContainer<DIV>#scroller phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/svg-in-img-is-recorded-without-visual-contexts.txt b/Tests/LibWeb/Text/expected/display_list/svg-in-img-is-recorded-without-visual-contexts.txtindex f87d212b2f9..edcb75fbc38 100644--- a/Tests/LibWeb/Text/expected/display_list/svg-in-img-is-recorded-without-visual-contexts.txt+++ b/Tests/LibWeb/Text/expected/display_list/svg-in-img-is-recorded-without-visual-contexts.txt@@ -5,13 +5,16 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintVectorImage@s1/e0 vector_image_id=svg1 rect=[8,13 300x200] recorded_size=[300x200] owner=ImageBox<IMG> phase=foreground- FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(255, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground- FillPath@s1/e0 path_bounding_rect=[0,100 100x100] path_data=[path: M0 100L100 100L100 200L0 200L0 100Z] color=rgb(255, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground- DrawIsolatedGroup@s1/e0 clip_rect=[0,0 300x200] inline_clips=[clip_path=[bounds: [4,10 55x56], path: M9.0903902 10.833505L58.900124 15.191292L54.542339 65.00103L4.7326026 60.643242L9.0903902 10.833505Z]] owner=ImageBox<IMG> phase=foreground- FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground- FillPath@s1/e0 path_bounding_rect=[0,100 100x100] path_data=[path: M0 100L100 100L100 200L0 200L0 100Z] color=rgb(0, 0, 255) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground- Mask:- FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.09039,10.833505] owner=ImageBox<IMG> phase=foreground+L0 PaintVectorImage@s1/e0 vector_image_id=svg1 rect=[8,13 300x200] recorded_size=[300x200] owner=ImageBox<IMG> phase=foreground+ FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(255, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground+ FillPath@s1/e0 path_bounding_rect=[0,100 100x100] path_data=[path: M0 100L100 100L100 200L0 200L0 100Z] color=rgb(255, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground+ DrawIsolatedGroup@s1/e0 clip_rect=[0,0 300x200] inline_clips=[clip_path=[bounds: [4,10 55x56], path: M9.0903902 10.833505L58.900124 15.191292L54.542339 65.00103L4.7326026 60.643242L9.0903902 10.833505Z]] owner=ImageBox<IMG> phase=foreground+ FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 128, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground+ FillPath@s1/e0 path_bounding_rect=[0,100 100x100] path_data=[path: M0 100L100 100L100 200L0 200L0 100Z] color=rgb(0, 0, 255) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.961947,0.8715575] owner=ImageBox<IMG> phase=foreground+ Mask:+ FillPath@s1/e0 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(0, 0, 0) inline_transform=[0.49809736,0.043577872,-0.043577872,0.49809736,9.09039,10.833505] owner=ImageBox<IMG> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/svg-overflow-on-inner-elements.txt b/Tests/LibWeb/Text/expected/display_list/svg-overflow-on-inner-elements.txtindex 837ecd96a45..e9c686039dc 100644--- a/Tests/LibWeb/Text/expected/display_list/svg-overflow-on-inner-elements.txt+++ b/Tests/LibWeb/Text/expected/display_list/svg-overflow-on-inner-elements.txt@@ -8,6 +8,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s2/c0/e0 path_bounding_rect=[10,10 100x100] path_data=[path: M10 10L110 10L110 110L10 110L10 10Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s2/c0/e0 path_bounding_rect=[10,10 100x100] path_data=[path: M10 10L110 10L110 110L10 110L10 10Z] color=rgb(0, 128, 0) owner=SVGGeometryBox<rect> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/svg-transform-with-opacity.txt b/Tests/LibWeb/Text/expected/display_list/svg-transform-with-opacity.txtindex a875ada6a7f..e21dc8e4589 100644--- a/Tests/LibWeb/Text/expected/display_list/svg-transform-with-opacity.txt+++ b/Tests/LibWeb/Text/expected/display_list/svg-transform-with-opacity.txt@@ -10,6 +10,9 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[][e1 in s2 out=c0] effects=[opacity=0.5] (SVGGeometryBox<rect>)+Layers:+ [L0] base space=viewport+DisplayList:-FillPath@s3/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(255, 0, 0) owner=SVGGeometryBox<rect> phase=foreground+L0 FillPath@s3/c0/e1 path_bounding_rect=[0,0 100x100] path_data=[path: M0 0L100 0L100 100L0 100L0 0Z] color=rgb(255, 0, 0) owner=SVGGeometryBox<rect> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/text-decoration-thin-lines-cover-whole-pixels.txt b/Tests/LibWeb/Text/expected/display_list/text-decoration-thin-lines-cover-whole-pixels.txtindex b4f72ef2c97..3e6e6318499 100644--- a/Tests/LibWeb/Text/expected/display_list/text-decoration-thin-lines-cover-whole-pixels.txt+++ b/Tests/LibWeb/Text/expected/display_list/text-decoration-thin-lines-cover-whole-pixels.txt@@ -5,12 +5,15 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,14 45x14] glyph_bounding_rect=[8,14 48x13] translation=[8,25] color=rgb(0, 0, 0) text="double" owner=BlockContainer<P> phase=text-fragment-FillRect@s1/e0 rect=[8,27 44x1] color=rgb(0, 0, 0) owner=BlockContainer<P> phase=text-fragment-FillRect@s1/e0 rect=[8,29 44x1] color=rgb(0, 0, 0) owner=BlockContainer<P> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,42 43x14] glyph_bounding_rect=[8,42 47x13] translation=[8,53] color=rgb(0, 0, 0) text="dotted" owner=BlockContainer<P> phase=text-fragment-StrokePath@s1/e0 dash_array=[1, 1] path_bounding_rect=[7.5,55 43x1] path_data=[path: M8 55.5L50 55.5] color=rgb(0, 0, 0) thickness=1 owner=BlockContainer<P> phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,70 46x14] glyph_bounding_rect=[8,70 51x13] translation=[8,81] color=rgb(0, 0, 0) text="dashed" owner=BlockContainer<P> phase=text-fragment-StrokePath@s1/e0 dash_array=[2, 2] path_bounding_rect=[7.5,83 47x1] path_data=[path: M8 83.5L54 83.5] color=rgb(0, 0, 0) thickness=1 owner=BlockContainer<P> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,14 45x14] glyph_bounding_rect=[8,14 48x13] translation=[8,25] color=rgb(0, 0, 0) text="double" owner=BlockContainer<P> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,27 44x1] color=rgb(0, 0, 0) owner=BlockContainer<P> phase=text-fragment+L0 FillRect@s1/e0 rect=[8,29 44x1] color=rgb(0, 0, 0) owner=BlockContainer<P> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,42 43x14] glyph_bounding_rect=[8,42 47x13] translation=[8,53] color=rgb(0, 0, 0) text="dotted" owner=BlockContainer<P> phase=text-fragment+L0 StrokePath@s1/e0 dash_array=[1, 1] path_bounding_rect=[7.5,55 43x1] path_data=[path: M8 55.5L50 55.5] color=rgb(0, 0, 0) thickness=1 owner=BlockContainer<P> phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=6 rect=[8,70 46x14] glyph_bounding_rect=[8,70 51x13] translation=[8,81] color=rgb(0, 0, 0) text="dashed" owner=BlockContainer<P> phase=text-fragment+L0 StrokePath@s1/e0 dash_array=[2, 2] path_bounding_rect=[7.5,83 47x1] path_data=[path: M8 83.5L54 83.5] color=rgb(0, 0, 0) thickness=1 owner=BlockContainer<P> phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/text-decoration-underline-partial-selection.txt b/Tests/LibWeb/Text/expected/display_list/text-decoration-underline-partial-selection.txtindex 3d5fff8763b..9f890b8c4aa 100644--- a/Tests/LibWeb/Text/expected/display_list/text-decoration-underline-partial-selection.txt+++ b/Tests/LibWeb/Text/expected/display_list/text-decoration-underline-partial-selection.txt@@ -5,14 +5,17 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[9,-15 60x91]] text="x" owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[8,65 37x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[57,65 10x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[116,-15 61x91]] text="x" owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[116,65 37x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[165,65 12x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[69,-17 47x100] color=rgba(101, 2, 0, 0.8) owner=BlockContainer(anonymous) phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[69,-15 47x91]] text="g" owner=BlockContainer(anonymous) phase=text-fragment-FillRect@s1/e0 rect=[109,65 7x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[9,-15 60x91]] text="x" owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[8,65 37x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[57,65 10x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[116,-15 61x91]] text="x" owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[116,65 37x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[165,65 12x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[69,-17 47x100] color=rgba(101, 2, 0, 0.8) owner=BlockContainer(anonymous) phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[8,-17 169x100] glyph_bounding_rect=[9,-15 191x91] translation=[8,63] color=rgb(0, 0, 0) inline_clips=[clip=[69,-15 47x91]] text="g" owner=BlockContainer(anonymous) phase=text-fragment+L0 FillRect@s1/e0 rect=[109,65 7x10] color=rgb(0, 0, 0) owner=BlockContainer(anonymous) phase=text-fragmentdiff --git a/Tests/LibWeb/Text/expected/display_list/text-input-clip-is-not-rounded.txt b/Tests/LibWeb/Text/expected/display_list/text-input-clip-is-not-rounded.txtindex 37815e1252d..8c4b88efcf9 100644--- a/Tests/LibWeb/Text/expected/display_list/text-input-clip-is-not-rounded.txt+++ b/Tests/LibWeb/Text/expected/display_list/text-input-clip-is-not-rounded.txt@@ -8,8 +8,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/c1/e0 rect=[8,11 23x13] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground-DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=3 rect=[8,11 23x13] glyph_bounding_rect=[8,11 26x12] translation=[8,21] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[6,9 168x17] corner_radii=[8x8,8x8,8x8,8x8] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT>#input phase=outline+L0 FillRect@s1/c1/e0 rect=[8,11 23x13] color=rgba(101, 2, 0, 0.8) owner=BlockContainer<DIV> phase=foreground+L0 DrawGlyphRun@s1/c1/e0 font_id=font1 glyphs=3 rect=[8,11 23x13] glyph_bounding_rect=[8,11 26x12] translation=[8,21] color=rgb(0, 0, 0) text="abc" owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[6,9 168x17] corner_radii=[8x8,8x8,8x8,8x8] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextInputBox<INPUT>#input phase=outlinediff --git a/Tests/LibWeb/Text/expected/display_list/text-shadow-multiple-layers.txt b/Tests/LibWeb/Text/expected/display_list/text-shadow-multiple-layers.txtindex 2ead60fce02..35976fd81cc 100644--- a/Tests/LibWeb/Text/expected/display_list/text-shadow-multiple-layers.txt+++ b/Tests/LibWeb/Text/expected/display_list/text-shadow-multiple-layers.txt@@ -5,7 +5,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintTextShadow@s1/e0 font_id=font1 glyphs=7 layers=[{blur_radius=4 color=rgb(0, 0, 0)}, {offset=[-1,-1] rounded_offset=[-1,-1] color=rgba(45, 45, 45, 0.6)}, {offset=[1,1] rounded_offset=[1,1] color=rgba(45, 45, 45, 0.6)}, {offset=[-1,0] rounded_offset=[-1,0] color=rgba(0, 0, 0, 0.5)}, {offset=[1,0] rounded_offset=[1,0] color=rgba(0, 0, 0, 0.5)}] shadows_bounding_rect=[-8,-8 100x36] rect=[0,0 84x20] translation=[0,16] text="Joensuu" owner=BlockContainer<P> phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[0,0 84x20] glyph_bounding_rect=[0,0 88x18] translation=[0,16] color=rgb(255, 255, 255) text="Joensuu" owner=BlockContainer<P> phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=7 layers=[{blur_radius=4 color=rgb(0, 0, 0)}, {offset=[-1,-1] rounded_offset=[-1,-1] color=rgba(45, 45, 45, 0.6)}, {offset=[1,1] rounded_offset=[1,1] color=rgba(45, 45, 45, 0.6)}, {offset=[-1,0] rounded_offset=[-1,0] color=rgba(0, 0, 0, 0.5)}, {offset=[1,0] rounded_offset=[1,0] color=rgba(0, 0, 0, 0.5)}] shadows_bounding_rect=[-8,-8 100x36] rect=[0,0 84x20] translation=[0,16] text="Joensuu" owner=BlockContainer<P> phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=7 rect=[0,0 84x20] glyph_bounding_rect=[0,0 88x18] translation=[0,16] color=rgb(255, 255, 255) text="Joensuu" owner=BlockContainer<P> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/text-shadow-vertical-writing-mode.txt b/Tests/LibWeb/Text/expected/display_list/text-shadow-vertical-writing-mode.txtindex 109ec1b2b27..bc399dbb236 100644--- a/Tests/LibWeb/Text/expected/display_list/text-shadow-vertical-writing-mode.txt+++ b/Tests/LibWeb/Text/expected/display_list/text-shadow-vertical-writing-mode.txt@@ -5,7 +5,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(255, 0, 0)}] shadows_bounding_rect=[762,2 20x35] rect=[760,0 20x35] translation=[760,16] orientation=Vertical text="abc" owner=BlockContainer<P> phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[760,0 20x35] glyph_bounding_rect=[762,0 18x40] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical text="abc" owner=BlockContainer<P> phase=foreground+L0 PaintTextShadow@s1/e0 font_id=font1 glyphs=3 layers=[{offset=[2,2] rounded_offset=[2,2] color=rgb(255, 0, 0)}] shadows_bounding_rect=[762,2 20x35] rect=[760,0 20x35] translation=[760,16] orientation=Vertical text="abc" owner=BlockContainer<P> phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=3 rect=[760,0 20x35] glyph_bounding_rect=[762,0 18x40] translation=[760,16] color=rgb(0, 0, 0) orientation=Vertical text="abc" owner=BlockContainer<P> phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/textarea-caret.txt b/Tests/LibWeb/Text/expected/display_list/textarea-caret.txtindex 8f7ca7eda76..759067bbdaa 100644--- a/Tests/LibWeb/Text/expected/display_list/textarea-caret.txt+++ b/Tests/LibWeb/Text/expected/display_list/textarea-caret.txt@@ -7,16 +7,19 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRectWithRoundedCorners@s1/e0 rect=[8,8 106x34] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA> phase=background-FillRoundedRectRing@s1/e0 rect=[8,8 106x34] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA> phase=border-DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=5 rect=[11,11 31x14] glyph_bounding_rect=[11,12 33x12] translation=[11,22] color=rgb(0, 0, 0) text="hello" owner=BlockContainer<DIV> phase=foreground-PaintCaret@s1/c0/e0 rect=[11,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground-FillRoundedRectRing@s1/e0 rect=[6,6 110x38] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA> phase=outline-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[109,39] to=[111,37] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[108,39] to=[111,36] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[106,39] to=[111,34] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[105,39] to=[111,33] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay-DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[103,39] to=[111,31] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay-DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[102,39] to=[111,30] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 FillRectWithRoundedCorners@s1/e0 rect=[8,8 106x34] color=rgb(255, 255, 255) corner_radii=[4x4,4x4,4x4,4x4] owner=TextAreaBox<TEXTAREA> phase=background+L0 FillRoundedRectRing@s1/e0 rect=[8,8 106x34] corner_radii=[4x4,4x4,4x4,4x4] top_width=1 right_width=1 bottom_width=1 left_width=1 color=rgb(118, 118, 118) owner=TextAreaBox<TEXTAREA> phase=border+L0 DrawGlyphRun@s1/c0/e0 font_id=font1 glyphs=5 rect=[11,11 31x14] glyph_bounding_rect=[11,12 33x12] translation=[11,22] color=rgb(0, 0, 0) text="hello" owner=BlockContainer<DIV> phase=foreground+L0 PaintCaret@s1/c0/e0 rect=[11,11 1x14] color=rgb(0, 0, 0) blink_cycle_start_time_ns=t1 owner=BlockContainer<DIV> phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[6,6 110x38] corner_radii=[6x6,6x6,6x6,6x6] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(61, 174, 233) owner=TextAreaBox<TEXTAREA> phase=outline+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[109,39] to=[111,37] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[108,39] to=[111,36] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[106,39] to=[111,34] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[105,39] to=[111,33] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 DrawLine@s1/e0 color=rgba(255, 255, 255, 0.392) from=[103,39] to=[111,31] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlay+L0 DrawLine@s1/e0 color=rgba(0, 0, 0, 0.392) from=[102,39] to=[111,30] thickness=1 owner=TextAreaBox<TEXTAREA> phase=overlaydiff --git a/Tests/LibWeb/Text/expected/display_list/three-way-branch.txt b/Tests/LibWeb/Text/expected/display_list/three-way-branch.txtindex 153d3ca0fc8..007b48bb3bd 100644--- a/Tests/LibWeb/Text/expected/display_list/three-way-branch.txt+++ b/Tests/LibWeb/Text/expected/display_list/three-way-branch.txt@@ -8,11 +8,14 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 60x60] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.box.a phase=background-DrawGlyphRun@s2/e0 font_id=font1 glyphs=1 rect=[8,8 7x16] glyph_bounding_rect=[8,8 13x15] translation=[8,21] color=rgb(0, 0, 0) text="1" owner=BlockContainer<DIV>.box.a phase=foreground-FillRect@s3/e0 rect=[73,8 60x60] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.box.b phase=background-DrawGlyphRun@s3/e0 font_id=font1 glyphs=1 rect=[73,8 9x16] glyph_bounding_rect=[73,8 13x15] translation=[73,21] color=rgb(0, 0, 0) text="2" owner=BlockContainer<DIV>.box.b phase=foreground-FillRect@s4/e0 rect=[138,8 60x60] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box.c phase=background-DrawGlyphRun@s4/e0 font_id=font1 glyphs=1 rect=[138,8 10x16] glyph_bounding_rect=[138,8 13x15] translation=[138,21] color=rgb(0, 0, 0) text="3" owner=BlockContainer<DIV>.box.c phase=foreground+L0 FillRect@s2/e0 rect=[8,8 60x60] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.box.a phase=background+L0 DrawGlyphRun@s2/e0 font_id=font1 glyphs=1 rect=[8,8 7x16] glyph_bounding_rect=[8,8 13x15] translation=[8,21] color=rgb(0, 0, 0) text="1" owner=BlockContainer<DIV>.box.a phase=foreground+L0 FillRect@s3/e0 rect=[73,8 60x60] color=rgb(0, 128, 0) owner=BlockContainer<DIV>.box.b phase=background+L0 DrawGlyphRun@s3/e0 font_id=font1 glyphs=1 rect=[73,8 9x16] glyph_bounding_rect=[73,8 13x15] translation=[73,21] color=rgb(0, 0, 0) text="2" owner=BlockContainer<DIV>.box.b phase=foreground+L0 FillRect@s4/e0 rect=[138,8 60x60] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box.c phase=background+L0 DrawGlyphRun@s4/e0 font_id=font1 glyphs=1 rect=[138,8 10x16] glyph_bounding_rect=[138,8 13x15] translation=[138,21] color=rgb(0, 0, 0) text="3" owner=BlockContainer<DIV>.box.c phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/transform-basic.txt b/Tests/LibWeb/Text/expected/display_list/transform-basic.txtindex 3ec3d1b6ad5..e6cf5c42b5f 100644--- a/Tests/LibWeb/Text/expected/display_list/transform-basic.txt+++ b/Tests/LibWeb/Text/expected/display_list/transform-basic.txt@@ -6,7 +6,10 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box phase=background-DrawGlyphRun@s2/e0 font_id=font1 glyphs=4 rect=[8,8 38x16] glyph_bounding_rect=[8,8 44x15] translation=[8,21] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>.box phase=foreground+L0 FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 0, 255) owner=BlockContainer<DIV>.box phase=background+L0 DrawGlyphRun@s2/e0 font_id=font1 glyphs=4 rect=[8,8 38x16] glyph_bounding_rect=[8,8 44x15] translation=[8,21] color=rgb(0, 0, 0) text="Text" owner=BlockContainer<DIV>.box phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/transform-invertibility-invalidation.txt b/Tests/LibWeb/Text/expected/display_list/transform-invertibility-invalidation.txtindex 956874be592..5f89be9d5fd 100644--- a/Tests/LibWeb/Text/expected/display_list/transform-invertibility-invalidation.txt+++ b/Tests/LibWeb/Text/expected/display_list/transform-invertibility-invalidation.txt@@ -3,6 +3,9 @@ AccumulatedVisualContext Tree:spatial:[s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+Layers:+ [L0] single layer replaying the whole list: empty display list+DisplayList:After transform change:@@ -14,6 +17,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=background+L0 FillRect@s2/e0 rect=[8,8 100x100] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#box phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/transform-nested.txt b/Tests/LibWeb/Text/expected/display_list/transform-nested.txtindex f043c7a9d19..0728544c762 100644--- a/Tests/LibWeb/Text/expected/display_list/transform-nested.txt+++ b/Tests/LibWeb/Text/expected/display_list/transform-nested.txt@@ -7,8 +7,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/e0 rect=[8,8 200x200] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.outer phase=background-FillRect@s3/e0 rect=[8,8 100x100] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.inner phase=background-DrawGlyphRun@s3/e0 font_id=font1 glyphs=6 rect=[8,8 52x16] glyph_bounding_rect=[8,8 57x15] translation=[8,21] color=rgb(0, 0, 0) text="Nested" owner=BlockContainer<DIV>.inner phase=foreground+L0 FillRect@s2/e0 rect=[8,8 200x200] color=rgb(173, 216, 230) owner=BlockContainer<DIV>.outer phase=background+L0 FillRect@s3/e0 rect=[8,8 100x100] color=rgb(255, 127, 80) owner=BlockContainer<DIV>.inner phase=background+L0 DrawGlyphRun@s3/e0 font_id=font1 glyphs=6 rect=[8,8 52x16] glyph_bounding_rect=[8,8 57x15] translation=[8,21] color=rgb(0, 0, 0) text="Nested" owner=BlockContainer<DIV>.inner phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/transform-with-clip.txt b/Tests/LibWeb/Text/expected/display_list/transform-with-clip.txtindex 2c820978615..d84399f76a4 100644--- a/Tests/LibWeb/Text/expected/display_list/transform-with-clip.txt+++ b/Tests/LibWeb/Text/expected/display_list/transform-with-clip.txt@@ -12,8 +12,12 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[10,10 150x150] min_scroll_offset=[0,0] max_scroll_offset=[70,70] is_viewport=false+Layers:+ [L0] base space=viewport+ [L1] painted space=scroller@s2 in viewport composited within [10,10 150x150] of viewport+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 154x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.container phase=border-FillRect@s3/c0/e0 rect=[10,10 200x200] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.transformed phase=background-DrawGlyphRun@s3/c0/e0 font_id=font1 glyphs=21 rect=[10,10 185x16] glyph_bounding_rect=[10,10 190x15] translation=[10,23] color=rgb(0, 0, 0) text="Clipped + Transformed" owner=BlockContainer<DIV>.transformed phase=foreground+L0 FillRoundedRectRing@s1/e0 rect=[8,8 154x154] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 0) owner=BlockContainer<DIV>.container phase=border+L1 FillRect@s3/c0/e0 rect=[10,10 200x200] color=rgb(144, 238, 144) owner=BlockContainer<DIV>.transformed phase=background+L1 DrawGlyphRun@s3/c0/e0 font_id=font1 glyphs=21 rect=[10,10 185x16] glyph_bounding_rect=[10,10 190x15] translation=[10,23] color=rgb(0, 0, 0) text="Clipped + Transformed" owner=BlockContainer<DIV>.transformed phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/uniform-solid-border-ring.txt b/Tests/LibWeb/Text/expected/display_list/uniform-solid-border-ring.txtindex 8a909f3472a..e5ec1c5e8a6 100644--- a/Tests/LibWeb/Text/expected/display_list/uniform-solid-border-ring.txt+++ b/Tests/LibWeb/Text/expected/display_list/uniform-solid-border-ring.txt@@ -8,24 +8,27 @@ AccumulatedVisualContext Tree:ScrollNodes:ScrollNode scroll_node_index=s1 parent_scroll_node_index=s0 scrollport_rect=[0,0 800x600] min_scroll_offset=[0,0] max_scroll_offset=[0,20] is_viewport=true+Layers:+ [L1] base space=document+DisplayList:-FillRoundedRectRing@s1/e0 rect=[8,8 106x46] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.solid phase=border-FillRoundedRectRing@s1/e0 rect=[8,64 104x44] corner_radii=[8x8,8x8,8x8,8x8] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.rounded phase=border-FillRoundedRectRing@s1/e0 rect=[8,118 100x41] bottom_width=1 color=rgb(0, 128, 0) owner=BlockContainer<DIV>.bottom-only phase=border-FillRoundedRectRing@s1/e0 rect=[8,169 104x44] corner_radii=[10x10,10x10,10x10,10x10] top_width=4 left_width=4 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.partial-rounded phase=border-FillRoundedRectRing@s1/e0 rect=[8,223 106x44] corner_radii=[12x6,12x6,12x6,12x6] top_width=1 right_width=2 bottom_width=3 left_width=4 color=rgb(255, 165, 0) owner=BlockContainer<DIV>.uneven-widths phase=border-FillRoundedRectRing@s1/e0 rect=[8,277 118x58] corner_radii=[10x10,10x10,10x10,10x10] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(128, 0, 128) owner=BlockContainer<DIV>.double phase=border-FillRoundedRectRing@s1/e0 rect=[14,283 106x46] corner_radii=[4x4,4x4,4x4,4x4] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(128, 0, 128) owner=BlockContainer<DIV>.double phase=border-FillRoundedRectRing@s1/e0 rect=[8,345 104x44] top_width=4 left_width=4 color=rgb(43, 43, 43) owner=BlockContainer<DIV>.inset-top-left-only phase=border-FillPath@s1/e0 path_bounding_rect=[8,399 108x48] path_data=[path: M116 399L116 399L112 403L112 443L116 447L116 447M116 447L116 447L112 443L12 443L8 447L8 447] color=rgb(128, 128, 128) winding_rule=EvenOdd owner=BlockContainer<DIV>.inset phase=border-FillPath@s1/e0 path_bounding_rect=[8,399 108x48] path_data=[path: M8 447L8 447L12 443L12 403L8 399L8 399M8 399L8 399L12 403L112 403L116 399L116 399] color=rgb(43, 43, 43) winding_rule=EvenOdd owner=BlockContainer<DIV>.inset phase=border-FillPath@s1/e0 path_bounding_rect=[110,457 2x44] path_data=[path: M112 457L112 457L110 459L110 499L112 501L112 501] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border-FillPath@s1/e0 path_bounding_rect=[8,499 104x2] path_data=[path: M112 501L112 501L110 499L10 499L8 501L8 501] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border-FillPath@s1/e0 path_bounding_rect=[8,457 2x44] path_data=[path: M8 501L8 501L10 499L10 459L8 457L8 457] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border-FillPath@s1/e0 path_bounding_rect=[8,457 104x2] path_data=[path: M8 457L8 457L10 459L110 459L112 457L112 457] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border-FillPath@s1/e0 path_bounding_rect=[8,511 106x46] path_data=[path: M8 511L8 511L11 514L111 514L114 511L114 511M114 511L114 511L111 514L111 554L114 557L114 557] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border-FillPath@s1/e0 path_bounding_rect=[8,556 106x1] path_data=[path: M114 557L114 557L113 556L9 556L8 557L8 557] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border-FillPath@s1/e0 path_bounding_rect=[10,554 102x1] path_data=[path: M112 555L112 555L111 554L11 554L10 555L10 555] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border-FillPath@s1/e0 path_bounding_rect=[8,511 3x46] path_data=[path: M8 557L8 557L11 554L11 514L8 511L8 511] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border-FillRoundedRectRing@s1/e0 rect=[4,563 108x48] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 128, 128) owner=BlockContainer<DIV>.outlined phase=outline+L1 FillRoundedRectRing@s1/e0 rect=[8,8 106x46] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.solid phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,64 104x44] corner_radii=[8x8,8x8,8x8,8x8] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 0, 255) owner=BlockContainer<DIV>.rounded phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,118 100x41] bottom_width=1 color=rgb(0, 128, 0) owner=BlockContainer<DIV>.bottom-only phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,169 104x44] corner_radii=[10x10,10x10,10x10,10x10] top_width=4 left_width=4 color=rgb(255, 0, 0) owner=BlockContainer<DIV>.partial-rounded phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,223 106x44] corner_radii=[12x6,12x6,12x6,12x6] top_width=1 right_width=2 bottom_width=3 left_width=4 color=rgb(255, 165, 0) owner=BlockContainer<DIV>.uneven-widths phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,277 118x58] corner_radii=[10x10,10x10,10x10,10x10] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(128, 0, 128) owner=BlockContainer<DIV>.double phase=border+L1 FillRoundedRectRing@s1/e0 rect=[14,283 106x46] corner_radii=[4x4,4x4,4x4,4x4] top_width=3 right_width=3 bottom_width=3 left_width=3 color=rgb(128, 0, 128) owner=BlockContainer<DIV>.double phase=border+L1 FillRoundedRectRing@s1/e0 rect=[8,345 104x44] top_width=4 left_width=4 color=rgb(43, 43, 43) owner=BlockContainer<DIV>.inset-top-left-only phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,399 108x48] path_data=[path: M116 399L116 399L112 403L112 443L116 447L116 447M116 447L116 447L112 443L12 443L8 447L8 447] color=rgb(128, 128, 128) winding_rule=EvenOdd owner=BlockContainer<DIV>.inset phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,399 108x48] path_data=[path: M8 447L8 447L12 443L12 403L8 399L8 399M8 399L8 399L12 403L112 403L116 399L116 399] color=rgb(43, 43, 43) winding_rule=EvenOdd owner=BlockContainer<DIV>.inset phase=border+L1 FillPath@s1/e0 path_bounding_rect=[110,457 2x44] path_data=[path: M112 457L112 457L110 459L110 499L112 501L112 501] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,499 104x2] path_data=[path: M112 501L112 501L110 499L10 499L8 501L8 501] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,457 2x44] path_data=[path: M8 501L8 501L10 499L10 459L8 457L8 457] color=rgb(0, 0, 255) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,457 104x2] path_data=[path: M8 457L8 457L10 459L110 459L112 457L112 457] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.two-colors phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,511 106x46] path_data=[path: M8 511L8 511L11 514L111 514L114 511L114 511M114 511L114 511L111 514L111 554L114 557L114 557] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,556 106x1] path_data=[path: M114 557L114 557L113 556L9 556L8 557L8 557] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border+L1 FillPath@s1/e0 path_bounding_rect=[10,554 102x1] path_data=[path: M112 555L112 555L111 554L11 554L10 555L10 555] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border+L1 FillPath@s1/e0 path_bounding_rect=[8,511 3x46] path_data=[path: M8 557L8 557L11 554L11 514L8 511L8 511] color=rgb(255, 0, 0) winding_rule=EvenOdd owner=BlockContainer<DIV>.mixed-styles phase=border+L1 FillRoundedRectRing@s1/e0 rect=[4,563 108x48] top_width=2 right_width=2 bottom_width=2 left_width=2 color=rgb(0, 128, 128) owner=BlockContainer<DIV>.outlined phase=outlinediff --git a/Tests/LibWeb/Text/expected/display_list/will-change-visual-context-nodes.txt b/Tests/LibWeb/Text/expected/display_list/will-change-visual-context-nodes.txtindex 6f1c3831ab9..5bc6570d635 100644--- a/Tests/LibWeb/Text/expected/display_list/will-change-visual-context-nodes.txt+++ b/Tests/LibWeb/Text/expected/display_list/will-change-visual-context-nodes.txt@@ -9,10 +9,13 @@ AccumulatedVisualContext Tree:[e1 in s1] effects=[] (BlockContainer<DIV>#opacity)[e2 in s1] effects=[] (BlockContainer<DIV>#filter)+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[0,200 50x50] color=rgb(128, 128, 128) owner=BlockContainer<DIV>#other phase=background-FillRect@s2/e0 rect=[0,0 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#transform phase=background-FillRect@s3/e0 rect=[0,50 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#translate phase=background-FillRect@s1/e1 rect=[0,100 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>#opacity phase=background-FillRect@s1/e2 rect=[0,150 50x50] color=rgb(255, 255, 0) owner=BlockContainer<DIV>#filter phase=background+L0 FillRect@s1/e0 rect=[0,200 50x50] color=rgb(128, 128, 128) owner=BlockContainer<DIV>#other phase=background+L0 FillRect@s2/e0 rect=[0,0 50x50] color=rgb(0, 128, 0) owner=BlockContainer<DIV>#transform phase=background+L0 FillRect@s3/e0 rect=[0,50 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#translate phase=background+L0 FillRect@s1/e1 rect=[0,100 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>#opacity phase=background+L0 FillRect@s1/e2 rect=[0,150 50x50] color=rgb(255, 255, 0) owner=BlockContainer<DIV>#filter phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/z-index-change-no-double-paint.txt b/Tests/LibWeb/Text/expected/display_list/z-index-change-no-double-paint.txtindex 97145cf9200..4d8488202c3 100644--- a/Tests/LibWeb/Text/expected/display_list/z-index-change-no-double-paint.txt+++ b/Tests/LibWeb/Text/expected/display_list/z-index-change-no-double-paint.txt@@ -6,8 +6,11 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#target.target phase=background+L0 FillRect@s1/e0 rect=[8,8 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#target.target phase=backgroundAfter z-index change:AccumulatedVisualContext Tree:@@ -17,6 +20,9 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#target.target phase=background+L0 FillRect@s1/e0 rect=[8,8 50x50] color=rgb(0, 0, 255) owner=BlockContainer<DIV>#target.target phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/display_list/zero-area-clip-commands.txt b/Tests/LibWeb/Text/expected/display_list/zero-area-clip-commands.txtindex d29da5eb1ab..a0c5edc4352 100644--- a/Tests/LibWeb/Text/expected/display_list/zero-area-clip-commands.txt+++ b/Tests/LibWeb/Text/expected/display_list/zero-area-clip-commands.txt@@ -15,8 +15,11 @@ ScrollNodes:ScrollNode scroll_node_index=s2 parent_scroll_node_index=s0 scrollport_rect=[8,8 0x100] min_scroll_offset=[0,0] max_scroll_offset=[50,0] is_viewport=falseScrollNode scroll_node_index=s3 parent_scroll_node_index=s0 scrollport_rect=[8,108 100x0] min_scroll_offset=[0,0] max_scroll_offset=[0,50] is_viewport=false+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s2/c0/e0 rect=[8,8 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=background-FillRect@s3/c1/e0 rect=[8,108 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=background-FillRect@s1/c2/e0 rect=[8,108 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=background+L0 FillRect@s2/c0/e0 rect=[8,8 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=background+L0 FillRect@s3/c1/e0 rect=[8,108 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=background+L0 FillRect@s1/c2/e0 rect=[8,108 50x50] color=rgb(255, 0, 0) owner=BlockContainer<DIV>.child phase=backgrounddiff --git a/Tests/LibWeb/Text/expected/text-transform-contextual-selection-offset-mapping.txt b/Tests/LibWeb/Text/expected/text-transform-contextual-selection-offset-mapping.txtindex 09d980b94f2..4b23e964657 100644--- a/Tests/LibWeb/Text/expected/text-transform-contextual-selection-offset-mapping.txt+++ b/Tests/LibWeb/Text/expected/text-transform-contextual-selection-offset-mapping.txt@@ -5,9 +5,12 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,16 55x16] glyph_bounding_rect=[8,-8 59x39] translation=[8,29] color=rgb(0, 0, 0) text="i̇́ alpha" owner=BlockContainer<P>#selection-target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,32 35x16] glyph_bounding_rect=[8,32 38x15] translation=[8,45] color=rgb(0, 0, 0) text="beta" owner=BlockContainer<P>#selection-target phase=foreground-FillRect@s1/e0 rect=[8,48 51x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#selection-target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,48 51x16] glyph_bounding_rect=[8,48 55x15] translation=[8,61] color=rgb(0, 0, 0) text="gamma" owner=BlockContainer<P>#selection-target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=9 rect=[8,16 55x16] glyph_bounding_rect=[8,-8 59x39] translation=[8,29] color=rgb(0, 0, 0) text="i̇́ alpha" owner=BlockContainer<P>#selection-target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[8,32 35x16] glyph_bounding_rect=[8,32 38x15] translation=[8,45] color=rgb(0, 0, 0) text="beta" owner=BlockContainer<P>#selection-target phase=foreground+L0 FillRect@s1/e0 rect=[8,48 51x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#selection-target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=5 rect=[8,48 51x16] glyph_bounding_rect=[8,48 55x15] translation=[8,61] color=rgb(0, 0, 0) text="gamma" owner=BlockContainer<P>#selection-target phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/text-transform-selection-offset-mapping.txt b/Tests/LibWeb/Text/expected/text-transform-selection-offset-mapping.txtindex f946b97cf43..b600f28ecf7 100644--- a/Tests/LibWeb/Text/expected/text-transform-selection-offset-mapping.txt+++ b/Tests/LibWeb/Text/expected/text-transform-selection-offset-mapping.txt@@ -5,11 +5,14 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-FillRect@s1/e0 rect=[8,8 24x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#selection-target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,8 24x16] glyph_bounding_rect=[8,8 25x15] translation=[8,21] color=rgb(0, 0, 0) text="SS" owner=BlockContainer<P>#selection-target phase=foreground-DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,40 22x16] glyph_bounding_rect=[8,40 25x15] translation=[8,53] color=rgb(4, 5, 6) text="Ss" owner=BlockContainer<P>#capitalized phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) text="ello" owner=BlockContainer<P>#capitalized phase=text-fragment+L0 FillRect@s1/e0 rect=[8,8 24x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#selection-target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,8 24x16] glyph_bounding_rect=[8,8 25x15] translation=[8,21] color=rgb(0, 0, 0) text="SS" owner=BlockContainer<P>#selection-target phase=foreground+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,40 22x16] glyph_bounding_rect=[8,40 25x15] translation=[8,53] color=rgb(4, 5, 6) text="Ss" owner=BlockContainer<P>#capitalized phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) text="ello" owner=BlockContainer<P>#capitalized phase=text-fragmentAccumulatedVisualContext Tree:spatial:@@ -18,11 +21,14 @@ AccumulatedVisualContext Tree:effects:[e0 in s0] effects=[]+Layers:+ [L0] base space=viewport+DisplayList:-DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,8 24x16] glyph_bounding_rect=[8,8 25x15] translation=[8,21] color=rgb(0, 0, 0) text="SS" owner=BlockContainer<P>#selection-target phase=foreground-FillRect@s1/e0 rect=[8,40 21x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#capitalized phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,40 22x16] glyph_bounding_rect=[8,40 25x15] translation=[8,53] color=rgb(4, 5, 6) text="Ss" owner=BlockContainer<P>#capitalized phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) inline_clips=[clip=[38,40 19x15]] text="llo" owner=BlockContainer<P>#capitalized phase=text-fragment-FillRect@s1/e0 rect=[29,40 9x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#capitalized phase=text-fragment-DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) inline_clips=[clip=[29,40 9x15]] text="e" owner=BlockContainer<P>#capitalized phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,8 24x16] glyph_bounding_rect=[8,8 25x15] translation=[8,21] color=rgb(0, 0, 0) text="SS" owner=BlockContainer<P>#selection-target phase=foreground+L0 FillRect@s1/e0 rect=[8,40 21x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#capitalized phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=2 rect=[8,40 22x16] glyph_bounding_rect=[8,40 25x15] translation=[8,53] color=rgb(4, 5, 6) text="Ss" owner=BlockContainer<P>#capitalized phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) inline_clips=[clip=[38,40 19x15]] text="llo" owner=BlockContainer<P>#capitalized phase=text-fragment+L0 FillRect@s1/e0 rect=[29,40 9x16] color=rgb(1, 2, 3) owner=BlockContainer<P>#capitalized phase=text-fragment+L0 DrawGlyphRun@s1/e0 font_id=font1 glyphs=4 rect=[29,40 28x16] glyph_bounding_rect=[29,40 31x15] translation=[29.3125,53] color=rgb(0, 0, 0) inline_clips=[clip=[29,40 9x15]] text="e" owner=BlockContainer<P>#capitalized phase=text-fragmentdiff --git a/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html b/Tests/LibWeb/Text/input/css/compositor-background-color-animation.htmlindex adcb5c1c39e..568246a4e87 100644--- a/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html+++ b/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html@@ -124,7 +124,7 @@const initialSamples = parseStyleTrace(internals.takeStyleTrace()).filter(event => event.outcome?.startsWith("sampled"));const initialCompositorAnimations = compositorAnimations();const legacyNodes = visualContextNodes(document.querySelector("#legacy"));- const displayList = internals.dumpDisplayList();+ const displayList = internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "");const transparentFillIsRetained = displayList.split("\n").some(line =>line.startsWith("FillRectWithRoundedCorners") && line.includes("color=rgba(0, 0, 0, 0)"));const rootNodes = visualContextNodes(document.documentElement);diff --git a/Tests/LibWeb/Text/input/display_list/clipped-svg-background-stays-vector.html b/Tests/LibWeb/Text/input/display_list/clipped-svg-background-stays-vector.htmlindex b8ae13a1298..1d67f77e495 100644--- a/Tests/LibWeb/Text/input/display_list/clipped-svg-background-stays-vector.html+++ b/Tests/LibWeb/Text/input/display_list/clipped-svg-background-stays-vector.html@@ -23,7 +23,7 @@await image.decode();function check(label) {- const lines = internals.dumpDisplayList().split("\n");+ const lines = internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "").split("\n");const tiles = lines.filter(line => line.trimStart().startsWith("DrawRepeatedTile@"));const images = lines.filter(line => line.trimStart().startsWith("PaintVectorImage@"));println(`${label}: ${tiles.length} raster tiles, ${images.length} vector images`);diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.htmlnew file mode 100644index 00000000000..58a3be9fb81--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-in-filter-that-moves-it.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg width="0" height="0" style="position: absolute">+ <filter id="offset"><feOffset dx="40" dy="0" /></filter>+</svg>+<div style="filter: url(#offset)">+ <div style="width: 100px; height: 100px; backdrop-filter: drop-shadow(4px 4px 0 black)"></div>+</div>+<script>+ test(() => {+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.htmlindex 99c2d72af9b..962eb285f96 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-backdrop-filter-over-content-over-canvas.html@@ -3,8 +3,8 @@<style>body { margin: 0; }canvas { position: absolute; left: 20px; top: 20px; }- #over-canvas { position: absolute; left: 180px; top: 100px; width: 200px; height: 40px; background: rgba(255, 255, 255, 0.5); }- #frosted { position: absolute; left: 300px; top: 120px; width: 60px; height: 40px; backdrop-filter: grayscale(1); }+ #over-canvas { position: absolute; left: 180px; top: 100px; width: 440px; height: 40px; background: rgba(255, 255, 255, 0.5); }+ #frosted { position: absolute; left: 540px; top: 120px; width: 60px; height: 40px; backdrop-filter: grayscale(1); }</style><canvas id="canvas" width="200" height="120"></canvas><div id="over-canvas"></div>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-box-scaled-up-from-nothing.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-box-scaled-up-from-nothing.htmlnew file mode 100644index 00000000000..a592200e535--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-box-scaled-up-from-nothing.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ @keyframes pop { from { transform: scale(0); } to { transform: scale(1); } }+ #box { width: 300px; height: 200px; margin: 100px; background: green; animation: pop 4s ease-in infinite; }+</style>+<div id="box"></div>+<script>+ // The compositor runs the animation of the box in a raster space of its own, rastered at the largest scale of the+ // animation. Early frames show the box at a very small part of that scale, so the viewport maps to a very large+ // rect of the space. A frame keys tiles only where the box has content, so the compositor stays responsive. The+ // read of the compositor's scroll state waits until the compositor has taken in every frame drawn so far.+ asyncTest(async done => {+ for (let frame = 0; frame < 30; ++frame)+ await animationFrame();+ internals.compositorScrollState();+ println("The compositor drew 30 frames of the animation");+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-filter-that-moves-it.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-filter-that-moves-it.htmlnew file mode 100644index 00000000000..2f1bbaf7719--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-filter-that-moves-it.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg width="0" height="0" style="position: absolute">+ <filter id="offset"><feOffset dx="40" dy="0" /></filter>+</svg>+<div style="filter: url(#offset)">+ <canvas id="moved" width="200" height="120"></canvas>+ <span style="position: relative; left: -150px">text over the canvas</span>+</div>+<div style="filter: drop-shadow(10px 10px 0 black)"><canvas id="shadowed" width="200" height="120"></canvas></div>+<script>+ test(() => {+ for (const canvas of [moved, shadowed]) {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ }+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-nested-scroller.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-nested-scroller.htmlnew file mode 100644index 00000000000..47399d78b0d--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-nested-scroller.html@@ -0,0 +1,23 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; height: 2000px; }+ #scroller { position: absolute; left: 20px; top: 300px; width: 300px; height: 200px; overflow: scroll; scrollbar-width: none; }+ #content { height: 1000px; }+ canvas { display: block; margin-top: 400px; }+ #over-canvas { position: absolute; left: 10px; top: 420px; width: 100px; height: 40px; background: rgba(255, 255, 255, 0.5); }+</style>+<div id="scroller">+ <div id="content">+ <canvas id="canvas" width="200" height="120"></canvas>+ <div id="over-canvas"></div>+ </div>+</div>+<script>+ test(() => {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-scrolling-document.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-scrolling-document.htmlnew file mode 100644index 00000000000..feca0b5a437--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-scrolling-document.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; height: 2000px; }+ canvas { position: absolute; left: 20px; top: 900px; }+ #over-canvas { position: absolute; left: 100px; top: 940px; width: 100px; height: 40px; background: rgba(255, 255, 255, 0.5); }+ #fixed-header { position: fixed; left: 0; top: 0; width: 800px; height: 40px; background: navy; }+ #after-header { position: absolute; left: 300px; top: 1500px; width: 50px; height: 50px; background: green; z-index: 1; }+</style>+<canvas id="canvas" width="200" height="120"></canvas>+<div id="over-canvas"></div>+<div id="fixed-header"></div>+<div id="after-header"></div>+<script>+ test(() => {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-translucent-box.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-translucent-box.htmlindex fc453d3cb0d..8df44298384 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-translucent-box.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-translucent-box.html@@ -4,7 +4,7 @@body { margin: 0; background: linear-gradient(90deg, #eef, #fee); }canvas { position: absolute; left: 20px; top: 20px; border-radius: 12px; }#over { position: absolute; left: 60px; top: 60px; width: 100px; height: 40px; background: rgba(255, 255, 255, 0.5); }- #elsewhere { position: absolute; left: 300px; top: 300px; width: 50px; height: 50px; background: green; }+ #elsewhere { position: absolute; left: 600px; top: 300px; width: 50px; height: 50px; background: green; }</style><canvas id="canvas" width="200" height="120"></canvas><div id="over"></div>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-fixed-header-over-scrolling-text.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-fixed-header-over-scrolling-text.htmlnew file mode 100644index 00000000000..51293b4a44a--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-fixed-header-over-scrolling-text.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ @font-face {+ font-family: Ahem;+ src: url("../../../Ref/data/fonts/Ahem.ttf");+ }++ body {+ margin: 0;+ height: 2000px;+ font: 20px/40px Ahem;+ }++ #fixed-header {+ position: fixed;+ left: 0;+ top: 0;+ width: 800px;+ height: 40px;+ background: navy;+ }+</style>+<p>Text of the document</p>+<div id="fixed-header"></div>+<script>+ promiseTest(async () => {+ await document.fonts.ready;+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-and-canvas.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-and-canvas.htmlindex 66df1a02670..2ed9cdb452b 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-and-canvas.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-and-canvas.html@@ -3,8 +3,8 @@<style>body { margin: 0; }iframe { position: absolute; left: 20px; top: 20px; width: 200px; height: 120px; border: 0; }- canvas { position: absolute; left: 300px; top: 20px; }- #over-both { position: absolute; left: 100px; top: 60px; width: 300px; height: 40px; background: rgba(255, 255, 255, 0.5); }+ canvas { position: absolute; left: 520px; top: 20px; }+ #over-both { position: absolute; left: 100px; top: 60px; width: 600px; height: 40px; background: rgba(255, 255, 255, 0.5); }</style><iframe id="frame" srcdoc="<body style='margin: 0; background: blue'></body>"></iframe><canvas id="canvas" width="200" height="120"></canvas>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-under-content.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-under-content.htmlindex e19091f5d18..44db4035036 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-under-content.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-iframe-under-content.html@@ -4,7 +4,7 @@body { margin: 0; }iframe { position: absolute; left: 20px; top: 20px; width: 200px; height: 120px; border: 0; }#over-iframe { position: absolute; left: 100px; top: 60px; width: 200px; height: 40px; background: rgba(255, 255, 255, 0.5); }- #elsewhere { position: absolute; left: 400px; top: 300px; width: 50px; height: 20px; background: green; }+ #elsewhere { position: absolute; left: 600px; top: 300px; width: 50px; height: 20px; background: green; }</style><iframe id="frame" srcdoc="<body style='margin: 0; background: blue'></body>"></iframe><div id="over-iframe"></div>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.htmlnew file mode 100644index 00000000000..dc4a1e5e86f--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-scroller-after-many-overflow-hidden-boxes.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ .clipped { width: 20px; height: 20px; overflow: hidden; }+ .clipped > div { width: 100px; height: 100px; }+ #clipping-wrapper { width: 400px; height: 300px; overflow: hidden; }+ #wide { width: 2000px; height: 10px; }+ #scroller { width: 300px; height: 200px; overflow: auto; scrollbar-width: none; }+ #content { height: 1000px; }+ canvas { display: block; margin-top: 50px; }+ #over-canvas { width: 100px; height: 40px; margin-top: -60px; background: rgba(255, 255, 255, 0.5); }+</style>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div class="clipped"><div></div></div>+<div id="clipping-wrapper">+ <div id="wide"></div>+ <div id="scroller">+ <div id="content">+ <canvas id="canvas" width="200" height="120"></canvas>+ <div id="over-canvas"></div>+ </div>+ </div>+</div>+<script>+ test(() => {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ println(internals.dumpDisplayList());+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-transformed-boxes-beside-canvas.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-transformed-boxes-beside-canvas.htmlindex f07301a1e79..a8e78db2aa3 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-transformed-boxes-beside-canvas.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-transformed-boxes-beside-canvas.html@@ -2,12 +2,12 @@<script src="../include.js"></script><style>body { margin: 0; }- canvas { position: absolute; left: 20px; top: 20px; }+ canvas { position: absolute; left: 300px; top: 20px; }div { position: absolute; background: green; }- #rotated-with-only-bounding-box-on-canvas { left: 225px; top: 145px; width: 60px; height: 60px; transform: rotate(45deg); }- #scaled-onto-canvas { left: 250px; top: 60px; width: 40px; height: 40px; transform: scale(3); }+ #rotated-with-only-bounding-box-on-canvas { left: 505px; top: 145px; width: 60px; height: 60px; transform: rotate(45deg); }+ #scaled-onto-canvas { left: 530px; top: 60px; width: 40px; height: 40px; transform: scale(3); }#rotated-clear-of-canvas { left: 600px; top: 400px; width: 60px; height: 60px; transform: rotate(45deg); }- #scaled-clear-of-canvas { left: 100px; top: 450px; width: 40px; height: 40px; transform: scale(3); }+ #scaled-clear-of-canvas { left: 700px; top: 520px; width: 40px; height: 40px; transform: scale(3); }</style><canvas id="canvas" width="200" height="120"></canvas><div id="rotated-with-only-bounding-box-on-canvas"></div>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-two-canvases.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-two-canvases.htmlindex 7a567c6a6dd..d8460d004fb 100644--- a/Tests/LibWeb/Text/input/display_list/compositing-layers-two-canvases.html+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-two-canvases.html@@ -4,9 +4,9 @@body { margin: 0; }canvas { position: absolute; top: 20px; }#left { left: 20px; }- #right { left: 300px; }- #over-both { position: absolute; left: 100px; top: 60px; width: 300px; height: 40px; background: rgba(255, 255, 255, 0.5); }- #over-right { position: absolute; left: 400px; top: 100px; width: 50px; height: 20px; background: green; }+ #right { left: 520px; }+ #over-both { position: absolute; left: 100px; top: 60px; width: 600px; height: 40px; background: rgba(255, 255, 255, 0.5); }+ #over-right { position: absolute; left: 620px; top: 100px; width: 50px; height: 20px; background: green; }</style><canvas id="left" width="200" height="120"></canvas><canvas id="right" width="200" height="120"></canvas>diff --git a/Tests/LibWeb/Text/input/display_list/glyph-run-text-and-fonts.html b/Tests/LibWeb/Text/input/display_list/glyph-run-text-and-fonts.htmlindex bfb96a21960..86392916104 100644--- a/Tests/LibWeb/Text/input/display_list/glyph-run-text-and-fonts.html+++ b/Tests/LibWeb/Text/input/display_list/glyph-run-text-and-fonts.html@@ -9,7 +9,7 @@<div style="text-shadow: 1px 1px red">shadowed</div><script>test(() => {- const glyphRunLines = dump => dump.split("\n").filter(line => line.startsWith("DrawGlyphRun") || line.startsWith("PaintTextShadow"));+ const glyphRunLines = dump => dump.replace(/^L\d+(,L\d+)* /gm, "").split("\n").filter(line => line.startsWith("DrawGlyphRun") || line.startsWith("PaintTextShadow"));const lines = glyphRunLines(internals.dumpDisplayList());for (const line of lines)println(line.slice(0, line.indexOf(" owner=")).replace(/.* text=/, "text="));diff --git a/Tests/LibWeb/Text/input/display_list/inline-backdrop-filter.html b/Tests/LibWeb/Text/input/display_list/inline-backdrop-filter.htmlindex 273e7480238..1947f1380d6 100644--- a/Tests/LibWeb/Text/input/display_list/inline-backdrop-filter.html+++ b/Tests/LibWeb/Text/input/display_list/inline-backdrop-filter.html@@ -8,7 +8,7 @@<div>before <span id="wrap">filtered</span> after</div><script>test(() => {- const lines = internals.dumpDisplayList().split("\n");+ const lines = internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "").split("\n");const regionCommands = lines.filter(line => line.startsWith("BackdropFilterRegion"));const backdropEffects = lines.filter(line => line.includes("backdrop-filter="));println(`backdrop region commands: ${regionCommands.length}`);diff --git a/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html b/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.htmlindex 0d7e898dffb..2ba8b46683f 100644--- a/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html+++ b/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html@@ -3,8 +3,8 @@<style>body { margin: 0; }canvas { position: absolute; left: 20px; top: 20px; }- #transformed { position: absolute; left: 300px; top: 20px; width: 50px; height: 50px; background: green; transform: rotate(45deg); }- #masked { position: absolute; left: 400px; top: 20px; width: 50px; height: 50px; background: blue; mask-image: linear-gradient(black, transparent); }+ #transformed { position: absolute; left: 600px; top: 20px; width: 50px; height: 50px; background: green; transform: rotate(45deg); }+ #masked { position: absolute; left: 700px; top: 20px; width: 50px; height: 50px; background: blue; mask-image: linear-gradient(black, transparent); }</style><canvas id="canvas" width="200" height="120"></canvas><div id="transformed"></div>diff --git a/Tests/LibWeb/Text/input/display_list/node-names-follow-print-order.html b/Tests/LibWeb/Text/input/display_list/node-names-follow-print-order.htmlindex 092401934a6..b58621268ba 100644--- a/Tests/LibWeb/Text/input/display_list/node-names-follow-print-order.html+++ b/Tests/LibWeb/Text/input/display_list/node-names-follow-print-order.html@@ -14,7 +14,7 @@<div style="transform: translateX(3px); overflow: hidden"><div class="painted"></div></div><script>test(() => {- const nodeLines = dump => dump.split("\n").filter(line => /^\s+\[[sc]\d+.*\] (transform|clip)=/.test(line) || line.startsWith("FillRect"));+ const nodeLines = dump => dump.replace(/^L\d+(,L\d+)* /gm, "").split("\n").filter(line => /^\s+\[[sc]\d+.*\] (transform|clip)=/.test(line) || line.startsWith("FillRect"));println("Named in print order:");println(nodeLines(internals.dumpDisplayList()).join("\n"));println("Named by index:");diff --git a/Tests/LibWeb/Text/input/display_list/record-ids-number-nested-records-and-name-layer-records.html b/Tests/LibWeb/Text/input/display_list/record-ids-number-nested-records-and-name-layer-records.htmlindex 1f38b6a8775..bcfcf7f450c 100644--- a/Tests/LibWeb/Text/input/display_list/record-ids-number-nested-records-and-name-layer-records.html+++ b/Tests/LibWeb/Text/input/display_list/record-ids-number-nested-records-and-name-layer-records.html@@ -4,8 +4,8 @@body { margin: 0; }canvas { position: absolute; left: 20px; top: 20px; }#below { position: absolute; left: 0; top: 0; width: 300px; height: 10px; background: green; }- #masked { position: absolute; left: 300px; top: 20px; width: 50px; height: 50px; background: blue; mask-image: linear-gradient(black, transparent); }- #over { position: absolute; left: 100px; top: 60px; width: 300px; height: 40px; background: rgba(255, 255, 255, 0.5); }+ #masked { position: absolute; left: 600px; top: 20px; width: 50px; height: 50px; background: blue; mask-image: linear-gradient(black, transparent); }+ #over { position: absolute; left: 100px; top: 60px; width: 500px; height: 40px; background: rgba(255, 255, 255, 0.5); }</style><div id="below"></div><canvas id="canvas" width="200" height="120"></canvas>diff --git a/Tests/LibWeb/Text/input/display_list/repeated-gradient-background-is-tile.html b/Tests/LibWeb/Text/input/display_list/repeated-gradient-background-is-tile.htmlindex 57068c63a53..c76596d5f11 100644--- a/Tests/LibWeb/Text/input/display_list/repeated-gradient-background-is-tile.html+++ b/Tests/LibWeb/Text/input/display_list/repeated-gradient-background-is-tile.html@@ -16,7 +16,7 @@test(() => {const target = document.getElementById("target");function check(label) {- const lines = internals.dumpDisplayList().split("\n");+ const lines = internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "").split("\n");const tiles = lines.filter(line => line.trimStart().startsWith("DrawRepeatedTile@"));const gradients = lines.filter(line => /Paint(Linear|Radial|Conic)Gradient@/.test(line));println(`${label}: ${tiles.length} tiles, ${gradients.length} gradients`);diff --git a/Tests/LibWeb/Text/input/display_list/scrollbar-of-scroller-above-origin.html b/Tests/LibWeb/Text/input/display_list/scrollbar-of-scroller-above-origin.htmlindex aab45209c94..1ec4e070b5b 100644--- a/Tests/LibWeb/Text/input/display_list/scrollbar-of-scroller-above-origin.html+++ b/Tests/LibWeb/Text/input/display_list/scrollbar-of-scroller-above-origin.html@@ -9,7 +9,7 @@<div class="scroller" style="left: 200px; top: 100px; width: 4px; height: 3px"><div></div></div><script>test(() => {- for (const line of internals.dumpDisplayList().split("\n")) {+ for (const line of internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "").split("\n")) {if (line.startsWith("CompositorScrollbar"))println(`vertical=${line.includes(" vertical=true")} ${line.match(/track_rect=\[[^\]]*\]/)[0]}`);}diff --git a/Tests/LibWeb/Text/input/display_list/sibling-scrollables-in-fixed.html b/Tests/LibWeb/Text/input/display_list/sibling-scrollables-in-fixed.htmlindex 0196795b628..b89c5c7f5ba 100644--- a/Tests/LibWeb/Text/input/display_list/sibling-scrollables-in-fixed.html+++ b/Tests/LibWeb/Text/input/display_list/sibling-scrollables-in-fixed.html@@ -4,7 +4,7 @@.fixed-box {position: fixed;top: 10px;- left: 10px;+ left: 210px;width: 300px;height: 200px;background: lightgray;diff --git a/Tests/LibWeb/Text/input/multicol-broken-box-wheel-targets.html b/Tests/LibWeb/Text/input/multicol-broken-box-wheel-targets.htmlindex 25e0bb503a4..0004b34d621 100644--- a/Tests/LibWeb/Text/input/multicol-broken-box-wheel-targets.html+++ b/Tests/LibWeb/Text/input/multicol-broken-box-wheel-targets.html@@ -15,7 +15,7 @@internals.recordDisplayListForTesting();const state = internals.recordedAsyncScrollingState();println(`blocking regions: ${state.blockingWheelEventRegionCount}`);- for (const line of internals.dumpDisplayList().split("\n")) {+ for (const line of internals.dumpDisplayList().replace(/^L\d+(,L\d+)* /gm, "").split("\n")) {if (line.startsWith("CompositorWheelHitTestTarget") || line.startsWith("CompositorBlockingWheelEventRegion"))println(line);}