Skip to content

Truly independent web browser

LibWeb: Keep compositor scroll nodes and snap geometry in the tree

Aliaksandr Kalenik646b75cb4719
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs b/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs
index 05670b55574..ad925c3b60a 100644
--- a/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs
+++ b/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs
@@ -557,14 +557,28 @@ fn point_to_json(point: CssPixelPoint) -> String {
format!(r#"{{"x":{},"y":{}}}"#, point.x.to_double(), point.y.to_double())
}
+fn int_rect_to_json(rect: IntRect) -> String {
+ format!(
+ r#"{{"x":{},"y":{},"width":{},"height":{}}}"#,
+ rect.x, rect.y, rect.width, rect.height
+ )
+}
+
+fn float_point_to_json(point: FloatPoint) -> String {
+ format!(r#"{{"x":{},"y":{}}}"#, point.x, point.y)
+}
+
pub fn async_scrolling_state_to_json(state: &AsyncScrollingState) -> String {
let mut scroll_nodes = Vec::new();
for scroll_node in &state.scroll_nodes {
scroll_nodes.push(format!(
- r#"{{"scrollNodeIndex":{},"parentScrollNodeIndex":{},"isViewport":{}}}"#,
+ r#"{{"scrollNodeIndex":{},"parentScrollNodeIndex":{},"isViewport":{},"scrollportRect":{},"minScrollOffset":{},"maxScrollOffset":{}}}"#,
scroll_node.scroll_node_index.0,
scroll_node.parent_scroll_node_index.map_or(0, |index| index.0),
- scroll_node.is_viewport
+ scroll_node.is_viewport,
+ int_rect_to_json(scroll_node.scrollport_rect),
+ float_point_to_json(scroll_node.min_scroll_offset),
+ float_point_to_json(scroll_node.max_scroll_offset)
));
}
let mut snap_containers = Vec::new();
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index a78d2d6421b..61327e2d3d1 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -3188,8 +3188,10 @@ void Document::update_paint_and_hit_testing_properties_if_needed()
// Scroll nodes are (re)created by the visual context tree build above, so scroll offsets and
// the snapshot must be derived only after structure work is done.
- if (has_committed_viewport_box())
- paint_state().refresh_scroll_state(read, *this);
+ if (has_committed_viewport_box() && paint_state().refresh_scroll_state(read, *this) == Painting::RequiresDisplayListRecording::Yes) {
+ set_needs_to_record_display_list();
+ m_document->set_needs_repaint();
+ }
}
bool Document::can_compute_client_rects_without_accumulated_visual_contexts_update(Layout::Node const& layout_node) const
@@ -12269,7 +12271,7 @@ Painting::HitTestListAdoption Document::adopt_published_recording(Optional<Layou
}
if (recording.cache_mode == Painting::PaintCommandCacheMode::ReadWrite && !recording_returned_the_paint_command_cache_source)
- document_paint_state.set_display_list_used_as_paint_command_cache_source(display_list, referenced_resources());
+ document_paint_state.set_display_list_used_as_paint_command_cache_source(display_list, referenced_resources(), recording.visual_context_tree);
return adoption;
}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 1afd36007c9..1e6f7166cff 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -1714,7 +1714,7 @@ GC::Ref<JS::Object> Internals::recorded_display_list_wheel_target_at(double x, d
auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
if (!display_list)
return first_wheel_step_route_to_object({ .route = { InputRoutingDecision::NoAsyncScrollingState }, .document_id = {} });
- auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);
+ auto const& visual_context_tree = document.paint_state().paint_command_cache_source_visual_context_tree().value();
auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));
auto encoded_scroll_state = document.paint_state().encoded_scroll_state();
return first_wheel_step_route_to_object(Compositing::route_first_wheel_step_through_recorded_display_list(*display_list, visual_context_tree, encoded_scroll_state, document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_y) }));
@@ -1728,7 +1728,7 @@ bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)
auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
if (!display_list)
return false;
- auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);
+ auto const& visual_context_tree = document.paint_state().paint_command_cache_source_visual_context_tree().value();
auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));
auto encoded_scroll_state = document.paint_state().encoded_scroll_state();
return Compositing::recorded_display_list_blocks_wheel_event_at(*display_list, visual_context_tree, encoded_scroll_state, position);
@@ -4052,10 +4052,9 @@ GC::Ref<JS::Object> Internals::style_invalidation_counters_object() const
GC::Ref<JS::Object> Internals::recorded_async_scrolling_state_object()
{
auto& document = window().associated_document();
- Layout::ForcedReadScope read { document };
auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
auto json = display_list
- ? Compositing::async_scrolling_state_as_json(*display_list, document.paint_state().visual_context_tree_without_update(read, document))
+ ? Compositing::async_scrolling_state_as_json(*display_list, document.paint_state().paint_command_cache_source_visual_context_tree().value())
: Compositing::empty_async_scrolling_state_as_json();
auto report = MUST(JsonValue::from_string(json));
return scrolling_state_report_to_object(window(), report.as_object());
diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.cpp b/Libraries/LibWeb/Painting/DocumentPaintState.cpp
index 856d49ecd22..599766cf8e2 100644
--- a/Libraries/LibWeb/Painting/DocumentPaintState.cpp
+++ b/Libraries/LibWeb/Painting/DocumentPaintState.cpp
@@ -139,10 +139,16 @@ void DocumentPaintState::append_paint_command_cache_source_resources(Compositing
retained_resources.include(m_paint_command_cache_source_referenced_resources);
}
-void DocumentPaintState::refresh_scroll_state(Layout::BegunRead const& read, DOM::Document& document)
+RequiresDisplayListRecording DocumentPaintState::refresh_scroll_state(Layout::BegunRead const& read, DOM::Document& document)
{
- if (Layout::RustFFI::render_state_refresh_scroll_state(m_layout_node_arena->host(), &read, document.page().client().device_pixels_per_css_pixel()))
+ auto outcome = Layout::RustFFI::render_state_refresh_scroll_state(
+ m_layout_node_arena->host(), &read, document.page().client().device_pixels_per_css_pixel(),
+ document.page().css_to_device_rect(document.viewport_rect()).size().to_type<int>());
+ if (outcome.scroll_state_changed)
m_scroll_state_changed = true;
+ if (outcome.table_changed)
+ did_update_visual_context_values();
+ return outcome.requires_display_list_recording ? RequiresDisplayListRecording::Yes : RequiresDisplayListRecording::No;
}
Layout::RustFFI::FfiViewportMapping DocumentPaintState::viewport_mapping(Compositing::AccumulatedVisualContextTree const& visual_context_tree, double device_pixels_per_css_pixel) const
diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.h b/Libraries/LibWeb/Painting/DocumentPaintState.h
index 7a370cf9cc1..3ddbfefc040 100644
--- a/Libraries/LibWeb/Painting/DocumentPaintState.h
+++ b/Libraries/LibWeb/Painting/DocumentPaintState.h
@@ -25,6 +25,11 @@ struct BlockingWheelEventRegionState {
bool has_blocking_wheel_event_region_covering_viewport { false };
};
+enum class RequiresDisplayListRecording {
+ No,
+ Yes,
+};
+
class WEB_API DocumentPaintState {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -37,7 +42,7 @@ public:
// Called from Document::update_paint_and_hit_testing_properties_if_needed() once the visual
// context tree is settled; every other consumer reaches the scroll state through that update.
- void refresh_scroll_state(Layout::BegunRead const& read, DOM::Document&);
+ RequiresDisplayListRecording refresh_scroll_state(Layout::BegunRead const& read, DOM::Document&);
// The mapping reads the tree and the scroll state where it is used, so the tree has to outlive it.
Layout::RustFFI::FfiViewportMapping viewport_mapping(Compositing::AccumulatedVisualContextTree const&, double device_pixels_per_css_pixel) const;
// Only the scroll logic of the compositor, which is Rust, decodes it.
@@ -82,14 +87,17 @@ public:
Compositing::AccumulatedVisualContextTree visual_context_tree_without_update(Layout::BegunRead const& read, DOM::Document const&) const;
u64 visual_context_tree_structural_epoch_without_update(Layout::BegunRead const& read) const;
- void set_display_list_used_as_paint_command_cache_source(RefPtr<Compositing::DisplayList> display_list, Compositing::DisplayListResourceSet referenced_resources)
+ void set_display_list_used_as_paint_command_cache_source(RefPtr<Compositing::DisplayList> display_list, Compositing::DisplayListResourceSet referenced_resources, Compositing::AccumulatedVisualContextTree visual_context_tree)
{
m_display_list_used_as_paint_command_cache_source = move(display_list);
+ m_paint_command_cache_source_visual_context_tree = move(visual_context_tree);
m_paint_command_cache_source_referenced_resources = move(referenced_resources);
}
Compositing::DisplayList* display_list_used_as_paint_command_cache_source() const { return m_display_list_used_as_paint_command_cache_source.ptr(); }
Compositing::DisplayListResourceSet const& paint_command_cache_source_referenced_resources() const { return m_paint_command_cache_source_referenced_resources; }
+ Optional<Compositing::AccumulatedVisualContextTree> const& paint_command_cache_source_visual_context_tree() const { return m_paint_command_cache_source_visual_context_tree; }
+
void append_paint_command_cache_source_resources(Compositing::DisplayListResourceSet&) const;
private:
@@ -101,6 +109,7 @@ private:
Vector<Compositing::RustFFI::NodeSlotId> m_boxes_with_auto_content_visibility;
RefPtr<Compositing::DisplayList> m_display_list_used_as_paint_command_cache_source;
+ Optional<Compositing::AccumulatedVisualContextTree> m_paint_command_cache_source_visual_context_tree;
Compositing::DisplayListResourceSet m_paint_command_cache_source_referenced_resources;
u64 m_accumulated_visual_context_tree_build_count { 0 };
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
index ff902144953..3577e8bc971 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
@@ -483,17 +483,21 @@ pub unsafe extern "C" fn render_state_sync_svg_paint_resources(
/// Re-reads the scroll containers' offsets when something invalidated them since the last refresh, resolves the
/// sticky nodes' offsets on top of them, and has `host` keep them as its document's scroll state; otherwise the host
-/// keeps the one it has. Answers whether the offsets changed.
+/// keeps the one it has. Refreshes the compositor scroll table of the tree as well. Answers whether the offsets
+/// changed, and what refreshing the table changed.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_refresh_scroll_state(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
device_pixels_per_css_pixel: f64,
-) -> bool {
- let device_offsets = run_paint_pass(read, host, PassEffect::RewritesRows, |arena| {
- crate::painting::paint_passes::refresh_scroll_state(arena, device_pixels_per_css_pixel)
+ device_viewport_size: libgfx_rust::IntSize,
+) -> crate::painting::paint_passes::FfiCompositorScrollRefreshOutcome {
+ let (device_offsets, mut outcome) = run_paint_pass(read, host, PassEffect::RewritesRows, |arena| {
+ crate::painting::paint_passes::refresh_scroll_state(arena, device_pixels_per_css_pixel, device_viewport_size)
});
- device_offsets.is_some_and(|device_offsets| host.refresh_scroll_state(device_offsets))
+ outcome.scroll_state_changed =
+ device_offsets.is_some_and(|device_offsets| host.refresh_scroll_state(device_offsets));
+ outcome
}
/// Has `host` forget its document's scroll state, as the viewport's row or the document's paint state starts over.
diff --git a/Libraries/LibWeb/Rust/src/painting/paint_passes.rs b/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
index 8a597852d57..597fc3f364c 100644
--- a/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
@@ -13,13 +13,16 @@ use crate::layout::node_data::NodeSlotId;
use crate::painting::host::{FfiVisualContextTreeInputs, FfiVisualContextUpdateOutcome, RootBackgroundSource};
use crate::painting::paint_read::PaintRead;
use crate::painting::svg_paint_resources::{PublishedSvgFilter, PublishedSvgPaintServer, SvgPaintResourceKind};
+use crate::painting::visual_context::compositor_scroll_table::{
+ CompositorScrollInputs, refresh_compositor_scroll_table,
+};
use crate::painting::visual_context::dirty::VisualContextUpdateScope;
use crate::painting::visual_context::incremental::{
IncrementalUpdateResult, debug_assert_every_live_node_is_owned, update_visual_context_tree,
};
use crate::painting::visual_context::{VisualContextState, VisualContextTree};
use crate::render_state::{BegunRead, DocumentHost};
-use libgfx_rust::FloatPoint;
+use libgfx_rust::{FloatPoint, IntSize};
use std::sync::Arc;
/// What a paint pass writes, which decides what the host lets go of before it sends the pass, and whether the paint and
@@ -49,6 +52,14 @@ pub struct FfiRenderingPreparationOutcome {
pub visual_context_values_changed: bool,
}
+#[derive(Default)]
+#[repr(C)]
+pub struct FfiCompositorScrollRefreshOutcome {
+ pub scroll_state_changed: bool,
+ pub table_changed: bool,
+ pub requires_display_list_recording: bool,
+}
+
/// What preparing for rendering answers: its outcome, and the scroll offsets the new overflow moved out of range,
/// each clamped into it, for the host to store.
pub(crate) struct RenderingPreparation {
@@ -87,6 +98,17 @@ pub(crate) fn prepare_for_clock_tick(
"SVG paint resources or the root background moved",
));
}
+ let scroll_table_changed = arena.with_visual_context_state_lent(|arena, state| {
+ if !state.dirty_boxes.boxes.is_empty()
+ || !state.dirty_boxes.removed.is_empty()
+ || state.dirty_boxes.scope.rebuilds_every_box()
+ {
+ return false;
+ }
+ state
+ .last_compositor_scroll_inputs
+ .is_some_and(|inputs| refresh_compositor_scroll_table(arena, state, inputs).table_changed)
+ });
let (inputs, compositor_animations) = {
let paint_state = arena.paint_state_mut();
let state = &mut paint_state.visual_context;
@@ -98,7 +120,7 @@ pub(crate) fn prepare_for_clock_tick(
}
if state.dirty_boxes.boxes.is_empty() && state.dirty_boxes.removed.is_empty() {
// A tick that stopped compositor animations of the host's takes the tree without them to the compositor.
- if tree.visual_animations() == state.published_compositor_animations.as_slice() {
+ if !scroll_table_changed && tree.visual_animations() == state.published_compositor_animations.as_slice() {
return Ok(None);
}
state.published_compositor_animations = tree.visual_animations().to_vec();
@@ -124,6 +146,9 @@ pub(crate) fn prepare_for_clock_tick(
return Err(VisualContextsNeedHost("a full visual context tree build"));
}
arena.with_visual_context_state_lent(|arena, state| {
+ if let Some(inputs) = state.last_compositor_scroll_inputs {
+ refresh_compositor_scroll_table(arena, state, inputs);
+ }
let tree = state.tree.as_mut().expect("an incremental update keeps the tree");
if !outcome.structural_epoch_changed {
return Ok(Some(ClockTickVisualContexts {
@@ -349,15 +374,24 @@ pub(crate) fn prepare_for_rendering(
pub(crate) fn refresh_scroll_state(
arena: &mut LayoutNodeArena,
device_pixels_per_css_pixel: f64,
-) -> Option<Vec<FloatPoint>> {
+ device_viewport_size: IntSize,
+) -> (Option<Vec<FloatPoint>>, FfiCompositorScrollRefreshOutcome) {
arena.settle_scrollable_overflow();
arena.with_visual_context_state_lent(|arena, state| {
+ let outcome = refresh_compositor_scroll_table(
+ arena,
+ state,
+ CompositorScrollInputs {
+ device_pixels_per_css_pixel,
+ device_viewport_size,
+ },
+ );
if !state.needs_to_refresh_scroll_state {
- return None;
+ return (None, outcome);
}
let snapshot = scroll_state_snapshot(&arena.paintable_rows(), state, device_pixels_per_css_pixel);
state.needs_to_refresh_scroll_state = false;
- Some(snapshot)
+ (Some(snapshot), outcome)
})
}
diff --git a/Libraries/LibWeb/Rust/src/painting/paint_state.rs b/Libraries/LibWeb/Rust/src/painting/paint_state.rs
index ba68335b1f2..89101b888de 100644
--- a/Libraries/LibWeb/Rust/src/painting/paint_state.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paint_state.rs
@@ -123,11 +123,10 @@ impl crate::layout::LayoutNodeArena {
true
}
- /// Lends the visual context state out of the paint state to `update`, which reads the rest of the arena beside it:
- /// refreshing the scroll state and the sticky constraints reads the rows while it writes the state.
+ /// Lends the visual context state to `update`, which can read the rows and push paint damage beside it.
pub(crate) fn with_visual_context_state_lent<T>(
&mut self,
- update: impl FnOnce(&Self, &mut crate::painting::visual_context::VisualContextState) -> T,
+ update: impl FnOnce(&mut Self, &mut crate::painting::visual_context::VisualContextState) -> T,
) -> T {
let mut state = std::mem::take(&mut self.paint_state_mut().visual_context);
let answer = update(self, &mut state);
diff --git a/Libraries/LibWeb/Rust/src/painting/record/async_scroll_metadata.rs b/Libraries/LibWeb/Rust/src/painting/record/async_scroll_metadata.rs
index 91cb32d78e9..36292106c79 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/async_scroll_metadata.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/async_scroll_metadata.rs
@@ -95,6 +95,16 @@ fn compositor_snap_area_command(
}
impl<O: Observer> PaintRecorder<'_, O> {
+ pub(crate) fn has_compositor_scroll_node(&self, paintable: NodeSlotId) -> bool {
+ let index = self.data(paintable).own_scroll_node_index;
+ self.paint_state.visual_context_tree.as_ref().is_some_and(|tree| {
+ tree.compositor_scroll_table()
+ .nodes
+ .binary_search_by_key(&index, |node| node.scroll_node_index)
+ .is_ok()
+ })
+ }
+
fn wheel_scrollable_axes(&mut self, paintable: NodeSlotId) -> PhysicalAxes {
let facts = self.hit_test_facts(paintable);
PhysicalAxes {
@@ -114,7 +124,7 @@ impl<O: Observer> PaintRecorder<'_, O> {
}
paintables_to_cache.push(current);
- if compositor_scroll_node_kind(self.source, current, |slot| self.wheel_scrollable_axes(slot)).is_some() {
+ if self.has_compositor_scroll_node(current) {
target = self.data(current).own_scroll_node_index;
break;
}
@@ -126,7 +136,7 @@ impl<O: Observer> PaintRecorder<'_, O> {
if let Some(block) = containing_block
&& style_queries::is_fixed_position(self.source, block)
{
- if compositor_scroll_node_kind(self.source, block, |slot| self.wheel_scrollable_axes(slot)).is_some() {
+ if self.has_compositor_scroll_node(block) {
target = self.data(block).own_scroll_node_index;
}
if target != VISUAL_VIEWPORT_NODE_INDEX {
@@ -302,7 +312,7 @@ impl<O: Observer> PaintRecorder<'_, O> {
colors: ScrollbarColors,
) {
if self.source.node_kind_if_live(paintable) == Some(NodeKind::Viewport)
- || compositor_scroll_node_kind(self.source, paintable, |slot| self.wheel_scrollable_axes(slot)).is_none()
+ || !self.has_compositor_scroll_node(paintable)
|| !self.visibility_is_visible(paintable)
|| !self.visible_for_hit_testing(paintable)
{
diff --git a/Libraries/LibWeb/Rust/src/painting/record/damage.rs b/Libraries/LibWeb/Rust/src/painting/record/damage.rs
index 08beb689534..e01dd79f126 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/damage.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/damage.rs
@@ -153,6 +153,7 @@ pub(crate) struct DamageSet {
all: u32,
scroll_metadata_everywhere: u32,
started_publishing_recordings: u32,
+ push_revision: u64,
}
impl DamageSet {
@@ -251,6 +252,7 @@ impl LayoutNodeArena {
if damage.is_empty() || !self.paintable_row_is_populated(row) {
return;
}
+ self.paintable_rows.damage.push_revision += 1;
let stamp = self.paintable_rows.damage.stamp_for_push();
// Whole-document damage pushed for the same recording already covers every row.
if self.paintable_rows.damage.all == stamp {
@@ -362,14 +364,20 @@ impl LayoutNodeArena {
pub(crate) fn push_all_paint_damage(&mut self) {
let set = &mut self.paintable_rows.damage;
+ set.push_revision += 1;
set.all = set.stamp_for_push();
}
pub(crate) fn push_scroll_metadata_damage_everywhere(&mut self) {
let set = &mut self.paintable_rows.damage;
+ set.push_revision += 1;
set.scroll_metadata_everywhere = set.stamp_for_push();
}
+ pub(crate) fn paint_damage_push_revision(&self) -> u64 {
+ self.paintable_rows.damage.push_revision
+ }
+
pub(crate) fn paint_damage_covers_everything(&self) -> bool {
self.paintable_rows.damage.all != 0
}
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/compositor_scroll_table.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/compositor_scroll_table.rs
index f89a3d94e06..526cd4c9c10 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_context/compositor_scroll_table.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/compositor_scroll_table.rs
@@ -9,11 +9,12 @@ use crate::layout::node_data::{DomPaintFact, NodeKind, NodeSlotId};
use crate::painting::chrome_geometry::{PhysicalAxes, maximum_scroll_offset, minimum_scroll_offset};
use crate::painting::display_list::commands::UniqueNodeId;
use crate::painting::display_list::device_pixels::DevicePixelConverter;
+use crate::painting::paint_passes::FfiCompositorScrollRefreshOutcome;
use crate::painting::paint_read::PaintRead;
use crate::painting::{paintable_geometry, scroll_snap, style_queries};
use libcompositing_rust::visual_context::{
CompositorScrollNodeKind, CompositorScrollNodeRecord, CompositorSnapAreaRecord, CompositorSnapContainerRecord,
- VISUAL_VIEWPORT_NODE_INDEX,
+ SpatialData, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,
};
use libgfx_rust::{FloatPoint, IntRect, IntSize};
@@ -154,3 +155,141 @@ pub(crate) fn compositor_snap_container_and_area_records(
});
Some((container, areas))
}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct CompositorScrollInputs {
+ pub(crate) device_pixels_per_css_pixel: f64,
+ pub(crate) device_viewport_size: IntSize,
+}
+
+pub(crate) fn refresh_compositor_scroll_table(
+ arena: &mut crate::layout::LayoutNodeArena,
+ state: &mut super::VisualContextState,
+ inputs: CompositorScrollInputs,
+) -> FfiCompositorScrollRefreshOutcome {
+ use crate::painting::record::damage::PaintDamage;
+ use libcompositing_rust::visual_context::CompositorScrollTable;
+ use std::sync::Arc;
+
+ let Some(tree) = state.tree.as_mut() else {
+ return FfiCompositorScrollRefreshOutcome::default();
+ };
+ let previous = tree.compositor_scroll_table();
+ let inputs_changed = state.last_compositor_scroll_inputs != Some(inputs);
+ let new_damage = state.compositor_snap_damage_revision != Some(arena.paint_damage_push_revision());
+ let damage_everywhere = arena.paint_damage_covers_everything() || arena.scroll_metadata_damaged_everywhere();
+ let source = arena.paintable_rows();
+ let wheel_axes = |slot| crate::painting::chrome_geometry::wheel_scrollable_axes(&source, slot);
+ let mut nodes_with_owners = Vec::new();
+ for (index, spatial_node) in tree.spatial_nodes.iter().enumerate() {
+ let SpatialData::Scroll(scroll) = &spatial_node.data else {
+ continue;
+ };
+ let owner = scroll.owner_paintable;
+ if !source.paintable_row_is_populated(owner) {
+ continue;
+ }
+ if let Some(kind) = compositor_scroll_node_kind(&source, owner, wheel_axes) {
+ let node = compositor_scroll_node_record(
+ &source,
+ owner,
+ kind,
+ inputs.device_pixels_per_css_pixel,
+ inputs.device_viewport_size,
+ wheel_axes,
+ );
+ debug_assert_eq!(node.scroll_node_index, SpatialNodeIndex(index as u32));
+ nodes_with_owners.push((node, owner));
+ }
+ }
+ nodes_with_owners.sort_unstable_by_key(|(node, _)| node.scroll_node_index);
+ let mut containers = Vec::new();
+ let mut areas = Vec::new();
+ let mut damaged_subtrees = Vec::new();
+ let mut removed_snap_container_owners = Vec::new();
+ for (node, owner) in &nodes_with_owners {
+ let previous_node = previous
+ .nodes
+ .binary_search_by_key(&node.scroll_node_index, |node| node.scroll_node_index)
+ .ok()
+ .map(|index| &previous.nodes[index]);
+ let same_identity = previous_node.is_some_and(|before| {
+ before.scrollable_node_id == node.scrollable_node_id
+ && before.scroll_node_kind == node.scroll_node_kind
+ && before.pseudo_element_type == node.pseudo_element_type
+ });
+ if !same_identity
+ || previous_node.is_some_and(|before| before.parent_scroll_node_index != node.parent_scroll_node_index)
+ {
+ damaged_subtrees.push(*owner);
+ }
+ let recompute = inputs_changed
+ || !same_identity
+ || (new_damage && (damage_everywhere || !arena.row_paint_state(*owner).damage().is_empty()));
+ let snap_records = if recompute {
+ compositor_snap_container_and_area_records(&source, *owner)
+ } else {
+ previous
+ .snap_containers
+ .binary_search_by_key(&node.scroll_node_index, |container| container.scroll_node_index)
+ .ok()
+ .map(|index| {
+ let container = previous.snap_containers[index];
+ let first = container.first_area_index as usize;
+ let end = first + container.area_count as usize;
+ (container, previous.snap_areas[first..end].to_vec())
+ })
+ };
+ if snap_records.is_none()
+ && previous
+ .snap_containers
+ .binary_search_by_key(&node.scroll_node_index, |container| container.scroll_node_index)
+ .is_ok()
+ {
+ removed_snap_container_owners.push(*owner);
+ }
+ if let Some((mut container, container_areas)) = snap_records {
+ container.first_area_index = areas.len().try_into().expect("snap area index fits in u32");
+ container.area_count = container_areas.len().try_into().expect("snap area count fits in u32");
+ areas.extend(container_areas);
+ containers.push(container);
+ }
+ }
+ for (before, owner) in previous.nodes.iter().zip(&state.compositor_scroll_owners) {
+ if !nodes_with_owners
+ .binary_search_by_key(&before.scroll_node_index, |(node, _)| node.scroll_node_index)
+ .is_ok_and(|index| nodes_with_owners[index].1 == *owner)
+ && source.paintable_row_is_populated(*owner)
+ {
+ damaged_subtrees.push(*owner);
+ }
+ }
+ state.compositor_scroll_owners = nodes_with_owners.iter().map(|(_, owner)| *owner).collect();
+ let refreshed = CompositorScrollTable {
+ nodes: nodes_with_owners
+ .into_iter()
+ .map(|(node, _)| node)
+ .collect::<Vec<_>>()
+ .into(),
+ snap_containers: containers.into(),
+ snap_areas: areas.into(),
+ };
+ let table_changed = *previous != refreshed;
+ if table_changed {
+ Arc::make_mut(tree).set_compositor_scroll_table(refreshed);
+ }
+ let requires_display_list_recording = !damaged_subtrees.is_empty();
+ for owner in damaged_subtrees {
+ arena.push_paint_damage_to_paint_subtree(owner, PaintDamage::SCROLL_METADATA);
+ }
+ for owner in removed_snap_container_owners {
+ arena.push_paint_damage(owner, PaintDamage::SCROLL_METADATA);
+ }
+ state.last_compositor_scroll_inputs = Some(inputs);
+ state.compositor_snap_damage_revision = Some(arena.paint_damage_push_revision());
+ FfiCompositorScrollRefreshOutcome {
+ table_changed,
+ requires_display_list_recording,
+ ..Default::default()
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs
index c4b13f4fd7f..8840213a019 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs
@@ -18,6 +18,11 @@ pub struct VisualContextState {
pub scroll_state: scroll_state::ScrollState,
pub needs_to_refresh_scroll_state: bool,
pub dirty_boxes: dirty::VisualContextDirtySet,
+ pub(crate) last_compositor_scroll_inputs: Option<super::compositor_scroll_table::CompositorScrollInputs>,
+ // The owners of the tree's compositor scroll rows, in row order, so refresh can find boxes that left the table.
+ pub(crate) compositor_scroll_owners: Vec<NodeSlotId>,
+ // The paint damage push revision the table's snap geometry was last brought up to.
+ pub(crate) compositor_snap_damage_revision: Option<u64>,
pub last_tree_inputs: Option<crate::painting::host::FfiVisualContextTreeInputs>,
// The viewport's overflow when the tree was last updated. A sticky box finds its scrolling box by it.
pub last_viewport_overflow: (u8, u8),
diff --git a/Tests/LibWeb/Text/expected/async-scrolling/tree-scroll-range-after-layout.txt b/Tests/LibWeb/Text/expected/async-scrolling/tree-scroll-range-after-layout.txt
new file mode 100644
index 00000000000..b357a8d6730
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/async-scrolling/tree-scroll-range-after-layout.txt
@@ -0,0 +1,3 @@
+grown range: 500
+shrunk range: 100
+clamped compositor offset: 100
diff --git a/Tests/LibWeb/Text/expected/async-scrolling/tree-scrollport-after-ancestor-margin.txt b/Tests/LibWeb/Text/expected/async-scrolling/tree-scrollport-after-ancestor-margin.txt
new file mode 100644
index 00000000000..9aebb7d24cb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/async-scrolling/tree-scrollport-after-ancestor-margin.txt
@@ -0,0 +1,2 @@
+moved by 37 CSS pixels, rounded to device pixels: true
+other dimensions unchanged: true
diff --git a/Tests/LibWeb/Text/expected/async-scrolling/tree-snap-area-after-layout.txt b/Tests/LibWeb/Text/expected/async-scrolling/tree-snap-area-after-layout.txt
new file mode 100644
index 00000000000..3af9169a461
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/async-scrolling/tree-snap-area-after-layout.txt
@@ -0,0 +1,2 @@
+snap area movement: 75
+other dimensions unchanged: true
diff --git a/Tests/LibWeb/Text/expected/async-scrolling/tree-unpainted-scroller.txt b/Tests/LibWeb/Text/expected/async-scrolling/tree-unpainted-scroller.txt
new file mode 100644
index 00000000000..0de8f681f64
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/async-scrolling/tree-unpainted-scroller.txt
@@ -0,0 +1,3 @@
+unpainted scroller has a node: true
+scroll range: 200
+compositor offset: 75
diff --git a/Tests/LibWeb/Text/expected/async-scrolling/tree-viewport-snap-areas.txt b/Tests/LibWeb/Text/expected/async-scrolling/tree-viewport-snap-areas.txt
new file mode 100644
index 00000000000..3ae91951c35
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/async-scrolling/tree-viewport-snap-areas.txt
@@ -0,0 +1,4 @@
+viewport snap strictness: proximity
+viewport snaps vertically: true
+viewport snap area y: 125
+viewport snap area height: 50
diff --git a/Tests/LibWeb/Text/input/async-scrolling/tree-scroll-range-after-layout.html b/Tests/LibWeb/Text/input/async-scrolling/tree-scroll-range-after-layout.html
new file mode 100644
index 00000000000..7315f474141
--- /dev/null
+++ b/Tests/LibWeb/Text/input/async-scrolling/tree-scroll-range-after-layout.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ #scroller { width: 100px; height: 100px; overflow: hidden; }
+ #content { height: 300px; }
+</style>
+<div id="scroller"><div id="content"></div></div>
+<script>
+ promiseTest(async () => {
+ const state = () => internals.compositorScrollState(scroller);
+ const node = () => state().scrollNodes.find(node => !node.isViewport);
+ async function until(condition) {
+ while (!condition())
+ await animationFrame();
+ }
+ await until(() => state().document === document && node());
+
+ const maximum = () => Math.round(node().maxScrollOffset.y / state().devicePixelsPerCssPixel);
+ await until(() => maximum() === 200);
+ content.style.height = "600px";
+ await until(() => maximum() === 500);
+ println(`grown range: ${maximum()}`);
+ scroller.scrollTop = 450;
+ await until(() => state().scrollOffset.y === 450);
+ content.style.height = "200px";
+ await until(() => maximum() === 100 && state().scrollOffset.y === 100);
+ println(`shrunk range: ${maximum()}`);
+ println(`clamped compositor offset: ${state().scrollOffset.y}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/async-scrolling/tree-scrollport-after-ancestor-margin.html b/Tests/LibWeb/Text/input/async-scrolling/tree-scrollport-after-ancestor-margin.html
new file mode 100644
index 00000000000..f1619a3fd8b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/async-scrolling/tree-scrollport-after-ancestor-margin.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; }
+ #scroller { width: 100px; height: 100px; overflow: hidden; }
+</style>
+<div id="ancestor"><div id="scroller"><div style="height: 300px"></div></div></div>
+<script>
+ promiseTest(async () => {
+ const state = () => internals.compositorScrollState(scroller);
+ const node = () => state().scrollNodes.find(node => !node.isViewport);
+ async function until(condition) {
+ while (!condition())
+ await animationFrame();
+ }
+ await until(() => state().document === document && node());
+
+ const initial = node().scrollportRect;
+ const expectedX = initial.x + Math.round(37 * state().devicePixelsPerCssPixel);
+ ancestor.style.marginLeft = "37px";
+ await until(() => node().scrollportRect.x === expectedX);
+ const moved = node().scrollportRect;
+ println(`moved by 37 CSS pixels, rounded to device pixels: ${moved.x === expectedX}`);
+ println(`other dimensions unchanged: ${moved.y === initial.y && moved.width === initial.width && moved.height === initial.height}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/async-scrolling/tree-snap-area-after-layout.html b/Tests/LibWeb/Text/input/async-scrolling/tree-snap-area-after-layout.html
new file mode 100644
index 00000000000..c07e0606e93
--- /dev/null
+++ b/Tests/LibWeb/Text/input/async-scrolling/tree-snap-area-after-layout.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ #scroller { width: 100px; height: 100px; overflow: hidden; scroll-snap-type: y proximity; }
+ #area { height: 50px; scroll-snap-align: start; }
+</style>
+<div id="scroller"><div id="spacer" style="height: 150px"></div><div id="area"></div><div style="height: 300px"></div></div>
+<script>
+ promiseTest(async () => {
+ const state = () => internals.compositorScrollState(scroller);
+ const node = () => state().scrollNodes.find(node => !node.isViewport);
+ async function until(condition) {
+ while (!condition())
+ await animationFrame();
+ }
+ await until(() => state().document === document && node());
+
+ const container = () => state().snapContainers.find(container => container.scrollNodeIndex === node().scrollNodeIndex);
+ await until(() => container()?.areas.length === 1);
+ const initial = container().areas[0].rect;
+ spacer.style.height = "225px";
+ await until(() => container()?.areas[0]?.rect.y === initial.y + 75);
+ const moved = container().areas[0].rect;
+ println(`snap area movement: ${moved.y - initial.y}`);
+ println(`other dimensions unchanged: ${moved.x === initial.x && moved.width === initial.width && moved.height === initial.height}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/async-scrolling/tree-unpainted-scroller.html b/Tests/LibWeb/Text/input/async-scrolling/tree-unpainted-scroller.html
new file mode 100644
index 00000000000..6418797240f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/async-scrolling/tree-unpainted-scroller.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ #ancestor { scale: 0; }
+ #scroller { width: 100px; height: 100px; overflow: hidden; }
+</style>
+<div id="ancestor"><div id="scroller"><div style="height: 300px"></div></div></div>
+<script>
+ promiseTest(async () => {
+ const state = () => internals.compositorScrollState(scroller);
+ const node = () => state().scrollNodes.find(node => !node.isViewport);
+ async function until(condition) {
+ while (!condition())
+ await animationFrame();
+ }
+ await until(() => state().document === document && node());
+
+ println(`unpainted scroller has a node: ${!!node()}`);
+ println(`scroll range: ${Math.round(node().maxScrollOffset.y / state().devicePixelsPerCssPixel)}`);
+ scroller.scrollTop = 75;
+ await until(() => state().scrollOffset?.y === 75);
+ println(`compositor offset: ${state().scrollOffset.y}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/async-scrolling/tree-viewport-snap-areas.html b/Tests/LibWeb/Text/input/async-scrolling/tree-viewport-snap-areas.html
new file mode 100644
index 00000000000..3b356e132e1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/async-scrolling/tree-viewport-snap-areas.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ html { scroll-snap-type: y proximity; }
+ body { margin: 0; }
+ #area { margin-top: 125px; height: 50px; scroll-snap-align: start; }
+</style>
+<div id="area"></div><div style="height: 2000px"></div>
+<script>
+ promiseTest(async () => {
+ const state = () => internals.compositorScrollState();
+ const container = () => {
+ const current = state();
+ const viewport = current.scrollNodes.find(node => node.isViewport);
+ return current.snapContainers.find(container => container.scrollNodeIndex === viewport?.scrollNodeIndex);
+ };
+ while (state().document !== document || container()?.areas.length !== 1)
+ await animationFrame();
+ const snap = container();
+ println(`viewport snap strictness: ${snap.strictness}`);
+ println(`viewport snaps vertically: ${snap.snapsY}`);
+ println(`viewport snap area y: ${snap.areas[0].rect.y}`);
+ println(`viewport snap area height: ${snap.areas[0].rect.height}`);
+ });
+</script>