Truly independent web browser
LibCompositing: Snap scroll translations to device pixels once
Aliaksandr Kalenik9758ed3d17b4
diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cppindex 378d8ac9951..4e2a57afed1 100644--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp@@ -168,9 +168,9 @@ Optional<Gfx::Color> AccumulatedVisualContextTree::sampled_background_color(Effereturn color;}-bool AccumulatedVisualContextTree::can_snap_composited_context_origin(SpatialNodeIndex spatial_node_index) const+bool AccumulatedVisualContextTree::translations_snap_to_device_pixels(SpatialNodeIndex spatial_node_index, ScrollStateSnapshot const& scroll_state) const{- return Compositing::RustFFI::visual_context_tree_can_snap_composited_context_origin(m_rust_tree, spatial_node_index);+ return Compositing::RustFFI::world_transforms_translations_snap_to_device_pixels(scroll_state.world_transforms(*this), spatial_node_index);}Optional<Gfx::FloatPoint> AccumulatedVisualContextTree::transform_point_for_hit_test(ContextRef context, Gfx::FloatPoint screen_point, ScrollStateSnapshot const& scroll_state, ClipBehavior clip_behavior) constdiff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.hindex a618d1f2aba..7046739490a 100644--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h@@ -85,7 +85,9 @@ public:AccumulatedVisualContextTree with_visual_animation_samples(i64 monotonic_time_ns) const;// The sampled background color of a recorded fill's animation effect.Optional<Gfx::Color> sampled_background_color(EffectNodeIndex) const;- bool can_snap_composited_context_origin(SpatialNodeIndex) const;+ // Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no+ // transform but identities lies above it.+ bool translations_snap_to_device_pixels(SpatialNodeIndex, ScrollStateSnapshot const&) const;Optional<Gfx::FloatPoint> transform_point_for_hit_test(ContextRef, Gfx::FloatPoint, ScrollStateSnapshot const&, ClipBehavior = ClipBehavior::Respect) const;Gfx::FloatPoint inverse_transform_point(SpatialNodeIndex, Gfx::FloatPoint) const;diff --git a/Libraries/LibCompositing/Rust/src/display_list/damage.rs b/Libraries/LibCompositing/Rust/src/display_list/damage.rsindex 568e541a0d6..6cbec778884 100644--- a/Libraries/LibCompositing/Rust/src/display_list/damage.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/damage.rs@@ -23,7 +23,7 @@ use crate::fast_hash::FastMap;use crate::host::FfiAnimatedContentViewportEffect;use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{- ClipNodeData, EffectNodeData, ScrollSnap, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,+ ClipNodeData, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,};use libgfx_rust::{AffineTransform, FloatMatrix4x4, FloatPoint, FloatRect, IntRect, enclosing_int_rect};use std::cell::{Cell, OnceCell, RefCell};@@ -508,14 +508,9 @@ struct TreeSide<'b> {impl<'b> TreeSide<'b> {// Damage maps commands with the matrices replay draws them with.fn world(&self) -> &'b WorldTransforms {- self.lazy_geometry.world_transforms.get_or_init(|| {- WorldTransforms::new(- self.tree,- self.scroll_offsets,- Some(FloatMatrix4x4::identity()),- ScrollSnap::Truncate,- )- })+ self.lazy_geometry+ .world_transforms+ .get_or_init(|| WorldTransforms::new(self.tree, self.scroll_offsets, Some(FloatMatrix4x4::identity())))}}@@ -1391,14 +1386,8 @@ pub fn animated_content_may_affect_viewport(}let mut rect = header.bounding_rect.to_float();if has_inline_clip_in_its_own_space && header.has_bounding_rect {- let world = world.get_or_init(|| {- WorldTransforms::new(- tree,- scroll_offsets,- Some(FloatMatrix4x4::identity()),- ScrollSnap::Truncate,- )- });+ 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| {@@ -2269,7 +2258,7 @@ mod tests {Some(rect),context_in(scroll_node, ContextRef::default()),);- // Replay truncates each of the three offsets to zero, so the rect is drawn where it was recorded.+ // 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(),@@ -2280,7 +2269,7 @@ mod tests {&scroll_offsets,IntRect::new(0, 0, 100, 100),),- Some(IntRect::new(9, 9, 22, 22))+ Some(IntRect::new(9, 6, 22, 22)));}diff --git a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rsindex 95035f5f66a..120370043a3 100644--- a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs@@ -200,7 +200,7 @@ pub fn compute_effect_geometry(mod tests {use super::*;use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, VISUAL_VIEWPORT_NODE_INDEX};- use crate::visual_context::{EffectsData, ScrollSnap, SpatialData, TransformData, TransformDataRole};+ use crate::visual_context::{EffectsData, SpatialData, TransformData, TransformDataRole};use libgfx_rust::filter::Filter;use libgfx_rust::{Color, ColorFilterType, CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, IntRect, rotation_matrix,@@ -261,7 +261,7 @@ mod tests {fn geometry_of(tree: &VisualContextTree, runs: &[DisplayListCommandRun]) -> Vec<EffectGeometry> {let mut geometry = Vec::new();- let world = WorldTransforms::new(tree, &[], Some(FloatMatrix4x4::identity()), ScrollSnap::None);+ let world = WorldTransforms::new(tree, &[], Some(FloatMatrix4x4::identity()));compute_effect_geometry(tree, runs, &world, &mut geometry);geometry}@@ -376,7 +376,7 @@ mod tests {assert_eq!(nearest[opacity.0 as usize], blur);assert_eq!(nearest[plain.0 as usize], EffectNodeIndex::NONE);let content = FloatRect::new(10.0, 20.0, 30.0, 40.0);- let world = WorldTransforms::new(&tree, &[], Some(FloatMatrix4x4::identity()), ScrollSnap::None);+ let world = WorldTransforms::new(&tree, &[], Some(FloatMatrix4x4::identity()));assert_eq!(changed_extent_through_filters(&tree, &nearest, scaled, content, shadow, &world),(VISUAL_VIEWPORT_NODE_INDEX, within(-10.0, 10.0, 120.0, 160.0))diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rsindex f9cdd40479c..810261297ff 100644--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs@@ -18,8 +18,8 @@ use crate::display_list::ffi_bytes::FfiBytes;use crate::display_list::nested_records::span_bytes;use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{- ClipNodeData, ContextRef, EffectNodeData, ScrollSnap, SpatialData, VisualContextTree, WorldTransforms,- device_offset_for_index, resolve_leaf_to_context_matrices,+ ClipNodeData, ContextRef, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,+ resolve_leaf_to_context_matrices,};use libgfx_rust::filter::Filter;use libgfx_rust::path::Path;@@ -810,13 +810,11 @@ pub fn replay_display_list(effect_geometry: scratch.effect_geometry,effect_geometry_is_known: false,};- // Whole device pixels, so scrolled content never lands on subpixel positions.driver.world.fill(tree,&driver.spatial_dependency_order,scroll_offsets,Some(replay_base_matrix),- ScrollSnap::Truncate,);driver.execute();return_replay_scratch_storage(ReplayScratchStorage {@@ -894,8 +892,8 @@ mod tests {permuted.spatial_nodes[permuted_child.0 as usize].parent = permuted_parent;let base = scale_matrix(2.0, 2.0, 1.0);- let in_order_palette = WorldTransforms::new(&in_order, &[], Some(base), ScrollSnap::Truncate);- let permuted_palette = WorldTransforms::new(&permuted, &[], Some(base), ScrollSnap::Truncate);+ let in_order_palette = WorldTransforms::new(&in_order, &[], Some(base));+ let permuted_palette = WorldTransforms::new(&permuted, &[], Some(base));let pairs = [(VISUAL_VIEWPORT_NODE_INDEX, VISUAL_VIEWPORT_NODE_INDEX),(parent, permuted_parent),@@ -2013,7 +2011,7 @@ mod tests {assert_eq!(painter.events,vec![- PainterEvent::SetMatrix(base.multiplied(translation_matrix(0.0, -30.0, 0.0))),+ PainterEvent::SetMatrix(base.multiplied(translation_matrix(0.0, -31.0, 0.0))),PainterEvent::Run(1),PainterEvent::SetMatrix(base),]diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex 2ca0243cb88..ade2ac14939 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -333,12 +333,7 @@ pub unsafe extern "C" fn world_transforms_create(let tree = unsafe { tree_from_handle(tree) };// SAFETY: The caller guarantees the offsets address `scroll_offsets_len` points.let scroll_offsets = unsafe { ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len) };- let world = crate::visual_context::WorldTransforms::new(- tree,- scroll_offsets,- None,- crate::visual_context::ScrollSnap::None,- );+ let world = crate::visual_context::WorldTransforms::new(tree, scroll_offsets, None);Box::into_raw(Box::new(world)).cast()}@@ -415,6 +410,17 @@ pub unsafe extern "C" fn world_transforms_transform_rect_to_viewport();}+/// # Safety+///+/// `world` must be a live handle from `world_transforms_create`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn world_transforms_translations_snap_to_device_pixels(+ world: *const c_void,+ spatial: SpatialNodeIndex,+) -> bool {+ unsafe { world_transforms_from_handle(world) }.translations_snap_to_device_pixels(spatial)+}+/// # Safety////// `world` must be a live handle from `world_transforms_create`.@@ -511,17 +517,6 @@ pub unsafe extern "C" fn visual_context_tree_has_visual_animations(tree: *constunsafe { tree_from_handle(tree) }.has_visual_animations()}-/// # Safety-///-/// `tree` must be a live retained tree handle.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn visual_context_tree_can_snap_composited_context_origin(- tree: *const c_void,- spatial_node_index: SpatialNodeIndex,-) -> bool {- unsafe { tree_from_handle(tree) }.can_snap_composited_context_origin(spatial_node_index)-}-/// # Safety////// `tree` must be a live retained tree handle.diff --git a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs b/Libraries/LibCompositing/Rust/src/visual_context/mod.rsindex b9b3e4baa57..a073552d7fe 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/mod.rs@@ -249,12 +249,6 @@ pub enum IncludeVisualViewportTransform {Yes,}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ScrollSnap {- None,- Truncate,-}-#[derive(Clone, Copy, Debug, PartialEq)]pub enum LocalTransformKind {Identity,@@ -1218,12 +1212,7 @@ impl VisualContextTree {chain}- pub fn local_transform(- &self,- index: SpatialNodeIndex,- scroll_offsets: &[FloatPoint],- scroll_snap: ScrollSnap,- ) -> LocalTransform {+ pub fn local_transform(&self, index: SpatialNodeIndex, scroll_offsets: &[FloatPoint]) -> LocalTransform {let mut local = LocalTransform {matrix: FloatMatrix4x4::identity(),flattens_inherited_transform: false,@@ -1233,13 +1222,6 @@ impl VisualContextTree {backface_plane_root: None,};let translation = |offset: FloatPoint| {- let offset = match scroll_snap {- ScrollSnap::None => offset,- ScrollSnap::Truncate => FloatPoint {- x: offset.x as i32 as f32,- y: offset.y as i32 as f32,- },- };(translation_matrix(offset.x, offset.y, 0.0),LocalTransformKind::Translation(offset),@@ -1547,7 +1529,7 @@ mod tests {let child = tree.append_spatial(SpatialData::Transform(scaled(3.0)), scroll);let scroll_offsets = [FloatPoint::default(), FloatPoint { x: -10.0, y: -20.0 }];- let world = WorldTransforms::new(&tree, &scroll_offsets, None, ScrollSnap::None);+ let world = WorldTransforms::new(&tree, &scroll_offsets, None);let without_viewport = world.to_viewport_matrix(child, IncludeVisualViewportTransform::No);assert_eq!(without_viewport,@@ -1585,7 +1567,7 @@ mod tests {}),VISUAL_VIEWPORT_NODE_INDEX,);- let world = WorldTransforms::new(&tree, &[], None, ScrollSnap::None);+ let world = WorldTransforms::new(&tree, &[], None);let matrix = world.to_viewport_matrix(child, IncludeVisualViewportTransform::No);assert_eq!(matrix.map_vector4([50.0, 50.0, 0.0, 1.0]), [50.0, 50.0, 0.0, 1.0]);assert_eq!(matrix.map_vector4([0.0, 0.0, 0.0, 1.0]), [-50.0, -50.0, 0.0, 1.0]);@@ -2011,7 +1993,7 @@ mod tests {fn an_untransformed_plane_has_zero_depth() {let tree = tree();assert_eq!(- WorldTransforms::new(&tree, &[], None, ScrollSnap::None)+ WorldTransforms::new(&tree, &[], None).plane_depth_at_point_for_hit_test(VISUAL_VIEWPORT_NODE_INDEX, FloatPoint { x: 25.0, y: 50.0 }),Some(0.0));@@ -2028,7 +2010,7 @@ mod tests {VISUAL_VIEWPORT_NODE_INDEX,);assert_eq!(- WorldTransforms::new(&tree, &[], None, ScrollSnap::None)+ WorldTransforms::new(&tree, &[], None).plane_depth_at_point_for_hit_test(plane, FloatPoint { x: 25.0, y: 50.0 }),Some(75.0));@@ -2051,7 +2033,7 @@ mod tests {}),perspective,);- let depth = WorldTransforms::new(&tree, &[], None, ScrollSnap::None)+ let depth = WorldTransforms::new(&tree, &[], None).plane_depth_at_point_for_hit_test(plane, FloatPoint { x: 25.0, y: 50.0 }).unwrap();assert!((depth - 1000.0 / 9.0).abs() < 0.0001);@@ -2068,7 +2050,7 @@ mod tests {VISUAL_VIEWPORT_NODE_INDEX,);assert_eq!(- WorldTransforms::new(&tree, &[], None, ScrollSnap::None)+ WorldTransforms::new(&tree, &[], None).plane_depth_at_point_for_hit_test(plane, FloatPoint { x: 25.0, y: 50.0 }),None);diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rsindex 17e82b79da3..9f162f302c7 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs@@ -7,7 +7,7 @@use super::world_transforms::MINIMUM_PROJECTION_W;use super::{ClipData, ClipMode, ClipNode, ClipNodeData, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex,- IncludeVisualViewportTransform, LocalTransform, LocalTransformKind, ScrollSnap, SpatialData, SpatialNodeIndex,+ IncludeVisualViewportTransform, LocalTransform, LocalTransformKind, SpatialData, SpatialNodeIndex,TransformDataRole, VISUAL_VIEWPORT_NODE_INDEX, VisualContextTree, WorldTransforms, device_offset_for_index,};use ak::math;@@ -130,7 +130,7 @@ impl VisualContextTree {fn chain_contains_3d_transform(&self, index: SpatialNodeIndex) -> bool {let mut current = index;loop {- if self.local_transform(current, &[], ScrollSnap::None).kind == LocalTransformKind::Projective {+ if self.local_transform(current, &[]).kind == LocalTransformKind::Projective {return true;}if current == VISUAL_VIEWPORT_NODE_INDEX {@@ -244,29 +244,6 @@ impl VisualContextTree {}}- pub fn can_snap_composited_context_origin(&self, mut spatial_node_index: SpatialNodeIndex) -> bool {- loop {- let Some(node) = self.spatial_nodes.get(spatial_node_index.0 as usize) else {- return false;- };-- if !node.data.is_live() {- return false;- }-- if spatial_node_index == VISUAL_VIEWPORT_NODE_INDEX {- return true;- }-- let local = self.local_transform(spatial_node_index, &[], ScrollSnap::None);- if local.is_transform_or_perspective() && local.matrix != FloatMatrix4x4::identity() {- return false;- }-- spatial_node_index = node.parent;- }- }-pub fn transform_point_for_hit_test(&self,world: &WorldTransforms,@@ -320,7 +297,7 @@ impl VisualContextTree {let transforms = chain.iter().rev()- .map(|node_index| self.local_transform(*node_index, &[], ScrollSnap::None))+ .map(|node_index| self.local_transform(*node_index, &[])).filter(LocalTransform::is_transform_or_perspective);if self.chain_contains_3d_transform(index) {let matrix = transforms.fold(FloatMatrix4x4::identity(), |matrix, local| local.applied_to(matrix));@@ -613,7 +590,7 @@ impl VisualContextTree {let radius = math::hypot(dx, dy);rect = FloatRect::new(origin.x - radius, origin.y - radius, 2.0 * radius, 2.0 * radius);} else {- let matrix = self.local_transform(index, scroll_offsets, ScrollSnap::None).matrix;+ let matrix = self.local_transform(index, scroll_offsets).matrix;// Projecting a rectangle at each ancestor would discard depth needed by later 3D transforms.if !matrix.is_2d_affine() {return None;@@ -714,7 +691,7 @@ mod tests {scroll_offsets: &[FloatPoint],clip_behavior: ClipBehavior,) -> Option<FloatPoint> {- let world = WorldTransforms::new(tree, scroll_offsets, None, ScrollSnap::None);+ let world = WorldTransforms::new(tree, scroll_offsets, None);tree.transform_point_for_hit_test(&world, context, screen_point, clip_behavior)}@@ -725,7 +702,7 @@ mod tests {scroll_offsets: &[FloatPoint],include_visual_viewport_transform: IncludeVisualViewportTransform,) -> FloatRect {- WorldTransforms::new(tree, scroll_offsets, None, ScrollSnap::None).transform_rect_to_viewport(+ WorldTransforms::new(tree, scroll_offsets, None).transform_rect_to_viewport(node,rect,include_visual_viewport_transform,@@ -1166,6 +1143,31 @@ mod tests {);}+ #[test]+ fn scroll_translations_round_to_device_pixels_unless_a_transform_is_above_them() {+ // The visual viewport's own transform does not keep translations below it from snapping.+ let mut tree = VisualContextTree::create(transform_data(scale_matrix(2.0, 2.0, 1.0), FloatPoint::default()));+ let outer = tree.append_spatial(scroll(), VISUAL_VIEWPORT_NODE_INDEX);+ let identity = tree.append_spatial(+ SpatialData::Transform(transform_data(FloatMatrix4x4::identity(), point(5.0, 5.0))),+ outer,+ );+ let inner = tree.append_spatial(scroll(), identity);+ let scaled = tree.append_spatial(+ SpatialData::Transform(transform_data(scale_matrix(2.0, 2.0, 1.0), FloatPoint::default())),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ let under_scale = tree.append_spatial(scroll(), scaled);+ let mut offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];+ offsets[outer.0 as usize] = point(0.0, -10.5);+ offsets[inner.0 as usize] = point(-0.25, -0.75);+ offsets[under_scale.0 as usize] = point(0.0, -10.5);+ let rect = FloatRect::new(0.0, 0.0, 10.0, 10.0);+ let mapped = |node| rect_to_viewport(&tree, node, rect, &offsets, IncludeVisualViewportTransform::No);+ assert_eq!(mapped(inner), FloatRect::new(0.0, -12.0, 10.0, 10.0));+ assert_eq!(mapped(under_scale), FloatRect::new(0.0, -21.0, 20.0, 20.0));+ }+#[test]fn a_2d_rect_maps_node_by_node_and_may_leave_out_the_visual_viewport() {let mut tree = VisualContextTree::create(transform_data(scale_matrix(2.0, 2.0, 1.0), FloatPoint::default()));diff --git a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rsindex 3f6cf32b83d..b285818d9a5 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs@@ -1729,12 +1729,11 @@ mod tests {assert_eq!(decoded.clip_dependency_order(), vec![1, 0]);assert_eq!(decoded.effect_dependency_order(), vec![1, 0]);assert_eq!(- super::super::WorldTransforms::new(&decoded, &[], None, super::super::ScrollSnap::None)- .transform_rect_to_viewport(- SpatialNodeIndex(1),- FloatRect::new(0.0, 0.0, 10.0, 10.0),- super::super::IncludeVisualViewportTransform::Yes- ),+ super::super::WorldTransforms::new(&decoded, &[], None).transform_rect_to_viewport(+ SpatialNodeIndex(1),+ FloatRect::new(0.0, 0.0, 10.0, 10.0),+ super::super::IncludeVisualViewportTransform::Yes+ ),FloatRect::new(5.0, 5.0, 10.0, 10.0));}diff --git a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rsindex 4665e2c8677..e2312c63401 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs@@ -7,7 +7,7 @@//! The compositor animations a visual context tree carries, and the trees derived by sampling them.use super::{- ClipBehavior, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex, EffectsData, ScrollSnap, SpatialData,+ ClipBehavior, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex, EffectsData, SpatialData,SpatialNodeIndex, VisualContextTree, WorldTransforms,};use crate::host::{FfiVisualAnimationSummary, FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};@@ -130,8 +130,7 @@ impl VisualContextTree {clip: ClipNodeIndex::NONE,effect: EffectNodeIndex::NONE,};- let world =- world.get_or_init(|| WorldTransforms::new(self, scroll_offsets, None, ScrollSnap::None));+ let world = world.get_or_init(|| WorldTransforms::new(self, scroll_offsets, None));self.transform_point_for_hit_test(world, context, screen_point, ClipBehavior::Ignore).is_some_and(|local_point| transform.bounds.contains_point(local_point))})diff --git a/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rsindex 5d05f924c23..3f4962ffc0a 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs@@ -5,10 +5,12 @@*/use super::{- IncludeVisualViewportTransform, LocalTransformKind, ScrollSnap, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,+ IncludeVisualViewportTransform, LocalTransformKind, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,VisualContextTree, should_cull_back_face,};-use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, map_rect_through_matrix, multiply_affine};+use libgfx_rust::{+ FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, map_rect_through_matrix, multiply_affine, translation_matrix,+};// Homogeneous coordinates this close to the eye plane have no meaningful projection.pub const MINIMUM_PROJECTION_W: f32 = 0.0001;@@ -18,6 +20,9 @@ pub const MINIMUM_PROJECTION_W: f32 = 0.0001;/// cull test and its descendants, while content recorded directly under the marker belongs to its parent's plane, so/// `draw_space` redirects the marker to the parent's entry. A table filled without a root parent matrix is in the/// layout viewport's space, and the queries below add the visual viewport transform where asked.+///+/// Scroll, sticky and anchor scroll shift translations under no transform but identities round to whole device pixels+/// of the layout viewport, so scrolled content never lands on subpixel positions. Under a transform they stay exact.#[derive(Default)]pub struct WorldTransforms {pub local: Vec<FloatMatrix4x4>,@@ -25,6 +30,7 @@ pub struct WorldTransforms {pub flattens_inherited_transform: Vec<bool>,pub backface_culled: Vec<bool>,pub draw_space: Vec<SpatialNodeIndex>,+ 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@@ -36,10 +42,7 @@ fn backface_culled_outside_sorting_context() -> bool {let mut index = root;loop {- if tree- .local_transform(index, &[], ScrollSnap::None)- .establishes_sorting_context- {+ if tree.local_transform(index, &[]).establishes_sorting_context {return backface_culled[index.0 as usize];}if index.0 == 0 {@@ -54,7 +57,6 @@ impl WorldTransforms {tree: &VisualContextTree,scroll_offsets: &[FloatPoint],root_parent_matrix: Option<FloatMatrix4x4>,- scroll_snap: ScrollSnap,) -> Self {let mut world = Self::default();world.fill(@@ -62,7 +64,6 @@ impl WorldTransforms {&tree.spatial_dependency_order(),scroll_offsets,root_parent_matrix,- scroll_snap,);world}@@ -73,6 +74,7 @@ impl WorldTransforms {self.flattens_inherited_transform.clear();self.backface_culled.clear();self.draw_space.clear();+ self.translations_snap_to_device_pixels.clear();}/// Fills the table, with `root_parent_matrix` as what the visual viewport node's transform applies on top of, or@@ -83,7 +85,6 @@ impl WorldTransforms {spatial_dependency_order: &[u32],scroll_offsets: &[FloatPoint],root_parent_matrix: Option<FloatMatrix4x4>,- scroll_snap: ScrollSnap,) {let node_count = tree.spatial_nodes.len();self.clear();@@ -93,10 +94,19 @@ impl WorldTransforms {self.backface_culled.resize(node_count, false);self.draw_space.extend((0..node_count).map(|index| SpatialNodeIndex(index as u32)));+ self.translations_snap_to_device_pixels.resize(node_count, false);for &index in spatial_dependency_order {let i = index as usize;let parent = tree.spatial_nodes[i].parent.0 as usize;- let local = tree.local_transform(SpatialNodeIndex(index), scroll_offsets, scroll_snap);+ 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;+ if let LocalTransformKind::Translation(offset) = local.kind+ && snaps+ {+ local.matrix = translation_matrix(offset.x.round(), offset.y.round(), 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),@@ -128,6 +138,13 @@ impl WorldTransforms {self.to_root[self.draw_space[space.0 as usize].0 as usize]}+ pub fn translations_snap_to_device_pixels(&self, node: SpatialNodeIndex) -> bool {+ self.translations_snap_to_device_pixels+ .get(node.0 as usize)+ .copied()+ .unwrap_or(false)+ }+pub fn draw_matrix_if_known(&self, space: SpatialNodeIndex) -> Option<FloatMatrix4x4> {((space.0 as usize) < self.draw_space.len()).then(|| self.draw_matrix(space))}@@ -193,7 +210,7 @@ impl WorldTransforms {let mut offset = FloatPoint::default();let mut current = node;while current != VISUAL_VIEWPORT_NODE_INDEX {- if let LocalTransformKind::Translation(_) = tree.local_transform(current, &[], ScrollSnap::None).kind {+ if let LocalTransformKind::Translation(_) = tree.local_transform(current, &[]).kind {let local = &self.local[current.0 as usize].elements;offset.x += local[0][3];offset.y += local[1][3];diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex f883c2adca6..f32d37e1b0e 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -4350,9 +4350,12 @@ static CSSPixelPoint determine_the_scroll_into_view_position(Layout::BegunRead cscrolling_box_rect = Painting::scroll_snapport_rect(*layout_node, scrolling_box_rect);scrolling_box_layout_node = as_if<Layout::NodeWithStyle>(layout_node);}- current_scroll_position = document.navigable()->viewport_scroll_offset() + visual_viewport.offset();+ current_scroll_position = document.navigable()->viewport_scroll_offset();+ if (auto* layout_node = document.layout_node(read))+ current_scroll_position = Painting::presented_scroll_offset(*layout_node, current_scroll_position);+ current_scroll_position += visual_viewport.offset();} else if (auto* layout_node = scrolling_box.layout_node(read); layout_node && Painting::has_committed_box(*layout_node)) {- current_scroll_position = Painting::scroll_offset(*layout_node);+ current_scroll_position = Painting::presented_scroll_offset(*layout_node, Painting::scroll_offset(*layout_node));scrolling_box_layout_node = as_if<Layout::NodeWithStyle>(layout_node);scrolling_box_rect = Painting::transform_rect_to_viewport(*layout_node, Painting::scroll_snapport_rect(*layout_node), Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform::No);} else {@@ -4614,7 +4617,7 @@ void scroll_a_target_into_view(Layout::BegunRead const& read, ScrollIntoViewTarg// the outermost scrolling box, so its own scroll cannot affect a later iteration.if (!scrolling_box.is_document()) {if (auto const* layout_node = scrolling_box.layout_node(read); layout_node && Painting::has_committed_box(*layout_node)) {- target_bounding_border_box.translate_by(Painting::scroll_offset(*layout_node) - Painting::clamp_scroll_offset(*layout_node, position));+ target_bounding_border_box.translate_by(Painting::presented_scroll_offset(*layout_node, Painting::scroll_offset(*layout_node)) - Painting::clamp_scroll_offset(*layout_node, position));auto scrollport_rect = Painting::transform_rect_to_viewport(*layout_node, Painting::absolute_padding_box_rect(*layout_node), Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform::No);auto visible_rect = target_bounding_border_box.intersected(scrollport_rect);if (!visible_rect.is_empty())diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cppindex ca21001e552..9fedc4cb83d 100644--- a/Libraries/LibWeb/Painting/BoxViews.cpp+++ b/Libraries/LibWeb/Painting/BoxViews.cpp@@ -714,6 +714,19 @@ CSSPixelPoint inverse_transform_point(Layout::Node const& node, CSSPixelPoint poreturn (result / pixel_ratio).to_type<CSSPixels>();}+CSSPixelPoint presented_scroll_offset(Layout::Node const& node, CSSPixelPoint scroll_offset)+{+ auto const& document = node.document();+ if (!has_committed_box(node) || !document.has_committed_viewport_box())+ return scroll_offset;+ auto visual_context_tree = document.visual_context_tree();+ if (!visual_context_tree.translations_snap_to_device_pixels(accumulated_visual_context(node).spatial, document.scroll_state_snapshot()))+ return scroll_offset;+ auto pixel_ratio = document.page().client().device_pixels_per_css_pixel();+ auto snap = [&](CSSPixels value) { return CSSPixels::nearest_value_for(round(value.to_double() * pixel_ratio) / pixel_ratio); };+ return { snap(scroll_offset.x()), snap(scroll_offset.y()) };+}+CSSPixelPoint transform_to_local_coordinates(Layout::Node const& node, CSSPixelPoint position){if (!has_committed_box(node))diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.hindex 9cff75b0a7f..5a62daa06cb 100644--- a/Libraries/LibWeb/Painting/BoxViews.h+++ b/Libraries/LibWeb/Painting/BoxViews.h@@ -62,6 +62,9 @@ WEB_API bool is_svg_svg_paintable(Layout::Node const&);WEB_API CSSPixelRect transform_rect_to_viewport(Layout::Node const&, CSSPixelRect const&, Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform = Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform::Yes);WEB_API CSSPixelPoint inverse_transform_point(Layout::Node const&, CSSPixelPoint);+// The scroll offset at which the box's content is drawn, hit tested and measured: rounded to whole device pixels where+// nothing but identity transforms lies above the box.+WEB_API CSSPixelPoint presented_scroll_offset(Layout::Node const&, CSSPixelPoint scroll_offset);WEB_API CSSPixelPoint transform_to_local_coordinates(Layout::Node const&, CSSPixelPoint);WEB_API bool has_accumulated_visual_context(Layout::Node const&);diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rsindex 1578720c718..8404dcf0f2a 100644--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs@@ -71,12 +71,7 @@ impl FfiHitTestQueryCallbacks {&self,tree: &crate::painting::visual_context::VisualContextTree,) -> crate::painting::visual_context::WorldTransforms {- crate::painting::visual_context::WorldTransforms::new(- tree,- self.scroll_offsets(),- None,- crate::painting::visual_context::ScrollSnap::None,- )+ crate::painting::visual_context::WorldTransforms::new(tree, self.scroll_offsets(), None)}/// These callbacks with the world transforms the query reads, which `world` holds for the query.diff --git a/Libraries/LibWeb/Rust/src/painting/published_frame.rs b/Libraries/LibWeb/Rust/src/painting/published_frame.rsindex 565b6f3aca2..837c20b057f 100644--- a/Libraries/LibWeb/Rust/src/painting/published_frame.rs+++ b/Libraries/LibWeb/Rust/src/painting/published_frame.rs@@ -33,7 +33,7 @@ use crate::painting::selection::{use crate::painting::stacking_context::entries::StackingContextEntries;use crate::painting::svg_paint_resources::SvgPaintResourceRows;use crate::painting::visual_context::{BoxVisualContextNodeHandles, EMPTY_BOX_VISUAL_CONTEXT_NODE_HANDLES};-use crate::painting::visual_context::{ScrollSnap, VisualContextTree, WorldTransforms};+use crate::painting::visual_context::{VisualContextTree, WorldTransforms};use std::sync::Arc;/// The document's text rows and its replaced, layer image and SVG paint resource tables, as they@@ -184,7 +184,7 @@ impl PublishedPaintState {.visual_context_tree.as_deref().expect("recording runs against a visual context tree");- WorldTransforms::new(tree, &[], None, ScrollSnap::None)+ WorldTransforms::new(tree, &[], None)})}diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 123fa8f82bd..557ed5f8e75 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -291,7 +291,7 @@ void DisplayListPlayerSkia::play_command(DrawCompositedContext const& command)// 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 && active_visual_context_tree().can_snap_composited_context_origin(command.spatial_node_index)) {+ if (command.snap_origin_if_untransformed && active_visual_context_tree().translations_snap_to_device_pixels(command.spatial_node_index, active_scroll_state())) {destination_rect.set_x(roundf(destination_rect.x()));destination_rect.set_y(roundf(destination_rect.y()));}diff --git a/Tests/LibWeb/Ref/expected/fractional-scroll-offset-rounds-to-device-pixels-ref.html b/Tests/LibWeb/Ref/expected/fractional-scroll-offset-rounds-to-device-pixels-ref.htmlnew file mode 100644index 00000000000..190401a96b2--- /dev/null+++ b/Tests/LibWeb/Ref/expected/fractional-scroll-offset-rounds-to-device-pixels-ref.html@@ -0,0 +1,25 @@+<!DOCTYPE html>+<style>+ body {+ margin: 0;+ }+ #scroller {+ width: 100px;+ height: 100px;+ overflow: hidden;+ }+ #rows {+ margin-top: -11px;+ }+ .row {+ height: 1px;+ }+ .row:nth-child(odd) {+ background: black;+ }+</style>+<div id="scroller"><div id="rows"></div></div>+<script>+ for (let i = 0; i < 200; i++)+ rows.appendChild(document.createElement("div")).className = "row";+</script>diff --git a/Tests/LibWeb/Ref/input/fractional-scroll-offset-rounds-to-device-pixels.html b/Tests/LibWeb/Ref/input/fractional-scroll-offset-rounds-to-device-pixels.htmlnew file mode 100644index 00000000000..ce71d781563--- /dev/null+++ b/Tests/LibWeb/Ref/input/fractional-scroll-offset-rounds-to-device-pixels.html@@ -0,0 +1,25 @@+<!DOCTYPE html>+<link rel="match" href="../expected/fractional-scroll-offset-rounds-to-device-pixels-ref.html" />+<style>+ body {+ margin: 0;+ }+ #scroller {+ width: 100px;+ height: 100px;+ overflow: hidden;+ }+ .row {+ height: 1px;+ }+ .row:nth-child(odd) {+ background: black;+ }+</style>+<div id="scroller"></div>+<script>+ for (let i = 0; i < 200; i++)+ scroller.appendChild(document.createElement("div")).className = "row";+ // A scroll offset of 10.6px rounds to 11 device pixels, one row away from where truncating it would leave the rows.+ scroller.scrollTop = 10.6;+</script>diff --git a/Tests/LibWeb/Text/expected/hit_testing/fractional-scroll-offset-hit-test.txt b/Tests/LibWeb/Text/expected/hit_testing/fractional-scroll-offset-hit-test.txtnew file mode 100644index 00000000000..15007ac2804--- /dev/null+++ b/Tests/LibWeb/Text/expected/hit_testing/fractional-scroll-offset-hit-test.txt@@ -0,0 +1,8 @@+device pixel ratio 1: 0:r12 1:r13 2:r14 50:r62 138:r150 139:spacer 140:spacer+ r12: top=0 bottom=1+ r13: top=1 bottom=2+ inner: top=-11 bottom=139+device pixel ratio 2: 0:r11 1:r12 2:r13 50:r61 138:r149 139:r150 140:spacer+ r12: top=0.5 bottom=1.5+ r13: top=1.5 bottom=2.5+ inner: top=-10.5 bottom=139.5diff --git a/Tests/LibWeb/Text/input/hit_testing/fractional-scroll-offset-hit-test.html b/Tests/LibWeb/Text/input/hit_testing/fractional-scroll-offset-hit-test.htmlnew file mode 100644index 00000000000..44844e4186f--- /dev/null+++ b/Tests/LibWeb/Text/input/hit_testing/fractional-scroll-offset-hit-test.html@@ -0,0 +1,58 @@+<!DOCTYPE html>+<style>+ body {+ margin: 0;+ }+ #outer {+ position: absolute;+ left: 0;+ top: 0;+ width: 200px;+ height: 200px;+ overflow: scroll;+ scrollbar-width: none;+ }+ #inner {+ width: 180px;+ height: 150px;+ overflow: scroll;+ scrollbar-width: none;+ }+ .row {+ height: 1px;+ }+ #spacer {+ height: 1000px;+ }+</style>+<div id="outer"><div id="inner"></div><div id="spacer"></div></div>+<script src="../include.js"></script>+<script>+ // Scrolling 10.5px and then 0.75px moves the rows by whole device pixels, and hit testing and client rects follow+ // them: each offset rounds to 11px and 1px at 1x, and to 21 and 2 device pixels at 2x.+ promiseTest(async () => {+ for (let i = 0; i < 300; i++) {+ const row = document.createElement("div");+ row.className = "row";+ row.id = "r" + i;+ inner.appendChild(row);+ }+ for (const ratio of [1, 2]) {+ internals.setDevicePixelRatio(ratio);+ outer.scrollTo(0, 0);+ inner.scrollTo(0, 0);+ await animationFrame();+ await animationFrame();+ outer.scrollTo(0, 10.5);+ inner.scrollTo(0, 0.75);+ await animationFrame();+ const hits = [0, 1, 2, 50, 138, 139, 140].map(y => `${y}:${document.elementFromPoint(50, y)?.id}`);+ println(`device pixel ratio ${ratio}: ${hits.join(" ")}`);+ for (const element of [r12, r13, inner]) {+ const rect = element.getBoundingClientRect();+ println(` ${element.id}: top=${rect.top} bottom=${rect.bottom}`);+ }+ }+ internals.setDevicePixelRatio(1);+ });+</script>