Truly independent web browser
LibWeb: Map viewports through the tree the document host keeps
Aliaksandr Kalenikc4f018eb698b
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 4ad7d7414df..94d33d86410 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -7993,7 +7993,7 @@ void Document::queue_an_intersection_observer_entry(IntersectionObserver::Inters}// https://www.w3.org/TR/intersection-observer/#compute-the-intersection-static Optional<CSSPixelRect> compute_intersection(Layout::BegunRead const& read, GC::Ref<Element> target, CSSPixelRect target_rect, IntersectionObserver::IntersectionObserver const& observer, Layout::Box const* root_layout_box, CSSPixelRect const& root_bounds, Compositing::AccumulatedVisualContextTree const& visual_context_tree)+static Optional<CSSPixelRect> compute_intersection(Layout::BegunRead const& read, GC::Ref<Element> target, CSSPixelRect target_rect, IntersectionObserver::IntersectionObserver const& observer, Layout::Box const* root_layout_box, CSSPixelRect const& root_bounds, MonotonicTime visual_animation_sample_time){auto& document = target->document();auto const& scroll_margin = observer.scroll_margin_values();@@ -8012,7 +8012,7 @@ static Optional<CSSPixelRect> compute_intersection(Layout::BegunRead const& readauto intersects = Layout::RustFFI::layout_script_intersection_observer_intersection_rect(document.layout_node_arena().host(), Layout::Node::slot_id(target->layout_node(read)), target_rect,Layout::Node::slot_id(root_layout_box), root_bounds,- Painting::viewport_mapping(document, visual_context_tree),+ Painting::viewport_mapping_with_visual_animations_sampled_at(document, visual_animation_sample_time),const_cast<Vector<CSS::LengthPercentage>*>(&scroll_margin), inflate_scroll_container_clip_rect_by_scroll_margin, &rect);if (!intersects)return {};@@ -8036,20 +8036,9 @@ void Document::run_the_update_intersection_observations_steps(HighResolutionTimefor (auto& observer : m_intersection_observers)intersection_observers.append(observer);- GC::RootHashMap<Document*, Compositing::AccumulatedVisualContextTree> observation_visual_context_trees;- auto sample_time_ns = MonotonicTime::now().nanoseconds();- auto sampled_visual_context_tree = [&](Document& document) -> Optional<Compositing::AccumulatedVisualContextTree> {- if (!document.m_paint_state)- return {};- if (auto cached_tree = observation_visual_context_trees.get(&document); cached_tree.has_value())- return *cached_tree;- auto committed_tree = document.paint_state().visual_context_tree(document);- auto sampled_tree = committed_tree.has_visual_animations()- ? committed_tree.with_visual_animation_samples(sample_time_ns)- : committed_tree;- observation_visual_context_trees.set(&document, sampled_tree);- return sampled_tree;- };+ // Every document the observers read is mapped with the compositor's animations sampled at one time, as the screen+ // shows them then.+ auto const visual_animation_sample_time = MonotonicTime::now();for (auto& observer : intersection_observers) {observer->remove_dead_observation_targets();@@ -8060,10 +8049,9 @@ void Document::run_the_update_intersection_observations_steps(HighResolutionTimeLayout::ForcedReadScope root_read { intersection_root_node->document() };// 1. Let rootBounds be observer’s root intersection rectangle.- auto root_visual_context_tree = sampled_visual_context_tree(intersection_root_node->document());- if (!root_visual_context_tree.has_value())+ if (!intersection_root_node->document().has_paint_state())continue;- auto root_bounds = observer->root_intersection_rectangle(root_read, &*root_visual_context_tree);+ auto root_bounds = observer->root_intersection_rectangle(root_read, visual_animation_sample_time);// Pre-compute per-observer values to avoid repeated work in the per-target loop.// An inline element root has a committed box but no Layout::Box. No containing block chain passes@@ -8122,16 +8110,15 @@ void Document::run_the_update_intersection_observations_steps(HighResolutionTime}}if (!root_is_hidden && target_layout_node && (is_implicit_root || &target->document() == &intersection_root_node->document()) && root_contains_target) {- auto target_visual_context_tree = sampled_visual_context_tree(target->document());- if (!target_visual_context_tree.has_value())+ if (!target->document().has_paint_state())continue;// 4. Set targetRect to the DOMRectReadOnly obtained by getting the bounding box for target.- target_rect = target->bounding_client_rect_assuming_layout_clean(target_read, *target_visual_context_tree);+ target_rect = target->bounding_client_rect_assuming_layout_clean(target_read, visual_animation_sample_time);// 5. Let intersectionRect be the result of running the compute the intersection algorithm on target and// observer’s intersection root.- auto maybe_intersection_rect = compute_intersection(target_read, target, target_rect, *observer, root_layout_box, root_bounds, *target_visual_context_tree);+ auto maybe_intersection_rect = compute_intersection(target_read, target, target_rect, *observer, root_layout_box, root_bounds, visual_animation_sample_time);if (maybe_intersection_rect.has_value())intersection_rect = *maybe_intersection_rect;@@ -8464,11 +8451,6 @@ Painting::DocumentPaintState const& Document::paint_state() constreturn *m_paint_state;}-Compositing::AccumulatedVisualContextTree Document::visual_context_tree() const-{- return paint_state().visual_context_tree(*this);-}-// https://html.spec.whatwg.org/multipage/browsing-the-web.html#restore-the-history-object-statevoid Document::restore_the_history_object_state(NonnullRefPtr<HTML::SessionHistoryEntry> entry){@@ -9279,7 +9261,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)}};- Optional<Compositing::AccumulatedVisualContextTree> visual_context_tree = paint_state().visual_context_tree(*this);+ auto animation_pass_viewport_mapping = Painting::viewport_mapping(*this);paint_state().begin_compositor_animation_update();GC::RootHashMap<GC::Ref<Layout::Node>, bool> previous_content_retention;GC::RootHashTable<GC::Ref<Layout::Node>> retained_this_pass;@@ -9370,13 +9352,13 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)return false;};- auto transform_subtree_is_clipped_outside = [this, &visual_context_tree, &read](Element const& animated_target, CSSPixelRect const& root_bounds) {+ auto transform_subtree_is_clipped_outside = [&animation_pass_viewport_mapping, &read](Element const& animated_target, CSSPixelRect const& root_bounds) {auto const* layout_node = animated_target.unsafe_layout_node(read);if (!layout_node)return false;return Layout::RustFFI::layout_script_transform_subtree_is_clipped_outside(layout_node->document_host(), Layout::Node::slot_id(layout_node), root_bounds,- Painting::viewport_mapping(*this, *visual_context_tree));+ animation_pass_viewport_mapping);};auto paint_only_effect_is_offscreen = [&](Animations::KeyframeEffect const& effect, AbstractElement abstract_target) {@@ -9477,7 +9459,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)return false;auto viewport_bounds = CSSPixelRect { { 0, 0 }, viewport_rect().size() };- auto viewport_mapping = Painting::viewport_mapping(*this, *visual_context_tree);+ auto const& viewport_mapping = animation_pass_viewport_mapping;auto bounds_in_viewport = [&](Layout::Node const& node) -> CSSPixelRect {CSSPixelRect rect;Layout::RustFFI::layout_script_bounding_client_rect(@@ -9710,7 +9692,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)});}if (forced_opacity_effects_layer)- visual_context_tree = paint_state().visual_context_tree(*this);+ animation_pass_viewport_mapping = Painting::viewport_mapping(*this);bool has_observation_relevant_compositor_animation = false;bool requested_withdrawn_effect_sample = false;@@ -9976,9 +9958,6 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);}- // Publishing gives the animations to the tree in place unless something else still holds it.- visual_context_tree.clear();-// A descriptor must target the tree it is published with. The selection pass above can force// or release animation-only visual context nodes, so redo it after applying those updates.if (Layout::RustFFI::document_host_visual_contexts_need_update(layout_node_arena().host())) {@@ -12695,8 +12674,7 @@ Utf16String Document::dump_display_list()if (!display_list)return "No display list"_utf16;- auto visual_context_tree = paint_state().visual_context_tree(*this);- return Painting::serialize_painting_dump(read, *this, visual_context_tree, *display_list, resource_storage);+ return Painting::serialize_painting_dump(read, *this, *display_list, resource_storage);}Utf16String Document::dump_stacking_context_tree()diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 7c0e8e971b6..94a594f5dfb 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -693,7 +693,6 @@ public:Painting::DocumentPaintState const& paint_state() const;// Whether the last layout committed a box whose `content-visibility` is `auto`.bool has_boxes_with_auto_content_visibility() const;- Compositing::AccumulatedVisualContextTree visual_context_tree() const;PaintTiming::DocumentPaintTimingState& paint_timing_state() { return m_paint_timing_state; }diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 64f6dcd9020..0760b78ed57 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -2721,15 +2721,20 @@ CSSPixelRect Element::bounding_client_rect_assuming_layout_clean() constLayout::ForcedReadScope read { document() };if (!document().navigable())return {};- return bounding_client_rect_assuming_layout_clean(read, document().visual_context_tree());+ auto viewport_mapping = Painting::viewport_mapping(document());+ auto const* layout_node = principal_layout_node(read);+ if (!layout_node)+ return {};+ return Painting::bounding_client_rect(*layout_node, viewport_mapping);}-CSSPixelRect Element::bounding_client_rect_assuming_layout_clean(Layout::BegunRead const& read, Compositing::AccumulatedVisualContextTree const& visual_context_tree) const+CSSPixelRect Element::bounding_client_rect_assuming_layout_clean(Layout::BegunRead const& read, MonotonicTime visual_animation_sample_time) const{+ auto viewport_mapping = Painting::viewport_mapping_with_visual_animations_sampled_at(document(), visual_animation_sample_time);auto const* layout_node = principal_layout_node(read);if (!layout_node)return {};- return Painting::bounding_client_rect(*layout_node, Painting::viewport_mapping(document(), visual_context_tree));+ return Painting::bounding_client_rect(*layout_node, viewport_mapping);}int Element::client_top() constdiff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.hindex f4394a8f0b8..b63bb11ff21 100644--- a/Libraries/LibWeb/DOM/Element.h+++ b/Libraries/LibWeb/DOM/Element.h@@ -11,6 +11,7 @@#include <AK/Concepts.h>#include <AK/Error.h>#include <AK/Optional.h>+#include <AK/Time.h>#include <AK/Utf16String.h>#include <LibGC/RootVector.h>#include <LibGfx/DecodedImageFrame.h>@@ -698,7 +699,8 @@ public:[[nodiscard]] Vector<CSSPixelRect> get_client_rects() const;[[nodiscard]] CSSPixelRect bounding_client_rect_assuming_layout_clean() const;- [[nodiscard]] CSSPixelRect bounding_client_rect_assuming_layout_clean(Layout::BegunRead const& read, Compositing::AccumulatedVisualContextTree const&) const;+ // The same, with the compositor's animations sampled at the time, as the screen shows them then.+ [[nodiscard]] CSSPixelRect bounding_client_rect_assuming_layout_clean(Layout::BegunRead const& read, MonotonicTime visual_animation_sample_time) const;// Which principal box this element asks for, before its computed style has a say.virtual CSS::ElementBoxKind box_kind() const;diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cppindex 559d6cfc371..3b1336caa13 100644--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp@@ -346,7 +346,7 @@ GC::Ref<DOM::Node> IntersectionObserver::intersection_root_node() const}// https://www.w3.org/TR/intersection-observer/#intersectionobserver-root-intersection-rectangle-CSSPixelRect IntersectionObserver::root_intersection_rectangle(Layout::BegunRead const& read, Compositing::AccumulatedVisualContextTree const* visual_context_tree) const+CSSPixelRect IntersectionObserver::root_intersection_rectangle(Layout::BegunRead const& read, Optional<MonotonicTime> visual_animation_sample_time) const{// If the IntersectionObserver is an implicit root observer,// it’s treated as if the root were the top-level browsing context’s document, according to the following rule for document.@@ -387,8 +387,8 @@ CSSPixelRect IntersectionObserver::root_intersection_rectangle(Layout::BegunRead// Otherwise,// it’s the result of getting the bounding box for the intersection root.- rect = visual_context_tree- ? element->bounding_client_rect_assuming_layout_clean(read, *visual_context_tree)+ rect = visual_animation_sample_time.has_value()+ ? element->bounding_client_rect_assuming_layout_clean(read, *visual_animation_sample_time): element->bounding_client_rect_assuming_layout_clean();if (auto const* layout_node = element->layout_node(read); layout_node && Painting::has_committed_box(*layout_node))intersection_root_is_scrollable = layout_node->is_scroll_container();diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.h b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.hindex 31b1fdb6ba7..a03e1036523 100644--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.h+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.h@@ -7,6 +7,7 @@#pragma once#include <AK/Optional.h>+#include <AK/Time.h>#include <AK/Variant.h>#include <LibJS/Forward.h>#include <LibWeb/Bindings/IntersectionObserver.h>@@ -60,7 +61,8 @@ public:Variant<GC::Ref<DOM::Element>, GC::Ref<DOM::Document>> intersection_root() const;GC::Ref<DOM::Node> intersection_root_node() const;bool is_implicit_root() const { return !m_root; }- CSSPixelRect root_intersection_rectangle(Layout::BegunRead const& read, Compositing::AccumulatedVisualContextTree const* = nullptr) const;+ // An element root's box is mapped with the compositor's animations sampled at the time, where one is given.+ CSSPixelRect root_intersection_rectangle(Layout::BegunRead const& read, Optional<MonotonicTime> visual_animation_sample_time = {}) const;void queue_entry(Badge<DOM::Document>, GC::Ref<IntersectionObserverEntry>);diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cppindex abbd020f843..4a91c94ba02 100644--- a/Libraries/LibWeb/Painting/BoxViews.cpp+++ b/Libraries/LibWeb/Painting/BoxViews.cpp@@ -498,20 +498,19 @@ Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const& docume{if (!document.has_committed_viewport_box())return {};- // NB: The document's tree outlives the handle made here: the render state holds it, and so does the scroll state,- // whose world transforms retain the tree they were built from.- return viewport_mapping(document, document.visual_context_tree());+ return document.paint_state().viewport_mapping(document, {}, document.page().client().device_pixels_per_css_pixel());}-Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const& document, Compositing::AccumulatedVisualContextTree const& visual_context_tree)+Layout::RustFFI::FfiViewportMapping viewport_mapping_with_visual_animations_sampled_at(DOM::Document const& document, MonotonicTime sample_time){if (!document.has_committed_viewport_box())return {};- return document.paint_state().viewport_mapping(visual_context_tree, document.page().client().device_pixels_per_css_pixel());+ return document.paint_state().viewport_mapping(document, sample_time, document.page().client().device_pixels_per_css_pixel());}-// NB: Taking the document's visual context tree brings it up to date, which can compact it and move a box's visual-// context to other nodes. The functions below read a box's visual context only once they have the tree.+// NB: Making a viewport mapping brings the document's visual context tree up to date, which can compact it and move a+// box's visual context to other nodes. The functions below read a box's visual context only once they have the+// mapping.CSSPixelRect rect_to_viewport(Layout::Node const& node, CSSPixelRect const& rect, Layout::RustFFI::ViewportSpace space){if (!has_committed_box(node))@@ -554,8 +553,7 @@ CSSPixelPoint presented_scroll_offset(Layout::Node const& node, CSSPixelPoint scauto 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))+ if (!document.paint_state().translations_snap_to_device_pixels(document, committed_row_slot(node)))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); };diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.hindex f4c175e1b43..eb7efb68e6a 100644--- a/Libraries/LibWeb/Painting/BoxViews.h+++ b/Libraries/LibWeb/Painting/BoxViews.h@@ -6,7 +6,8 @@#pragma once-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>+#include <AK/Time.h>+#include <LibCompositing/DisplayList/ContextRef.h>#include <LibGC/Ptr.h>#include <LibGfx/AffineTransform.h>#include <LibGfx/Forward.h>@@ -61,10 +62,11 @@ WEB_API bool is_viewport_paintable(Layout::Node const&);WEB_API bool is_paintable_with_lines(Layout::Node const&);// What maps the CSS-pixel geometry of the document's boxes to and from its viewport: the document's visual context tree,-// brought up to date unless given, under its scroll offsets. It is lent until either changes, and a document without a+// brought up to date, under its scroll offsets, as the host has them where the mapping is used. A document without a// committed viewport box maps nothing.WEB_API Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const&);-WEB_API Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const&, Compositing::AccumulatedVisualContextTree const&);+// The same, with the compositor's animations sampled at the time, as the screen shows them then.+WEB_API Layout::RustFFI::FfiViewportMapping viewport_mapping_with_visual_animations_sampled_at(DOM::Document const&, MonotonicTime);WEB_API CSSPixelRect rect_to_viewport(Layout::Node const&, CSSPixelRect const&, Layout::RustFFI::ViewportSpace);// The part of a rect in the viewport that the content clips of the box's containing blocks leave.WEB_API CSSPixelRect visible_rect_in_containing_blocks(Layout::Node const&, CSSPixelRect const&, Layout::RustFFI::ViewportSpace);diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.cpp b/Libraries/LibWeb/Painting/DocumentPaintState.cppindex b86006a00c2..b7e166bde8b 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.cpp+++ b/Libraries/LibWeb/Painting/DocumentPaintState.cpp@@ -116,13 +116,21 @@ void DocumentPaintState::append_paint_command_cache_source_resources(Compositingretained_resources.include(m_paint_command_cache_source_referenced_resources);}-Layout::RustFFI::FfiViewportMapping DocumentPaintState::viewport_mapping(Compositing::AccumulatedVisualContextTree const& visual_context_tree, double device_pixels_per_css_pixel) const+Layout::RustFFI::FfiViewportMapping DocumentPaintState::viewport_mapping(DOM::Document const& document, Optional<MonotonicTime> visual_animation_sample_time, double device_pixels_per_css_pixel) const{+ Layout::ForcedReadScope read { document };Layout::RustFFI::FfiViewportMapping mapping {};- Layout::RustFFI::render_state_viewport_mapping(m_layout_node_arena->host(), visual_context_tree.rust_handle(), static_cast<float>(device_pixels_per_css_pixel), &mapping);+ auto sample_time_ns = visual_animation_sample_time.map([](auto time) { return time.nanoseconds(); });+ Layout::RustFFI::render_state_viewport_mapping(m_layout_node_arena->host(), read, sample_time_ns.has_value(), sample_time_ns.value_or(0), static_cast<float>(device_pixels_per_css_pixel), &mapping);return mapping;}+bool DocumentPaintState::translations_snap_to_device_pixels(DOM::Document const& document, Compositing::RustFFI::NodeSlotId box) const+{+ Layout::ForcedReadScope read { document };+ return Layout::RustFFI::render_state_translations_snap_to_device_pixels(m_layout_node_arena->host(), read, box);+}+ByteBuffer DocumentPaintState::encoded_scroll_state() const{ByteBuffer bytes;diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.h b/Libraries/LibWeb/Painting/DocumentPaintState.hindex b6b4eb6252c..8aa3c7763c0 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.h+++ b/Libraries/LibWeb/Painting/DocumentPaintState.h@@ -9,6 +9,7 @@#include <AK/ByteBuffer.h>#include <AK/Optional.h>#include <AK/RefPtr.h>+#include <AK/Time.h>#include <AK/Vector.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>@@ -35,8 +36,13 @@ public:BlockingWheelEventRegionState collect_root_blocking_wheel_event_regions(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;+ // The mapping through the document's visual context tree, brought up to date, with the compositor's animations+ // sampled at the time where one is given. It reads the scroll state, and the tree the host keeps for its mappings,+ // where it is used.+ Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const&, Optional<MonotonicTime> visual_animation_sample_time, double device_pixels_per_css_pixel) const;+ // Whether the scroll translations of the space the box is painted in, and the origins drawn in it, round to whole+ // device pixels: no transform but identities lies above it in the visual context tree, brought up to date.+ bool translations_snap_to_device_pixels(DOM::Document const&, Compositing::RustFFI::NodeSlotId box) const;// Only the scroll logic of the compositor, which is Rust, decodes it.ByteBuffer encoded_scroll_state() const;void did_update_visual_context_values();diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex 6476ed596cb..7aa01a383a1 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -252,7 +252,7 @@ static void push_debug_description(DOM::Document const& document, Compositing::RLayout::RustFFI::layout_arena_paint_push_bytes(description_sink, bytes.data(), bytes.size());}-Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document const& document, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::DisplayList const& display_list, Compositing::DisplayListResourceStorage const& resource_storage)+Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document const& document, Compositing::DisplayList const& display_list, Compositing::DisplayListResourceStorage const& resource_storage){struct DumpContext {GC::Ref<DOM::Document const> document;@@ -270,7 +270,7 @@ Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document.append_text = [](void* context_pointer, u8 const* bytes, size_t byte_count) { static_cast<DumpContext*>(context_pointer)->dump = Utf16String::from_utf8_without_validation(StringView { bytes, byte_count }); },};Gfx::IntRect device_viewport_rect { {}, document.page().css_to_device_rect(document.viewport_rect()).size().to_type<int>() };- Layout::RustFFI::painting_dump(document_host(document), &read, viewport_row_slot(read, document), visual_context_tree.rust_handle(), display_list.rust_handle(), device_viewport_rect, callbacks);+ Layout::RustFFI::painting_dump(document_host(document), &read, viewport_row_slot(read, document), display_list.rust_handle(), device_viewport_rect, callbacks);return move(context.dump);}diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.h b/Libraries/LibWeb/Painting/PaintingRustBridge.hindex 4958d64ef7c..df565ba4cc3 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.h+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.h@@ -81,7 +81,7 @@ WEB_API NonnullRefPtr<Compositing::DisplayList> display_list_of_published_record// visual context tree that recording was recorded against. A recording that repeats the list it published before// publishes that list again, which holds the tree of the recording before.WEB_API NonnullRefPtr<Compositing::DisplayList> nestable_display_list_of_last_recording(Layout::BegunRead const&, DOM::Document const&, NonnullRefPtr<Compositing::DisplayList> published);-WEB_API Utf16String serialize_painting_dump(Layout::BegunRead const&, DOM::Document const&, Compositing::AccumulatedVisualContextTree const&, Compositing::DisplayList const&, Compositing::DisplayListResourceStorage const&);+WEB_API Utf16String serialize_painting_dump(Layout::BegunRead const&, DOM::Document const&, Compositing::DisplayList const&, Compositing::DisplayListResourceStorage const&);WEB_API Compositing::DisplayListResource record_image_paint_display_list(ImagePaint const&, ImagePaintRequest const&, double device_pixels_per_css_pixel);// Records one image frame drawn into the destination rectangle, in device pixels.diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rsindex 0878e284598..c5c4f83e8cd 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs@@ -176,16 +176,18 @@ pub unsafe extern "C" fn render_state_dump_compositor_animations(/// # Safety///-/// `host` must be a live document host, on its document's thread, and `visual_context_tree` a live retained tree-/// handle built from its render state; `display_list` is the storage handle of the display list, and it and every-/// storage handle `callbacks` returns must remain live for this call. `debug_description` is called synchronously-/// with a `Vec<u8>` sink the host fills through `layout_arena_paint_push_bytes`.+/// Dumps `display_list` with the nodes it names of the visual context tree of `host`'s document, prepared up to date.+///+/// # Safety+///+/// `host` must be a live document host, on its document's thread; `display_list` is the storage handle of the display+/// list, and it and every storage handle `callbacks` returns must remain live for this call. `debug_description` is+/// called synchronously with a `Vec<u8>` sink the host fills through `layout_arena_paint_push_bytes`.#[unsafe(no_mangle)]pub unsafe extern "C" fn painting_dump(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,viewport: NodeSlotId,- visual_context_tree: *const c_void,display_list: *const c_void,device_viewport_rect: IntRect,callbacks: FfiPaintingDumpCallbacks,@@ -193,7 +195,10 @@ pub unsafe extern "C" fn painting_dump(assert!(!display_list.is_null());// SAFETY: Guaranteed by the entry point's contract.let main_thread = unsafe { main_thread(host) };- let visual_context_tree = unsafe { libcompositing_rust::ffi::tree_from_handle(visual_context_tree) };+ // SAFETY: As above.+ let visual_context_tree = unsafe { crate::painting::ffi::main_visual_context_tree(host, read) }+ .expect("a document with a committed viewport box has a visual context tree");+ let visual_context_tree = visual_context_tree.as_ref();let (tape, command_runs) = unsafe { libcompositing_rust::display_list::storage::tape_of(display_list) };let owners = {crate::painting::ffi::read_arena(host, read, viewport, |arena, viewport| {diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 437b25bdc6b..7932109be69 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -27,7 +27,7 @@ use std::ffi::c_void;mod main_thread_entries;-pub(crate) use main_thread_entries::MainThreadFfiEntry;+pub(crate) use main_thread_entries::{MainThreadFfiEntry, main_visual_context_tree};crate::render_state::held_node_entries!();diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex b4a866b409d..a46f125bc61 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -414,31 +414,65 @@ pub unsafe extern "C" fn render_state_publish_compositor_animations(outcome}-/// The visual context tree of `host`'s document, prepared up to date, retained for the caller.+/// The visual context tree of `host`'s document, prepared up to date.////// # Safety////// `host` must be a live document host, on its document's thread.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn render_state_main_visual_context_tree_retain(+pub(crate) unsafe fn main_visual_context_tree(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,-) -> *const c_void {- fn retain(tree: Option<&std::sync::Arc<crate::painting::visual_context::VisualContextTree>>) -> *const c_void {- tree.map_or(std::ptr::null(), |tree| {- std::sync::Arc::into_raw(std::sync::Arc::clone(tree)).cast()- })- }+) -> Option<std::sync::Arc<crate::painting::visual_context::VisualContextTree>> {// SAFETY: Guaranteed by the caller.unsafe { prepare_paint_properties(host, read) };- if let Some(tree) = host.read_known_rows(|rows, _| retain(rows.visual_context_tree.as_ref())) {+ if let Some(tree) = host.read_known_rows(|rows, _| rows.visual_context_tree.clone()) {return tree;}read_arena(host, read, (), |arena, ()| {- retain(arena.paint_state().visual_context.tree.as_ref())+ arena.paint_state().visual_context.tree.clone()})}+/// The visual context tree of `host`'s document, prepared up to date, retained for the caller.+///+/// # Safety+///+/// `host` must be a live document host, on its document's thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_main_visual_context_tree_retain(+ host: &crate::render_state::DocumentHost,+ read: &crate::render_state::BegunRead,+) -> *const c_void {+ // SAFETY: Guaranteed by the caller.+ unsafe { main_visual_context_tree(host, read) }+ .map_or(std::ptr::null(), |tree| std::sync::Arc::into_raw(tree).cast())+}++/// Whether the scroll translations of the space `slot`'s box is painted in, in the visual context tree of `host`'s+/// document, prepared up to date, and the origins drawn in that space round to whole device pixels: no transform but+/// identities lies above it.+///+/// # Safety+///+/// `host` must be a live document host, on its document's thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_translations_snap_to_device_pixels(+ host: &crate::render_state::DocumentHost,+ read: &crate::render_state::BegunRead,+ slot: NodeSlotId,+) -> bool {+ // NB: Preparing the tree can move the box's visual context to other nodes, so the box's space is read after.+ // SAFETY: Guaranteed by the caller.+ let Some(tree) = (unsafe { main_visual_context_tree(host, read) }) else {+ return false;+ };+ let spatial = host.read_rows(node_read(), false, |rows| {+ rows.paintable_row_is_populated(slot)+ .then(|| rows.paintable_data(slot).accumulated_visual_context.spatial)+ });+ spatial.is_some_and(|spatial| tree.translations_snap_to_device_pixels(spatial))+}+/// The structural epoch of the visual context tree of `host`'s document, prepared up to date.////// # Safetydiff --git a/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs b/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rsindex b3162c3b167..d6b83865b4b 100644--- a/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs+++ b/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs@@ -18,10 +18,8 @@ use crate::painting::visual_context::{};use crate::painting::visual_context::{basic_shapes, node_values};use crate::render_state::DocumentHost;-use libcompositing_rust::ffi::tree_sharing_handle;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot};use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect};-use std::ffi::c_void;use std::rc::Rc;use std::sync::Arc;@@ -289,25 +287,71 @@ impl<'a> ViewportMapping<'a> {}}+/// The visual context trees the viewport mappings of a document map through, which its host keeps for them: C++ carries+/// mappings, never trees.+#[derive(Default)]+pub(crate) struct ViewportMappingTrees {+ /// The document's tree as it was prepared for the newest mapping.+ main: Option<Arc<VisualContextTree>>,+ /// The main tree with the compositor's animations sampled at a time, for the mappings that read them so.+ sampled: Option<(i64, Arc<VisualContextTree>)>,+}++impl ViewportMappingTrees {+ fn set_main(&mut self, tree: Arc<VisualContextTree>) {+ if !self.main.as_ref().is_some_and(|main| Arc::ptr_eq(main, &tree)) {+ self.sampled = None;+ }+ self.main = Some(tree);+ }++ /// The main tree, with the compositor's animations sampled at `visual_animation_sample_time_ns` where it is some.+ fn tree(&mut self, visual_animation_sample_time_ns: Option<i64>) -> Option<Arc<VisualContextTree>> {+ let main = self.main.clone()?;+ let Some(sample_time_ns) = visual_animation_sample_time_ns.filter(|_| main.has_visual_animations()) else {+ return Some(main);+ };+ if let Some((sampled_at, sampled)) = &self.sampled+ && *sampled_at == sample_time_ns+ {+ return Some(sampled.clone());+ }+ let sampled = Arc::new(main.with_visual_animation_samples(sample_time_ns));+ self.sampled = Some((sample_time_ns, sampled.clone()));+ Some(sampled)+ }+}+/// A [`ViewportMapping`] as C++ carries it for `'a`, which only [`render_state_viewport_mapping`] makes: C++ hands it-/// back as it got it, or one it left zeroed, which leaves geometry as it is. `visual_context_tree` is a tree handle-/// that stays live for `'a`. Where the document is scrolled to, and the world transforms of the tree there, are read-/// from `host` where the mapping is used.+/// back as it got it, or one it left zeroed, which leaves geometry as it is. Where the document is scrolled to, the+/// tree the host keeps for its mappings, and the world transforms of that tree there, are read from `host` where the+/// mapping is used.#[repr(C)]pub struct FfiViewportMapping<'a> {host: Option<&'a DocumentHost>,- visual_context_tree: *const c_void,device_pixels_per_css_pixel: f32,+ samples_visual_animations: bool,+ visual_animation_sample_time_ns: i64,}impl FfiViewportMapping<'_> {+ fn visual_animation_sample_time_ns(&self) -> Option<i64> {+ self.samples_visual_animations+ .then_some(self.visual_animation_sample_time_ns)+ }+/// What the mapping maps through as the host has it now, kept for as long as an entry point reads the mapping.pub(crate) fn resolve(&self) -> ResolvedViewportMapping {- let Some(host) = self.host.filter(|_| !self.visual_context_tree.is_null()) else {+ let Some(host) = self.host else {+ return ResolvedViewportMapping { transforms: None };+ };+ let Some(tree) = host+ .viewport_mapping_trees()+ .tree(self.visual_animation_sample_time_ns())+ else {return ResolvedViewportMapping { transforms: None };};- // SAFETY: C++ keeps the tree live for as long as it carries the mapping.- let tree = unsafe { tree_sharing_handle(self.visual_context_tree) };+ let tree = AccumulatedVisualContextTree::from_arc(tree);let scroll_state = host.scroll_state();let world_transforms = scroll_state.world_transforms(&tree);ResolvedViewportMapping {@@ -348,29 +392,59 @@ impl ResolvedViewportMapping {}}-/// The mapping between the viewport of `host`'s document and the spaces of `visual_context_tree`, where the document's-/// boxes are scrolled to as the host has it when the mapping is used.+/// The mapping between the viewport of `host`'s document and the spaces of `tree`, which the host keeps as the tree of+/// its mappings from here on, with the compositor's animations sampled at `visual_animation_sample_time_ns` where it is+/// some, where the document's boxes are scrolled to as the host has it when the mapping is used.+fn viewport_mapping_through(+ host: &DocumentHost,+ tree: Arc<VisualContextTree>,+ visual_animation_sample_time_ns: Option<i64>,+ device_pixels_per_css_pixel: f32,+) -> FfiViewportMapping<'_> {+ let mapped_tree = {+ let mut trees = host.viewport_mapping_trees();+ trees.set_main(tree);+ trees.tree(visual_animation_sample_time_ns)+ };+ if let Some(mapped_tree) = mapped_tree {+ host.scroll_state()+ .world_transforms(&AccumulatedVisualContextTree::from_arc(mapped_tree));+ }+ FfiViewportMapping {+ host: Some(host),+ device_pixels_per_css_pixel,+ samples_visual_animations: visual_animation_sample_time_ns.is_some(),+ visual_animation_sample_time_ns: visual_animation_sample_time_ns.unwrap_or_default(),+ }+}++/// The mapping between the viewport of `host`'s document and the spaces of its visual context tree, prepared up to date,+/// with the compositor's animations sampled at `visual_animation_sample_time_ns` where `samples_visual_animations` says+/// so, where the document's boxes are scrolled to as the host has it when the mapping is used. A document without a+/// tree leaves the mapping zeroed.////// # Safety///-/// `visual_context_tree` must be a live retained tree handle, which stays live for as long as C++ carries the mapping:-/// the caller keeps it, or it is the document's own, which the scroll state retains from here on, with the world-/// transforms it builds for it, until the host refreshes the scroll state or builds those of another tree.+/// `host` must be a live document host, on its document's thread.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_viewport_mapping<'a>(host: &'a DocumentHost,- visual_context_tree: *const c_void,+ read: &crate::render_state::BegunRead,+ samples_visual_animations: bool,+ visual_animation_sample_time_ns: i64,device_pixels_per_css_pixel: f32,out: &mut FfiViewportMapping<'a>,) {- // SAFETY: The caller lends a strong reference to the tree.- let tree = unsafe { tree_sharing_handle(visual_context_tree) };- host.scroll_state().world_transforms(&tree);- *out = FfiViewportMapping {- host: Some(host),- visual_context_tree,- device_pixels_per_css_pixel,+ // SAFETY: Guaranteed by the caller.+ let Some(tree) = (unsafe { crate::painting::ffi::main_visual_context_tree(host, read) }) else {+ return;};+ *out = viewport_mapping_through(+ host,+ tree,+ samples_visual_animations.then_some(visual_animation_sample_time_ns),+ device_pixels_per_css_pixel,+ );}/// The matrix that takes the local space of `spatial` into the viewport, both in device pixels.@@ -454,16 +528,7 @@ mod tests {let (tree, scroller) = tree_with_scroller();let (other_tree, _) = tree_with_scroller();let scrolled_to = |y: f32| vec![FloatPoint::default(), FloatPoint { x: 0.0, y }];- let mapping_over = |tree: &Arc<VisualContextTree>| {- let mut mapping = FfiViewportMapping {- host: None,- visual_context_tree: std::ptr::null(),- device_pixels_per_css_pixel: 0.0,- };- // SAFETY: The test keeps the tree for as long as it uses the mapping.- unsafe { render_state_viewport_mapping(&host, Arc::as_ptr(tree).cast(), 1.0, &mut mapping) };- mapping- };+ let mapping_over = |tree: &Arc<VisualContextTree>| viewport_mapping_through(&host, tree.clone(), None, 1.0);let ten = CssPixels::from_integer(10);let rect = CssPixelRect::new(CssPixels::default(), CssPixels::default(), ten, ten);let top_in_viewport = |mapping: &FfiViewportMapping<'_>| {diff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rsindex c792f92c2f3..705c14156ac 100644--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs@@ -84,6 +84,8 @@ pub struct DocumentHost {/// Where the document's boxes are scrolled to, as the host refreshed it last: what its queries map through, and its/// frames take to the compositor. It is handed out by reference count, as the rows are.scroll_state: RefCell<Rc<ScrollStateSnapshot>>,+ /// The visual context trees the viewport mappings the host hands C++ map through.+ viewport_mapping_trees: RefCell<crate::painting::viewport_mapping::ViewportMappingTrees>,/// What the host's scopes of a read lend the entries they call.begun_read: BegunRead,/// The writes the host queued that the render state has not applied yet, in the order the host made them.@@ -208,6 +210,7 @@ impl DocumentHost {absolute_rects: RefCell::default(),compositor_animations: RefCell::default(),scroll_state: RefCell::default(),+ viewport_mapping_trees: RefCell::default(),begun_read: BegunRead::of_host(),changes: ChangeQueue::default(),flown_style: RefCell::default(),@@ -1537,6 +1540,11 @@ impl DocumentHost {self.scroll_state.borrow().clone()}+ /// The visual context trees the viewport mappings the host hands C++ map through.+ pub(crate) fn viewport_mapping_trees(&self) -> RefMut<'_, crate::painting::viewport_mapping::ViewportMappingTrees> {+ self.viewport_mapping_trees.borrow_mut()+ }+/// Takes `device_offsets`, the offsets the render state refreshed, as the document's scroll state.pub(crate) fn refresh_scroll_state(&self, device_offsets: Vec<FloatPoint>) {self.scroll_statediff --git a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Libraries/LibWeb/SVG/SVGGraphicsElement.cppindex 50dddeac092..0c9ca574dcb 100644--- a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp+++ b/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp@@ -297,7 +297,7 @@ GC::Ptr<Geometry::DOMMatrix> SVGGraphicsElement::get_screen_ctm()// NB: An SVG viewport's current user coordinate system is the space produced by its viewBox transform, which is the// coordinate system recorded for its descendants. Other graphics elements use their own accumulated context so// their transform property is included exactly once.- auto visual_context_tree = document().visual_context_tree();+ auto viewport_mapping = Painting::viewport_mapping(document());if (!Painting::has_accumulated_visual_context(*layout_node))return {};@@ -305,7 +305,7 @@ GC::Ptr<Geometry::DOMMatrix> SVGGraphicsElement::get_screen_ctm()? Painting::accumulated_visual_context_for_descendants(*layout_node): Painting::accumulated_visual_context(*layout_node);Gfx::FloatMatrix4x4 ctm;- Layout::RustFFI::viewport_mapping_matrix_to_viewport(Painting::viewport_mapping(document(), visual_context_tree), visual_context.spatial, Layout::RustFFI::ViewportSpace::LayoutViewport, &ctm);+ Layout::RustFFI::viewport_mapping_matrix_to_viewport(viewport_mapping, visual_context.spatial, Layout::RustFFI::ViewportSpace::LayoutViewport, &ctm);// NB: Accumulated visual-context matrices operate in device-pixel space. Conjugate the matrix by the device scale// to expose CSS-pixel coordinates through the DOM API, then project any 3D transform onto the SVG plane.