Truly independent web browser
LibWeb: Hit test points by walking paint order over rows
Aliaksandr Kalenikd13a9befe522
diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp b/Libraries/LibWeb/Painting/HitTestDisplayList.cppindex d06b63b1141..55cae4a043e 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp@@ -19,26 +19,8 @@ namespace Web::Painting {NonnullRefPtr<HitTestDisplayList> HitTestDisplayList::create_from_rust_recording(Layout::BegunRead const& read, u64 visual_context_tree_structural_epoch, Layout::NodeArena& arena, ChromeWidgetRegistry& chrome_widget_registry){- auto list = adopt_ref(*new HitTestDisplayList(visual_context_tree_structural_epoch, arena, chrome_widget_registry, Layout::RustFFI::layout_hit_test_list_generation(arena.host())));- struct VisitContext {- Layout::NodeArena& arena;- ChromeWidgetRegistry& chrome_widget_registry;- };- VisitContext visit_context { arena, chrome_widget_registry };- Layout::RustFFI::layout_hit_test_visit_chrome_widgets(arena.host(), &read, &visit_context,- [](void* sink, Compositing::RustFFI::NodeSlotId paintable, u8 chrome_widget_kind) {- auto& context = *static_cast<VisitContext*>(sink);- switch (static_cast<ChromeWidgetKind>(chrome_widget_kind)) {- case ChromeWidgetKind::None:- case ChromeWidgetKind::HorizontalScrollbar:- case ChromeWidgetKind::VerticalScrollbar:- break;- case ChromeWidgetKind::ResizeHandle:- (void)context.chrome_widget_registry.get_or_create_resize_handle(context.arena, paintable);- break;- }- });- return list;+ (void)read;+ return adopt_ref(*new HitTestDisplayList(visual_context_tree_structural_epoch, arena, chrome_widget_registry, Layout::RustFFI::layout_hit_test_list_generation(arena.host())));}HitTestDisplayList::HitTestDisplayList(u64 visual_context_tree_structural_epoch, Layout::NodeArena& arena, ChromeWidgetRegistry& chrome_widget_registry, u64 rust_generation)@@ -54,13 +36,6 @@ bool HitTestDisplayList::is_current() constreturn m_rust_generation != 0 && Layout::RustFFI::layout_hit_test_list_generation(m_arena->host()) == m_rust_generation;}-HitTestDisplayList::Item HitTestDisplayList::item(Layout::BegunRead const& read, size_t index) const-{- Layout::RustFFI::FfiHitTestItemExport facts;- Layout::RustFFI::layout_hit_test_item_facts(m_arena->host(), &read, index, &facts);- return { index, facts };-}-static Layout::RustFFI::FfiHitTestQuery ffi_query(HitTestQuery const& query){return {@@ -71,41 +46,6 @@ static Layout::RustFFI::FfiHitTestQuery ffi_query(HitTestQuery const& query)};}-Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Layout::RustFFI::FfiTopmostItem const& item)-{- if (!item.has_item)- return {};- return TopmostItem { item.index, item.local };-}--Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::find_topmost_item(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const-{- Layout::RustFFI::FfiTopmostItem item;- Layout::RustFFI::layout_hit_test_find_topmost_item(m_arena->host(), &read, ffi_query(query), point, &item);- return topmost_item_from(item);-}--Vector<HitTestDisplayList::TopmostItem> HitTestDisplayList::hit_items_topmost_first(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const-{- Vector<TopmostItem> hits;- Layout::RustFFI::layout_hit_test_all(m_arena->host(), &read, ffi_query(query), point, &hits, [](void* sink, size_t index, CSSPixelPoint local_point) {- static_cast<Vector<TopmostItem>*>(sink)->append({ index, local_point });- });- return hits;-}--Layout::Node const* HitTestDisplayList::layout_node_for_item(Layout::BegunRead const& read, Item item) const-{- return layout_node_for_committed_slot(read, *m_arena, item.paintable());-}--RefPtr<ChromeWidget> HitTestDisplayList::chrome_widget_for_item(Item item) const-{- if (item.chrome_widget_kind() == ChromeWidgetKind::ResizeHandle)- return m_chrome_widget_registry->resize_handle(item.paintable());- return nullptr;-}-// https://html.spec.whatwg.org/multipage/image-maps.html#image-map-processing-model// NB: The image publishes the areas of the map it is associated with onto its row, so the hit names one of them without// asking the DOM for the map or for the areas' attributes.@@ -120,10 +60,11 @@ static DOM::NodeIdentity image_map_area_for_point(Layout::Node const& layout_nodreturn DOM::NodeIdentity::of_style_node(CSS::StyleNodeID { area });}-HitTestResult HitTestDisplayList::hit_test_result_for_item(Layout::BegunRead const& read, Item item, CSSPixelPoint local_point) const+HitTestResult HitTestDisplayList::hit_test_result_for(Layout::BegunRead const& read, Layout::RustFFI::FfiPointHit const& hit) const{- auto const* paintable_layout_node = layout_node_for_item(read, item);- auto hit_node = item.hit_node();+ CSSPixelPoint local_point = hit.local;+ auto const* paintable_layout_node = layout_node_for_committed_slot(read, *m_arena, hit.paintable);+ auto hit_node = hit.hit_node;auto const* named_layout_node = layout_node_for_committed_slot(read, *m_arena, hit_node);VERIFY(named_layout_node && as<Layout::NodeWithStyle>(*named_layout_node).pointer_events() != CSS::PointerEvents::None);@@ -145,7 +86,7 @@ HitTestResult HitTestDisplayList::hit_test_result_for_item(Layout::BegunRead con}}- auto resolved = Layout::RustFFI::layout_hit_test_resolve_hit(m_arena->host(), &read, item.index(), local_point);+ auto const& resolved = hit.resolved;auto identity = DOM::NodeIdentity::of(root_element.ptr());// NB: Style runs before layout, so a laid-out document's style engine tracks its tree and every connected element// in it has a StyleNodeID.@@ -157,14 +98,17 @@ HitTestResult HitTestDisplayList::hit_test_result_for_item(Layout::BegunRead conif (identity.is_none())identity = node_identity_of(resolved.fallback_dispatch);- // NB: Empty-line items are not reachable through regular hit testing; the descriptor still resolves them for- // callers that already hold such an item.+ auto chrome_widget_kind = static_cast<ChromeWidgetKind>(hit.chrome_widget_kind);+ RefPtr<ChromeWidget> chrome_widget;+ if (chrome_widget_kind == ChromeWidgetKind::ResizeHandle)+ chrome_widget = m_chrome_widget_registry->get_or_create_resize_handle(*m_arena, hit.paintable);+auto result = HitTestResult {.node = identity,.hit_node = hit_node,.arena = *m_arena,- .chrome_widget = chrome_widget_for_item(item),- .is_scrollbar = first_is_one_of(item.chrome_widget_kind(), ChromeWidgetKind::HorizontalScrollbar, ChromeWidgetKind::VerticalScrollbar),+ .chrome_widget = move(chrome_widget),+ .is_scrollbar = first_is_one_of(chrome_widget_kind, ChromeWidgetKind::HorizontalScrollbar, ChromeWidgetKind::VerticalScrollbar),.is_text_fragment = resolved.is_text_fragment,};if (resolved.has_index_in_node)@@ -238,16 +182,20 @@ Optional<CaretPosition> HitTestDisplayList::caret_position_from_point(Layout::BeOptional<HitTestResult> HitTestDisplayList::hit_test(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const{- auto topmost_item = find_topmost_item(read, point, query);- if (!topmost_item.has_value())+ Layout::RustFFI::FfiPointHit hit;+ if (!Layout::RustFFI::layout_hit_test_topmost_hit(m_arena->host(), &read, ffi_query(query), point, &hit))return {};- return hit_test_result_for_item(read, item(read, topmost_item->index), topmost_item->local_point);+ return hit_test_result_for(read, hit);}TraversalDecision HitTestDisplayList::hit_test_all(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query, Function<TraversalDecision(HitTestResult)> const& callback) const{- for (auto hit : hit_items_topmost_first(read, point, query)) {- if (callback(hit_test_result_for_item(read, item(read, hit.index), hit.local_point)) == TraversalDecision::Break)+ Vector<Layout::RustFFI::FfiPointHit> hits;+ Layout::RustFFI::layout_hit_test_all_hits(m_arena->host(), &read, ffi_query(query), point, &hits, [](void* sink, Layout::RustFFI::FfiPointHit const* hit) {+ static_cast<Vector<Layout::RustFFI::FfiPointHit>*>(sink)->append(*hit);+ });+ for (auto const& hit : hits) {+ if (callback(hit_test_result_for(read, hit)) == TraversalDecision::Break)return TraversalDecision::Break;}diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.h b/Libraries/LibWeb/Painting/HitTestDisplayList.hindex 33c7b6af444..9b4588d8423 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.h+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.h@@ -67,31 +67,7 @@ public:private:HitTestDisplayList(u64 visual_context_tree_structural_epoch, Layout::NodeArena&, ChromeWidgetRegistry&, u64 rust_generation);- struct Item {- size_t item_index { 0 };- Layout::RustFFI::FfiHitTestItemExport facts;-- size_t index() const { return item_index; }- Compositing::RustFFI::NodeSlotId paintable() const { return facts.paintable; }- Compositing::RustFFI::NodeSlotId hit_node() const { return facts.hit_node; }- ChromeWidgetKind chrome_widget_kind() const { return static_cast<ChromeWidgetKind>(facts.chrome_widget_kind); }- Compositing::ContextRef context() const { return facts.context; }- };-- struct TopmostItem {- size_t index { 0 };- CSSPixelPoint local_point;- };-- static Optional<TopmostItem> topmost_item_from(Layout::RustFFI::FfiTopmostItem const&);- [[nodiscard]] Item item(Layout::BegunRead const& read, size_t index) const;-- [[nodiscard]] Optional<TopmostItem> find_topmost_item(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&) const;- [[nodiscard]] Vector<TopmostItem> hit_items_topmost_first(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&) const;-- [[nodiscard]] Layout::Node const* layout_node_for_item(Layout::BegunRead const& read, Item) const;- [[nodiscard]] RefPtr<ChromeWidget> chrome_widget_for_item(Item) const;- [[nodiscard]] HitTestResult hit_test_result_for_item(Layout::BegunRead const& read, Item, CSSPixelPoint local_point) const;+ [[nodiscard]] HitTestResult hit_test_result_for(Layout::BegunRead const& read, Layout::RustFFI::FfiPointHit const&) const;[[nodiscard]] Optional<CaretPosition> caret_position_from(Layout::RustFFI::FfiCaretAt const&) const;u64 m_visual_context_tree_structural_epoch { 0 };diff --git a/Libraries/LibWeb/Rust/src/layout/commit.rs b/Libraries/LibWeb/Rust/src/layout/commit.rsindex 686f73a9481..5d1bca23f28 100644--- a/Libraries/LibWeb/Rust/src/layout/commit.rs+++ b/Libraries/LibWeb/Rust/src/layout/commit.rs@@ -834,11 +834,10 @@ impl<'tree> Commit<'_, 'tree> {),];let data = self.arena().live_paintable_data(slot);- let ink_depends_on_later_fragment_placements = crate::painting::ink_overflow::maintenance_enabled()- && (containing_block_fragment != 0- || !later_fragments.is_empty()- || data.has_flag(crate::painting::paintable_data::PaintableFlag::HasLaterBoxFragments)- || data.has_flag(crate::painting::paintable_data::PaintableFlag::InLaterContainingBlockFragment));+ let ink_depends_on_later_fragment_placements = containing_block_fragment != 0+ || !later_fragments.is_empty()+ || data.has_flag(crate::painting::paintable_data::PaintableFlag::HasLaterBoxFragments)+ || data.has_flag(crate::painting::paintable_data::PaintableFlag::InLaterContainingBlockFragment);if flags.iter().any(|&(flag, value)| data.has_flag(flag) != value) {let arena = self.arena_mut();let mut paintable_rows = arena.paintable_rows_mut();diff --git a/Libraries/LibWeb/Rust/src/layout/row_reads.rs b/Libraries/LibWeb/Rust/src/layout/row_reads.rsindex 5be48bdab3e..657483588bc 100644--- a/Libraries/LibWeb/Rust/src/layout/row_reads.rs+++ b/Libraries/LibWeb/Rust/src/layout/row_reads.rs@@ -35,6 +35,8 @@ pub(crate) struct RowSnapshot {image_maps: Arc<ImageMaps>,/// The visual context tree hit testing maps points through.pub(crate) visual_context_tree: Option<Arc<VisualContextTree>>,+ /// The row the document's paint order starts at.+ pub(crate) viewport: NodeSlotId,/// How far the arena's rows had been written when they were published.version: RowsVersion,/// Whether every row's scrollable overflow was measured when the rows were published.@@ -286,6 +288,7 @@ impl LayoutNodeArena {pub(crate) fn publish_row_snapshot(&mut self, settle_overflow: bool) -> RowSnapshot {if settle_overflow {self.settle_scrollable_overflow();+ self.settle_ink_overflow();}let paintable = self.publish_rows();let bound = self.bound_rows_mut().publish();@@ -294,6 +297,7 @@ impl LayoutNodeArena {bound,image_maps: self.image_map_areas().snapshot(),visual_context_tree: self.paint_state().visual_context.tree.clone(),+ viewport: self.layout_root(),version: self.rows_version(),overflow_is_settled: self.scrollable_overflow_is_settled(),text_awaiting_render: self.text_rows_awaiting_sync(),diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex 2bd32cf32bd..f59b1c45090 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -997,15 +997,6 @@ fn with_hit_test_list<R>(query(list, &rows, &source)}-fn with_hit_test_list_items_only<R>(- host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,- default: R,- query: impl FnOnce(&crate::painting::hit_test::HitTestList, &crate::painting::paint_read::PaintSource<'_>) -> R,-) -> R {- with_hit_test_list(host, read, default, |_, _| {}, |list, _, source| query(list, source))-}-fn with_hit_test_list_spatial_indexes_and_visual_context_tree<R>(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,@@ -1044,39 +1035,6 @@ fn tree_as_the_query_reads_it<'tree>(}}-fn ffi_topmost(item: Option<crate::painting::hit_test::query::TopmostItem>) -> crate::painting::host::FfiTopmostItem {- match item {- Some(item) => crate::painting::host::FfiTopmostItem {- has_item: true,- index: item.index,- local: item.local_point.into(),- },- None => crate::painting::host::FfiTopmostItem::default(),- }-}--/// # Safety-///-/// `host` must be a live document host, on its document's thread; the-/// sink pointer must stay valid for this synchronous call.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn layout_hit_test_visit_chrome_widgets(- host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,- sink: *mut c_void,- visit: unsafe extern "C" fn(*mut c_void, NodeSlotId, u8),-) {- with_hit_test_list_items_only(host, read, (), |list, _arena| {- for item in list.items.iter() {- if item.chrome_widget_kind == crate::painting::hit_test::CHROME_WIDGET_NONE {- continue;- }- // SAFETY: The C++ host consumes the visit synchronously.- unsafe { visit(sink, item.paintable, item.chrome_widget_kind) };- }- });-}-#[unsafe(no_mangle)]pub extern "C" fn layout_hit_test_list_generation(host: &crate::render_state::DocumentHost) -> u64 {let mut recording = host.recording();@@ -1095,97 +1053,108 @@ pub extern "C" fn layout_paintable_event_dispatch_target(})}-#[unsafe(no_mangle)]-pub extern "C" fn layout_hit_test_item_facts(+/// Answers `query` about `point` through `answer`, from the rows as of every write the host made, with every row's+/// overflow measured, in `read`. A hit test paints nothing, so it walks the overlays a frame paints.+fn with_point_query<R>(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,- index: usize,- out: &mut crate::painting::host::FfiHitTestItemExport,-) {- *out = with_hit_test_list_items_only(host, read, None, |list, arena| {- let item = &list.items[index];- assert!(- arena.paintable_row_is_populated(item.paintable),- "exporting a hit-test item for a non-live paintable"- );- assert!(- arena.paintable_row_is_populated(item.hit_node),- "exporting a hit-test item that names a non-live paintable"- );- Some(crate::painting::host::FfiHitTestItemExport {- paintable: item.paintable,- hit_node: item.hit_node,- chrome_widget_kind: item.chrome_widget_kind,- context: item.context,- })- })- .expect("no hit-test list");+ query: &crate::painting::host::FfiHitTestQuery,+ point: FfiCssPixelPoint,+ default: R,+ answer: impl FnOnce(&crate::painting::paint_read::PaintSource<'_>, crate::painting::hit_test::walk::PointQuery<'_>) -> R,+) -> R {+ let scroll_state = host.scroll_state();+ let callbacks =+ crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(query, scroll_state.device_offsets());+ let rows = host.fresh_measured_rows(read);+ let Some(tree) = rows.visual_context_tree.as_deref() else {+ return default;+ };+ let mut sampled = None;+ let tree = tree_as_the_query_reads_it(tree, &callbacks, &mut sampled);+ let world = callbacks.build_world_transforms(tree);+ let callbacks = &callbacks.with_world_transforms(&world);+ let absolute_rects = std::cell::RefCell::default();+ let source = crate::painting::paint_read::PaintSource::over_rows(&rows.paintable, &absolute_rects);+ answer(+ &source,+ crate::painting::hit_test::walk::PointQuery {+ tree,+ callbacks,+ viewport: rows.viewport,+ paint_overlay: true,+ point: point.into(),+ },+ )}-#[unsafe(no_mangle)]-pub extern "C" fn layout_hit_test_resolve_hit(- host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,- item_index: usize,- local_point: FfiCssPixelPoint,-) -> crate::painting::host::FfiResolvedHit {- with_hit_test_list_items_only(host, read, Default::default(), |list, arena| {- list.resolve_hit(arena, item_index, local_point.into())- })+fn ffi_point_hit(+ source: &crate::painting::paint_read::PaintSource<'_>,+ hit: &crate::painting::hit_test::walk::PointHit,+) -> crate::painting::host::FfiPointHit {+ use crate::painting::paint_read::GeometryRead;+ assert!(+ source.paintable_row_is_populated(hit.item.paintable),+ "a hit names a paintable that has a row"+ );+ crate::painting::host::FfiPointHit {+ paintable: hit.item.paintable,+ hit_node: hit.item.hit_node,+ chrome_widget_kind: hit.item.chrome_widget_kind,+ local: hit.local_point.into(),+ resolved: crate::painting::hit_test::resolve::resolve_hit(source, &hit.item, hit.local_point),+ }}+/// Writes the topmost thing under `point` to `out` and answers whether there is one.+////// # Safety////// `host` must be a live document host, on its document's thread.#[unsafe(no_mangle)]-pub unsafe extern "C" fn layout_hit_test_find_topmost_item(+pub unsafe extern "C" fn layout_hit_test_topmost_hit(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,query: crate::painting::host::FfiHitTestQuery,point: FfiCssPixelPoint,- out: &mut crate::painting::host::FfiTopmostItem,-) {- let scroll_state = host.scroll_state();- let callbacks =- crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(&query, scroll_state.device_offsets());- *out = with_hit_test_list_spatial_indexes_and_visual_context_tree(- host,- read,- Default::default(),- |list, tree, arena| {- let mut sampled = None;- let tree = tree_as_the_query_reads_it(tree, &callbacks, &mut sampled);- let world = callbacks.build_world_transforms(tree);- ffi_topmost(list.find_topmost_item(arena, tree, &callbacks.with_world_transforms(&world), point.into()))- },- );+ out: &mut crate::painting::host::FfiPointHit,+) -> bool {+ let hit = with_point_query(host, read, &query, point, None, |source, point_query| {+ crate::painting::hit_test::walk::topmost_hit(source, point_query).map(|hit| ffi_point_hit(source, &hit))+ });+ match hit {+ Some(hit) => {+ *out = hit;+ true+ }+ None => false,+ }}+/// Hands `visit` everything under `point`, topmost first.+////// # Safety///-/// `host` must be a live document host, on its document's thread.+/// `host` must be a live document host, on its document's thread; the sink pointer must stay valid for this+/// synchronous call.#[unsafe(no_mangle)]-pub unsafe extern "C" fn layout_hit_test_all(+pub unsafe extern "C" fn layout_hit_test_all_hits(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,query: crate::painting::host::FfiHitTestQuery,point: FfiCssPixelPoint,- push_context: *mut c_void,- push: unsafe extern "C" fn(*mut c_void, usize, FfiCssPixelPoint),+ sink: *mut c_void,+ visit: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiPointHit),) {- let scroll_state = host.scroll_state();- let callbacks =- crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(&query, scroll_state.device_offsets());- let hits =- with_hit_test_list_spatial_indexes_and_visual_context_tree(host, read, Vec::new(), |list, tree, arena| {- let mut sampled = None;- let tree = tree_as_the_query_reads_it(tree, &callbacks, &mut sampled);- let world = callbacks.build_world_transforms(tree);- list.hit_test_all(arena, tree, &callbacks.with_world_transforms(&world), point.into())- });- for hit in hits {+ let hits = with_point_query(host, read, &query, point, Vec::new(), |source, point_query| {+ crate::painting::hit_test::walk::all_hits(source, point_query)+ .iter()+ .map(|hit| ffi_point_hit(source, hit))+ .collect()+ });+ for hit in &hits {// SAFETY: The C++ sink consumes the hit synchronously.- unsafe { push(push_context, hit.index, hit.local_point.into()) };+ unsafe { visit(sink, hit) };}}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/items.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/items.rsindex 74bc8fc2df1..c35a27d47fc 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/items.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/items.rs@@ -449,6 +449,9 @@ impl<'a, R: PaintRead, S: HitTestItemSink> HitTestItems<'a, R, S> {return;}let context = self.rows.paintable_data(paintable).accumulated_visual_context;+ if !self.sink.wants(HitTestItemKind::SvgPath, bounding_box, context) {+ return;+ }let item = HitTestItem {rect: bounding_box,path: Some(path),@@ -481,6 +484,9 @@ impl<'a, R: PaintRead, S: HitTestItemSink> HitTestItems<'a, R, S> {CssPixels::default(),);let context = self.rows.paintable_data(paintable).accumulated_visual_context;+ if !self.sink.wants(HitTestItemKind::Box, rect, context) {+ return;+ }let item = HitTestItem {rect,..self.base_hit_test_item(HitTestItemKind::Box, paintable, context)@@ -582,6 +588,9 @@ impl<'a, R: PaintRead, S: HitTestItemSink> HitTestItems<'a, R, S> {context: ContextRef,border_radii: BorderRadii,) {+ if !self.sink.wants(HitTestItemKind::Box, rect, context) {+ return;+ }let item = HitTestItem {rect,border_radii,@@ -627,6 +636,9 @@ impl<'a, R: PaintRead, S: HitTestItemSink> HitTestItems<'a, R, S> {}fn append_empty_editable(&mut self, paintable: NodeSlotId, rect: CssPixelRect, context: ContextRef) {+ if !self.sink.wants(HitTestItemKind::EmptyEditable, rect, context) {+ return;+ }let item = HitTestItem {rect,..self.base_hit_test_item(HitTestItemKind::EmptyEditable, paintable, context)@@ -635,6 +647,12 @@ impl<'a, R: PaintRead, S: HitTestItemSink> HitTestItems<'a, R, S> {}fn append_chrome_widget(&mut self, paintable: NodeSlotId, chrome_widget_kind: u8, context: ContextRef) {+ if !self+ .sink+ .wants(HitTestItemKind::ChromeWidget, CssPixelRect::default(), context)+ {+ return;+ }let item = HitTestItem {chrome_widget_kind,..self.base_hit_test_item(HitTestItemKind::ChromeWidget, paintable, context)diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rsindex adec176bbef..7814294952c 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs@@ -8,6 +8,7 @@ pub mod caret;pub(crate) mod items;pub mod query;pub mod resolve;+pub(crate) mod walk;use crate::css::css_pixels::CssPixels;use crate::css::css_pixels::{CssPixelPoint, CssPixelRect};diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/query.rsindex d73f30e4f70..98768389662 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs@@ -16,7 +16,7 @@ use crate::painting::visual_context::{use libgfx_rust::FloatPoint;use std::collections::HashMap;-struct DepthSortingState<'a> {+pub(super) struct DepthSortingState<'a> {tree: &'a VisualContextTree,point: CssPixelPoint,device_pixels_per_css_pixel: f32,@@ -26,7 +26,11 @@ struct DepthSortingState<'a> {}impl<'a> DepthSortingState<'a> {- fn new(callbacks: &'a FfiHitTestQueryCallbacks, tree: &'a VisualContextTree, point: CssPixelPoint) -> Self {+ pub(super) fn new(+ callbacks: &'a FfiHitTestQueryCallbacks,+ tree: &'a VisualContextTree,+ point: CssPixelPoint,+ ) -> Self {Self {tree,point,@@ -42,7 +46,7 @@ impl<'a> DepthSortingState<'a> {.get_or_insert_with(|| self.tree.resolve_sorting_contexts())}- fn group_for(&mut self, spatial: SpatialNodeIndex) -> Option<u32> {+ pub(super) fn group_for(&mut self, spatial: SpatialNodeIndex) -> Option<u32> {let contexts = self.sorting_contexts();if contexts.is_empty() || contexts.leaf_by_node[spatial.0 as usize] == NO_SORTING_CONTEXT {None@@ -55,7 +59,7 @@ impl<'a> DepthSortingState<'a> {}}- fn depth_key_for(&mut self, spatial: SpatialNodeIndex) -> Option<i64> {+ pub(super) fn depth_key_for(&mut self, spatial: SpatialNodeIndex) -> Option<i64> {let contexts = self.sorting_contexts();if contexts.is_empty() {return None;@@ -88,74 +92,73 @@ pub struct TopmostItem {pub local_point: CssPixelPoint,}-impl HitTestList {- fn item_contains(- &self,- layout_arena: &impl PaintRead,- callbacks: &FfiHitTestQueryCallbacks,- item: &HitTestItem,- local: FloatPoint,- ) -> bool {- let local_point = to_css_point(local);- match item.kind {- HitTestItemKind::Box => {- item.rect.contains_point(local_point) && item.border_radii.contains(local_point, item.rect)+pub(super) fn item_contains_point(+ layout_arena: &impl PaintRead,+ callbacks: &FfiHitTestQueryCallbacks,+ item: &HitTestItem,+ local: FloatPoint,+) -> bool {+ let local_point = to_css_point(local);+ match item.kind {+ HitTestItemKind::Box => {+ item.rect.contains_point(local_point) && item.border_radii.contains(local_point, item.rect)+ }+ HitTestItemKind::SvgPath => {+ // SVG paths test in float: their local units can map to many device pixels each.+ let rect = item.rect;+ let FloatPoint { x, y } = local;+ let in_rect = x >= rect.left().to_float()+ && x < rect.right().to_float()+ && y >= rect.top().to_float()+ && y < rect.bottom().to_float();+ if !in_rect {+ return false;}- HitTestItemKind::SvgPath => {- // SVG paths test in float: their local units can map to many device pixels each.- let rect = item.rect;- let FloatPoint { x, y } = local;- let in_rect = x >= rect.left().to_float()- && x < rect.right().to_float()- && y >= rect.top().to_float()- && y < rect.bottom().to_float();- if !in_rect {- return false;- }- let Some(path) = item.path.as_ref() else {- return false;- };- (item.svg_hit_areas & svg_hit_area::FILL != 0 && path.contains(x, y, item.winding_rule))- || (item.svg_hit_areas & svg_hit_area::STROKE != 0- && item- .svg_stroke- .as_ref()- .is_some_and(|stroke| stroke.contains(path, x, y)))+ let Some(path) = item.path.as_ref() else {+ return false;+ };+ (item.svg_hit_areas & svg_hit_area::FILL != 0 && path.contains(x, y, item.winding_rule))+ || (item.svg_hit_areas & svg_hit_area::STROKE != 0+ && item+ .svg_stroke+ .as_ref()+ .is_some_and(|stroke| stroke.contains(path, x, y)))+ }+ HitTestItemKind::TextFragment => item.rect.contains_point(local_point),+ HitTestItemKind::EmptyEditable => item.rect.contains_point(local_point),+ HitTestItemKind::ChromeWidget => {+ if !layout_arena.paintable_row_is_populated(item.paintable) {+ return false;}- HitTestItemKind::TextFragment => item.rect.contains_point(local_point),- HitTestItemKind::EmptyEditable => item.rect.contains_point(local_point),- HitTestItemKind::ChromeWidget => {- if !layout_arena.paintable_row_is_populated(item.paintable) {- return false;- }- assert!(- callbacks.has_chrome_metrics,- "chrome widget hit testing needs the chrome metrics"- );- let node = item.paintable;- let rows = layout_arena;- let chrome_geometry = ChromeGeometry::for_hit_test_query(rows, callbacks);- match item.chrome_widget_kind {- 1 => chrome_geometry.resizer_contains(node, local_point),- 2 | 3 => {- let direction = if item.chrome_widget_kind == 2 {- ScrollDirection::Horizontal- } else {- ScrollDirection::Vertical- };- // An overlay scrollbar that has faded out takes no pointer input, as in Chromium. The- // compositor grows a hovered scrollbar, which is hit tested here as it is before it grows.- !scrollbar_is_hidden(rows, node, direction)- && chrome_geometry- .absolute_scrollbar_rect(node, direction, false)- .is_some_and(|rect| rect.contains_point(local_point))- }- _ => false,+ assert!(+ callbacks.has_chrome_metrics,+ "chrome widget hit testing needs the chrome metrics"+ );+ let node = item.paintable;+ let rows = layout_arena;+ let chrome_geometry = ChromeGeometry::for_hit_test_query(rows, callbacks);+ match item.chrome_widget_kind {+ 1 => chrome_geometry.resizer_contains(node, local_point),+ 2 | 3 => {+ let direction = if item.chrome_widget_kind == 2 {+ ScrollDirection::Horizontal+ } else {+ ScrollDirection::Vertical+ };+ // An overlay scrollbar that has faded out takes no pointer input, as in Chromium. The+ // compositor grows a hovered scrollbar, which is hit tested here as it is before it grows.+ !scrollbar_is_hidden(rows, node, direction)+ && chrome_geometry+ .absolute_scrollbar_rect(node, direction, false)+ .is_some_and(|rect| rect.contains_point(local_point))}+ _ => false,}}}+}+impl HitTestList {fn find_topmost_item_in_list(&self,layout_arena: &impl PaintRead,@@ -168,7 +171,7 @@ impl HitTestList {if topmost.is_some_and(|topmost| *item_index <= topmost) {return;}- if self.item_contains(layout_arena, callbacks, &self.items[*item_index], local) {+ if item_contains_point(layout_arena, callbacks, &self.items[*item_index], local) {*topmost = Some(*item_index);return;}@@ -256,7 +259,7 @@ impl HitTestList {{for item_index in candidate_list {if *item_index == winner.index- || !self.item_contains(layout_arena, callbacks, &self.items[*item_index], local)+ || !item_contains_point(layout_arena, callbacks, &self.items[*item_index], local){continue;}@@ -287,68 +290,4 @@ impl HitTestList {// context keeps record order, which stays correct because a context's items are recorded contiguously.Some(self.topmost_item_by_plane_depth(layout_arena, visual_context_tree, callbacks, point, topmost))}-- pub(crate) fn hit_test_all(- &self,- layout_arena: &impl PaintRead,- visual_context_tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- point: CssPixelPoint,- ) -> Vec<TopmostItem> {- debug_assert!(self.spatial_indexes_built);- let mut hits: Vec<TopmostItem> = Vec::new();- let viewport_mapping = callbacks.viewport_mapping(visual_context_tree);- for (context, spatial_index) in &self.spatial_indexes_by_context {- let Some(local) =- viewport_mapping.point_to_local(*context, point, ViewportSpace::VisualViewport, ClipBehavior::Respect)- else {- continue;- };- let local_point = to_css_point(local);- for candidate_list in Self::candidate_item_lists(spatial_index, local_point)- .into_iter()- .flatten()- {- for item_index in candidate_list {- if self.item_contains(layout_arena, callbacks, &self.items[*item_index], local) {- hits.push(TopmostItem {- index: *item_index,- local_point,- });- }- }- }- }- hits.sort_by_key(|hit| std::cmp::Reverse(hit.index));- hits.dedup_by_key(|hit| hit.index);- self.sort_hits_within_sorting_contexts(visual_context_tree, callbacks, point, &mut hits);- hits- }-- // Runs of hits on the planes of one 3D rendering context are reordered front to back. A context's items- // are recorded contiguously, so after the record-order sort its hits sit adjacent.- fn sort_hits_within_sorting_contexts(- &self,- visual_context_tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- point: CssPixelPoint,- hits: &mut [TopmostItem],- ) {- let mut depth_sorting = DepthSortingState::new(callbacks, visual_context_tree, point);- let mut run_begin = 0;- while run_begin < hits.len() {- let group = depth_sorting.group_for(self.items[hits[run_begin].index].context.spatial);- let mut run_end = run_begin + 1;- if group.is_some() {- while run_end < hits.len()- && depth_sorting.group_for(self.items[hits[run_end].index].context.spatial) == group- {- run_end += 1;- }- hits[run_begin..run_end]- .sort_by_key(|hit| std::cmp::Reverse(self.depth_sort_key(&mut depth_sorting, hit.index)));- }- run_begin = run_end;- }- }}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rsindex 9d8de388d7d..1a7ca377478 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs@@ -22,42 +22,48 @@ pub(crate) fn row_dom_style_node(arena: &impl PaintRead, slot: NodeSlotId) -> u3}}-impl HitTestList {- /// The DOM node the item dispatches events to. A text fragment generated for a pseudo-element- /// dispatches to the pseudo-element's generator.- pub(crate) fn item_dispatch_target(&self, arena: &impl PaintRead, item_index: usize) -> FfiNodeIdentity {- let item = &self.items[item_index];- match item.kind {- HitTestItemKind::TextFragment => fragment_layout_node_slot(arena, item)- .map_or_else(FfiNodeIdentity::default, |slot| row_node_identity(arena, slot, true)),- _ => event_dispatch_target_of_paintable(arena, item.paintable),+/// The DOM node the item dispatches events to. A text fragment generated for a pseudo-element+/// dispatches to the pseudo-element's generator.+pub(crate) fn item_dispatch_target(arena: &impl PaintRead, item: &HitTestItem) -> FfiNodeIdentity {+ match item.kind {+ HitTestItemKind::TextFragment => fragment_layout_node_slot(arena, item)+ .map_or_else(FfiNodeIdentity::default, |slot| row_node_identity(arena, slot, true)),+ _ => event_dispatch_target_of_paintable(arena, item.paintable),+ }+}++pub(crate) fn resolve_hit(+ arena: &impl PaintRead,+ item: &HitTestItem,+ local_point: CssPixelPoint,+) -> crate::painting::host::FfiResolvedHit {+ let mut result = crate::painting::host::FfiResolvedHit {+ dispatch: item_dispatch_target(arena, item),+ ..Default::default()+ };+ match item.kind {+ HitTestItemKind::TextFragment => {+ result.fallback_dispatch = event_dispatch_target_of_paintable(arena, item.paintable);+ result.has_index_in_node = true;+ result.index_in_node = fragment_index_in_node_for_point(arena, item, local_point);+ result.is_text_fragment = true;+ }+ HitTestItemKind::EmptyEditable => {+ result.has_index_in_node = true;}+ _ => {}}+ result+}+impl HitTestList {pub(crate) fn resolve_hit(&self,arena: &impl PaintRead,item_index: usize,local_point: CssPixelPoint,) -> crate::painting::host::FfiResolvedHit {- let item = &self.items[item_index];- let mut result = crate::painting::host::FfiResolvedHit {- dispatch: self.item_dispatch_target(arena, item_index),- ..Default::default()- };- match item.kind {- HitTestItemKind::TextFragment => {- result.fallback_dispatch = event_dispatch_target_of_paintable(arena, item.paintable);- result.has_index_in_node = true;- result.index_in_node = fragment_index_in_node_for_point(arena, item, local_point);- result.is_text_fragment = true;- }- HitTestItemKind::EmptyEditable => {- result.has_index_in_node = true;- }- _ => {}- }- result+ resolve_hit(arena, &self.items[item_index], local_point)}}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/walk.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/walk.rsnew file mode 100644index 00000000000..8f43b30dc17--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/walk.rs@@ -0,0 +1,397 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Hit testing by walking the document's paint order over its rows.+//!+//! The walk follows the plans the display list recorder records by, so what it meets is in paint order, and a point+//! is answered by walking that order backwards: the first item under the point is the topmost one. A scope whose+//! owner's ink overflow bounds it is skipped when the point lies outside the bound.++use super::items::{HitTestFacts, HitTestItemSink, hit_test_facts, hit_test_items_of_phase};+use super::query::{DepthSortingState, item_contains_point};+use super::*;+use crate::layout::node_data::{NodeFlag, NodeSlotId};+use crate::painting::host::FfiHitTestQueryCallbacks;+use crate::painting::ink_overflow::{ScopeInkBound, scope_ink_bound};+use crate::painting::paint_order_plan::{PaintOrderItem, PaintScope, PaintScopePlan};+use crate::painting::paint_read::PaintRead;+use crate::painting::paintable_data::PaintableFlag;+use crate::painting::record::PaintPhase;+use crate::painting::record::assemble::producer_kinds;+use crate::painting::record::order_tree::ProducerKind;+use crate::painting::record::producers::hit_phase;+use crate::painting::viewport_mapping::{ViewportMapping, ViewportSpace};+use crate::painting::visual_context::{+ ClipBehavior, IncludeVisualViewportTransform, SpatialNodeIndex, VisualContextTree, WorldTransforms,+};+use libgfx_rust::FloatPoint;+use smallvec::SmallVec;++// https://drafts.csswg.org/css-transforms-1/#transform-function-lists+// If a transform function causes the current transformation matrix of an object to be+// non-invertible, the object and its content do not get displayed. Content whose transform+// is animated is retained so the compositor can reveal it without a main-thread repaint.+pub(crate) fn stacking_context_paints(rows: &impl PaintRead, owner: NodeSlotId) -> bool {+ !(rows+ .paintable_data(owner)+ .has_flag(PaintableFlag::HasNonInvertibleCssTransform)+ && rows.node_flags_if_live(owner) & NodeFlag::HasAnimatedOpacityOrTransform as u32 == 0)+}++/// Whether the SVG box paints nothing, and so can be hit nowhere, because a mask or clip path it references covers+/// no area.+fn svg_box_is_hidden_by_an_empty_mask_or_clip(rows: &impl PaintRead, svg_box: NodeSlotId) -> bool {+ crate::painting::visual_context::node_values::mask_layer_presence(rows, svg_box, false)+ .iter()+ .any(|layer| layer.area.is_empty())+}++/// The boxes below an SVG box that its producer walks: those a stacking context of their own does not paint.+fn svg_children_painted_with_their_parent(rows: &impl PaintRead, svg_box: NodeSlotId) -> SmallVec<[NodeSlotId; 8]> {+ let mut children = SmallVec::new();+ let mut next_child = crate::painting::paint_order::first_paint_child(rows, svg_box);+ while let Some(child) = next_child {+ next_child = crate::painting::paint_order::next_paint_sibling(rows, child);+ if !rows.paintable_data(child).establishes_stacking_context {+ children.push(child);+ }+ }+ children+}++// The scale of a space does not depend on where anything is scrolled to, so any table of the tree's spaces gives it.+fn own_accumulated_2d_scale(+ rows: &impl PaintRead,+ spaces: &WorldTransforms,+ paintable: NodeSlotId,+) -> libgfx_rust::FloatSize {+ spaces.accumulated_2d_scale(+ rows.paintable_data(paintable).accumulated_visual_context.spatial,+ IncludeVisualViewportTransform::No,+ )+}++/// An item under a point, with the point in the space of the item.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct PointHit {+ pub item: HitTestItem,+ pub local_point: CssPixelPoint,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Wanted {+ Topmost,+ Everything,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Flow {+ Continue,+ Stop,+}++struct PointWalk<'a, R: PaintRead> {+ rows: &'a R,+ callbacks: &'a FfiHitTestQueryCallbacks,+ viewport_mapping: ViewportMapping<'a>,+ point: CssPixelPoint,+ paint_overlay: bool,+ wanted: Wanted,+ skips_scopes_the_point_misses: bool,+ depth_sorting: DepthSortingState<'a>,+ local_points_inside_clips: FastMap<ContextRef, Option<FloatPoint>>,+ local_points_ignoring_clips: FastMap<SpatialNodeIndex, Option<FloatPoint>>,+ hits_of_producer_in_paint_order: Vec<PointHit>,+ /// What lies under the point, topmost first as the walk met it.+ hits: Vec<PointHit>,+ /// The 3D rendering context the topmost hit is in, whose planes paint sorted by depth: the walk goes on until+ /// it leaves the context, and the plane nearest the viewer wins.+ sorting_group_of_topmost_hit: Option<u32>,+ walk_left_the_sorting_group: bool,+}++impl<R: PaintRead> HitTestItemSink for PointWalk<'_, R> {+ fn hit_test_facts(&mut self, paintable: NodeSlotId) -> HitTestFacts {+ hit_test_facts(self.rows, paintable)+ }++ fn own_accumulated_2d_scale(&self, paintable: NodeSlotId) -> libgfx_rust::FloatSize {+ own_accumulated_2d_scale(self.rows, self.callbacks.world_transforms(), paintable)+ }++ fn wants(&mut self, kind: HitTestItemKind, rect: CssPixelRect, context: ContextRef) -> bool {+ if let Some(group) = self.sorting_group_of_topmost_hit+ && self.depth_sorting.group_for(context.spatial) != Some(group)+ {+ self.walk_left_the_sorting_group = true;+ return false;+ }+ let Some(local) = self.local_point_inside_clips(context) else {+ return false;+ };+ // A chrome widget is placed when it is tested, and a path is tested in float units. Everything else lies in+ // its rect, which one unit of slack keeps from being rejected by rounding the point.+ let one_unit = CssPixels::from_raw(1);+ kind == HitTestItemKind::ChromeWidget+ || kind == HitTestItemKind::SvgPath+ || rect+ .inflated(one_unit, one_unit, one_unit, one_unit)+ .contains_point(to_css_point(local))+ }++ fn append(&mut self, item: HitTestItem) {+ let Some(local) = self.local_point_inside_clips(item.context) else {+ return;+ };+ if item_contains_point(self.rows, self.callbacks, &item, local) {+ self.hits_of_producer_in_paint_order.push(PointHit {+ item,+ local_point: to_css_point(local),+ });+ }+ }+}++impl<R: PaintRead> PointWalk<'_, R> {+ fn local_point(&self, context: ContextRef, clip_behavior: ClipBehavior) -> Option<FloatPoint> {+ self.viewport_mapping+ .point_to_local(context, self.point, ViewportSpace::VisualViewport, clip_behavior)+ }++ fn local_point_inside_clips(&mut self, context: ContextRef) -> Option<FloatPoint> {+ if let Some(local) = self.local_points_inside_clips.get(&context) {+ return *local;+ }+ let local = self.local_point(context, ClipBehavior::Respect);+ self.local_points_inside_clips.insert(context, local);+ local+ }++ fn local_point_ignoring_clips(&mut self, context: ContextRef) -> Option<FloatPoint> {+ if let Some(local) = self.local_points_ignoring_clips.get(&context.spatial) {+ return *local;+ }+ let local = self.local_point(context, ClipBehavior::Ignore);+ self.local_points_ignoring_clips.insert(context.spatial, local);+ local+ }++ /// Whether nothing the scope paints can be under the point. A point that cannot be taken into the owner's space+ /// misses nothing.+ fn point_misses_scope(&mut self, scope: PaintScope) -> bool {+ let ScopeInkBound::Rect(bound) = scope_ink_bound(self.rows, scope) else {+ return false;+ };+ let own_context = self.rows.paintable_data(scope.owner).accumulated_visual_context;+ let Some(local) = self.local_point_ignoring_clips(own_context) else {+ return false;+ };+ let one_pixel = CssPixels::from_integer(1);+ !bound+ .inflated(one_pixel, one_pixel, one_pixel, one_pixel)+ .contains_point(to_css_point(local))+ }++ fn scope(&mut self, scope: PaintScope) -> Flow {+ if self.skips_scopes_the_point_misses && self.point_misses_scope(scope) {+ return Flow::Continue;+ }+ let plan = PaintScopePlan::build(self.rows, scope, self.paint_overlay);+ if plan.establishes_stacking_context && !stacking_context_paints(self.rows, scope.owner) {+ return Flow::Continue;+ }+ for item in plan.items.iter().rev() {+ let flow = match *item {+ PaintOrderItem::Producer(producer) => producer_kinds(producer)+ .into_iter()+ .rev()+ .map(|kind| self.producer(scope.owner, kind))+ .find(|flow| *flow == Flow::Stop)+ .unwrap_or(Flow::Continue),+ PaintOrderItem::Scope(child) => self.scope(child),+ };+ if flow == Flow::Stop {+ return Flow::Stop;+ }+ }+ Flow::Continue+ }++ fn producer(&mut self, owner: NodeSlotId, kind: ProducerKind) -> Flow {+ if let Some(phase) = hit_phase(kind) {+ self.items_of_phase(owner, phase)+ } else if kind == ProducerKind::Svg {+ self.svg_box(owner)+ } else {+ Flow::Continue+ }+ }++ fn svg_box(&mut self, svg_box: NodeSlotId) -> Flow {+ if svg_box_is_hidden_by_an_empty_mask_or_clip(self.rows, svg_box) {+ return Flow::Continue;+ }+ for child in svg_children_painted_with_their_parent(self.rows, svg_box)+ .into_iter()+ .rev()+ {+ if self.svg_box(child) == Flow::Stop {+ return Flow::Stop;+ }+ }+ self.items_of_phase(svg_box, PaintPhase::Foreground)+ }++ fn items_of_phase(&mut self, owner: NodeSlotId, phase: PaintPhase) -> Flow {+ let rows = self.rows;+ debug_assert!(self.hits_of_producer_in_paint_order.is_empty());+ hit_test_items_of_phase(rows, self, owner, phase);+ let mut hits = std::mem::take(&mut self.hits_of_producer_in_paint_order);+ let mut flow = if self.walk_left_the_sorting_group {+ Flow::Stop+ } else {+ Flow::Continue+ };+ for hit in hits.drain(..).rev() {+ if flow == Flow::Continue {+ flow = self.take_hit(hit);+ }+ }+ self.hits_of_producer_in_paint_order = hits;+ flow+ }++ fn take_hit(&mut self, hit: PointHit) -> Flow {+ if self.wanted == Wanted::Everything {+ self.hits.push(hit);+ return Flow::Continue;+ }+ let group = self.depth_sorting.group_for(hit.item.context.spatial);+ if self.hits.is_empty() {+ self.hits.push(hit);+ self.sorting_group_of_topmost_hit = group;+ return if group.is_some() { Flow::Continue } else { Flow::Stop };+ }+ // A context's items are consecutive in paint order, so the first hit outside it ends it.+ if group != self.sorting_group_of_topmost_hit {+ return Flow::Stop;+ }+ self.hits.push(hit);+ Flow::Continue+ }++ /// The key hits on the planes of one 3D rendering context sort by, greatest in front: the depth of the plane at+ /// the point, and for planes at one depth their paint order, which is the reverse of the order the walk met+ /// them in.+ fn front_to_back_key(&mut self, position_among_hits: usize) -> (Option<i64>, std::cmp::Reverse<usize>) {+ let spatial = self.hits[position_among_hits].item.context.spatial;+ (+ self.depth_sorting.depth_key_for(spatial),+ std::cmp::Reverse(position_among_hits),+ )+ }++ fn topmost(mut self) -> Option<PointHit> {+ let front = (0..self.hits.len()).max_by_key(|position| self.front_to_back_key(*position))?;+ Some(self.hits.swap_remove(front))+ }++ // Runs of hits on the planes of one 3D rendering context are reordered front to back. A context's items are+ // consecutive in paint order, so its hits sit next to each other.+ fn everything_topmost_first(mut self) -> Vec<PointHit> {+ let mut order: Vec<usize> = (0..self.hits.len()).collect();+ let mut run_begin = 0;+ while run_begin < order.len() {+ let group = self.depth_sorting.group_for(self.hits[run_begin].item.context.spatial);+ let mut run_end = run_begin + 1;+ if group.is_some() {+ while run_end < order.len()+ && self.depth_sorting.group_for(self.hits[run_end].item.context.spatial) == group+ {+ run_end += 1;+ }+ order[run_begin..run_end].sort_by_key(|position| std::cmp::Reverse(self.front_to_back_key(*position)));+ }+ run_begin = run_end;+ }+ let mut hits: Vec<Option<PointHit>> = self.hits.into_iter().map(Some).collect();+ order+ .into_iter()+ .map(|position| hits[position].take().expect("every hit is taken once"))+ .collect()+ }+}++/// What a point query reads besides the rows.+#[derive(Clone, Copy)]+pub(crate) struct PointQuery<'a> {+ pub tree: &'a VisualContextTree,+ pub callbacks: &'a FfiHitTestQueryCallbacks,+ pub viewport: NodeSlotId,+ pub paint_overlay: bool,+ pub point: CssPixelPoint,+}++fn walk_for<'a, R: PaintRead>(+ rows: &'a R,+ query: PointQuery<'a>,+ wanted: Wanted,+ skips_scopes_the_point_misses: bool,+) -> PointWalk<'a, R> {+ let mut walk = PointWalk {+ rows,+ callbacks: query.callbacks,+ viewport_mapping: query.callbacks.viewport_mapping(query.tree),+ point: query.point,+ paint_overlay: query.paint_overlay,+ wanted,+ skips_scopes_the_point_misses,+ depth_sorting: DepthSortingState::new(query.callbacks, query.tree, query.point),+ local_points_inside_clips: FastMap::default(),+ local_points_ignoring_clips: FastMap::default(),+ hits_of_producer_in_paint_order: Vec::new(),+ hits: Vec::new(),+ sorting_group_of_topmost_hit: None,+ walk_left_the_sorting_group: false,+ };+ if rows.paintable_row_is_populated(query.viewport) {+ walk.scope(PaintScope::stacking_context(query.viewport));+ }+ walk+}++fn skipped_scopes_are_verified() -> bool {+ static VERIFIED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *VERIFIED.get_or_init(|| cfg!(debug_assertions) || std::env::var_os("LIBWEB_VERIFY_HIT_TEST_PRUNING").is_some())+}++/// The topmost item under the point.+pub(crate) fn topmost_hit(rows: &impl PaintRead, query: PointQuery<'_>) -> Option<PointHit> {+ let hit = walk_for(rows, query, Wanted::Topmost, true).topmost();+ if skipped_scopes_are_verified() {+ let hit_without_skipping = walk_for(rows, query, Wanted::Topmost, false).topmost();+ assert!(+ hit == hit_without_skipping,+ "Skipping paint scopes by their ink bounds changed the topmost hit at {:?}: {hit:?} instead of {hit_without_skipping:?}",+ query.point+ );+ }+ hit+}++/// Every item under the point, topmost first.+pub(crate) fn all_hits(rows: &impl PaintRead, query: PointQuery<'_>) -> Vec<PointHit> {+ let hits = walk_for(rows, query, Wanted::Everything, true).everything_topmost_first();+ if skipped_scopes_are_verified() {+ let hits_without_skipping = walk_for(rows, query, Wanted::Everything, false).everything_topmost_first();+ assert!(+ hits == hits_without_skipping,+ "Skipping paint scopes by their ink bounds changed the hits at {:?}: {hits:?} instead of {hits_without_skipping:?}",+ query.point+ );+ }+ hits+}diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rsindex cb0e6f2a11d..209c0125758 100644--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs@@ -6,7 +6,6 @@use crate::layout::node_data::NodeSlotId;use crate::layout::used_values;-use crate::painting::display_list::commands::ContextRef;use std::ffi::c_void;/// What the host gives a query of its document's hit test list. The query finds the document scrolled where the scroll@@ -128,12 +127,16 @@ impl FfiHitTestQueryCallbacks {}}+/// A box, text fragment or chrome widget under a point, with what the host needs to turn it into a hit.#[derive(Clone, Copy, Debug, Default)]#[repr(C)]-pub struct FfiTopmostItem {- pub has_item: bool,- pub index: usize,+pub struct FfiPointHit {+ pub paintable: NodeSlotId,+ pub hit_node: NodeSlotId,+ pub chrome_widget_kind: u8,+ /// The point in the space of what was hit.pub local: used_values::FfiCssPixelPoint,+ pub resolved: FfiResolvedHit,}pub use crate::layout::node_data::FfiNodeIdentity;@@ -188,12 +191,3 @@ impl FfiCaretAt {}}}--#[derive(Clone, Copy, Debug)]-#[repr(C)]-pub struct FfiHitTestItemExport {- pub paintable: NodeSlotId,- pub hit_node: NodeSlotId,- pub chrome_widget_kind: u8,- pub context: ContextRef,-}diff --git a/Libraries/LibWeb/Rust/src/painting/ink_overflow.rs b/Libraries/LibWeb/Rust/src/painting/ink_overflow.rsindex 91425dd6d13..b69595f1422 100644--- a/Libraries/LibWeb/Rust/src/painting/ink_overflow.rs+++ b/Libraries/LibWeb/Rust/src/painting/ink_overflow.rs@@ -398,10 +398,6 @@ pub(crate) fn scope_ink_bound(source: &impl PaintRead, scope: PaintScope) -> Sco.map_or(ScopeInkBound::Unbounded, ScopeInkBound::Rect)}-pub(crate) fn maintenance_enabled() -> bool {- crate::painting::record::ink_bounds::verification().enabled-}-fn include_child(ink: &mut InkOverflow, child: InkOverflow) {ink.rect.unite(child.rect);ink.unbounded |= child.contribution_unbounded;@@ -535,7 +531,7 @@ struct StoredInkOverflowAuditCounts {impl crate::layout::LayoutNodeArena {pub(crate) fn request_ink_overflow_recalculation(&mut self, node: NodeSlotId) {- if !maintenance_enabled() || !self.paintable_row_is_populated(node) {+ if !self.paintable_row_is_populated(node) {return;}if self.paintable_rows.mark_ink_overflow_dirty(node) {@@ -544,9 +540,6 @@ impl crate::layout::LayoutNodeArena {}pub(crate) fn request_containing_block_ink_overflow_recalculation(&mut self, node: NodeSlotId) {- if !maintenance_enabled() {- return;- }if self.paintable_row_is_populated(node) {let block = self.live_paintable_data(node).containing_block;self.request_ink_overflow_recalculation(block);@@ -554,9 +547,6 @@ impl crate::layout::LayoutNodeArena {}pub(crate) fn request_inline_ink_overflow_recalculation(&mut self, node: NodeSlotId) {- if !maintenance_enabled() {- return;- }let rows = self.paintable_rows();let root = if node_painting::is_fragmented_inline(&rows, node) {rows.inline_pieces_root(node)@@ -570,7 +560,7 @@ impl crate::layout::LayoutNodeArena {/// Takes the row's contribution away from whatever gathered it. The row must still name its containing block.pub(crate) fn forget_ink_overflow_of_row_being_reset(&mut self, node: NodeSlotId) {- if !maintenance_enabled() || !self.paintable_row_is_populated(node) {+ if !self.paintable_row_is_populated(node) {return;}self.request_containing_block_ink_overflow_recalculation(node);@@ -591,9 +581,6 @@ impl crate::layout::LayoutNodeArena {}pub(crate) fn settle_ink_overflow(&mut self) {- if !maintenance_enabled() {- return;- }let verification = crate::painting::record::ink_bounds::verification();if self.paintable_rows.ink_overflow_requests.is_empty() && !verification.enabled {return;diff --git a/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs b/Libraries/LibWeb/Rust/src/painting/paintable_rows.rsindex 0e9f706eb1a..caf5f8dd196 100644--- a/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs+++ b/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs@@ -764,12 +764,10 @@ impl LayoutNodeArena {store.visual_context_records.set(index, None);set_visual_context_node_handles(&mut store.visual_context_node_handles, index, None);drop_table(&mut store.stacking_context_entries, index);- if crate::painting::ink_overflow::maintenance_enabled() {- if let Some(dirty) = self.paintable_rows.ink_overflow_dirty.get_mut(index) {- *dirty = false;- }- self.request_ink_overflow_recalculation(layout_node);+ if let Some(dirty) = self.paintable_rows.ink_overflow_dirty.get_mut(index) {+ *dirty = false;}+ self.request_ink_overflow_recalculation(layout_node);self.notify_committed_box_changed(layout_node);}diff --git a/Libraries/LibWeb/Rust/src/painting/record/assemble.rs b/Libraries/LibWeb/Rust/src/painting/record/assemble.rsindex 1d762e2ed09..01daf73fade 100644--- a/Libraries/LibWeb/Rust/src/painting/record/assemble.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/assemble.rs@@ -31,7 +31,7 @@ pub(crate) struct ScopePlan {/// A box phase in paint order is up to three producers: its hit-test items, the scroll/// metadata recorded with the background, and its commands. An SVG root paints its/// background, border and then all of its content as one producer.-fn producer_kinds(producer: PaintProducer) -> SmallVec<[ProducerKind; 5]> {+pub(crate) fn producer_kinds(producer: PaintProducer) -> SmallVec<[ProducerKind; 5]> {use ProducerKind::*;match producer {PaintProducer::BoxPhase(PaintPhase::Background) => {diff --git a/Libraries/LibWeb/Rust/src/painting/record/damage.rs b/Libraries/LibWeb/Rust/src/painting/record/damage.rsindex f085c15b715..ed6d6963655 100644--- a/Libraries/LibWeb/Rust/src/painting/record/damage.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/damage.rs@@ -252,9 +252,7 @@ impl LayoutNodeArena {if damage.is_empty() || !self.paintable_row_is_populated(row) {return;}- if crate::painting::ink_overflow::maintenance_enabled()- && damage.intersects(PaintDamage::ALL_DRAW | PaintDamage::MOVED | PaintDamage::ORDER)- {+ if damage.intersects(PaintDamage::ALL_DRAW | PaintDamage::MOVED | PaintDamage::ORDER) {self.request_ink_overflow_recalculation(row);self.request_inline_ink_overflow_recalculation(row);if damage.contains(PaintDamage::MOVED) {diff --git a/Libraries/LibWeb/Rust/src/painting/record/producers.rs b/Libraries/LibWeb/Rust/src/painting/record/producers.rsindex f8fee096bc8..89cda58cad6 100644--- a/Libraries/LibWeb/Rust/src/painting/record/producers.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/producers.rs@@ -14,12 +14,11 @@ use super::order_tree::ProducerKind;use super::trace::{Action, Observer, Operation};use super::{PaintPhase, PaintRecorder};use crate::css::css_pixels::CssPixelRect;-use crate::layout::node_data::{NodeFlag, NodeSlotId};+use crate::layout::node_data::NodeSlotId;use crate::painting::display_list::commands::ContextRef;use crate::painting::force_dark::ForceDarkRole;use crate::painting::paint_order_plan::{PaintScope, PaintScopePlan};use crate::painting::paint_read::{GeometryRead, PaintRead};-use crate::painting::paintable_data::PaintableFlag;use crate::painting::record::damage::PaintDamage;use crate::painting::record::svg_resources::MaskLayerSet;use libgfx_rust::Color;@@ -49,7 +48,7 @@ fn draw_kind(phase: PaintPhase) -> ProducerKind {}}-fn hit_phase(kind: ProducerKind) -> Option<PaintPhase> {+pub(crate) fn hit_phase(kind: ProducerKind) -> Option<PaintPhase> {match kind {ProducerKind::HitBackground => Some(PaintPhase::Background),ProducerKind::HitForeground => Some(PaintPhase::Foreground),@@ -97,15 +96,6 @@ impl<O: Observer> PaintRecorder<'_, O> {root_group_color}- // https://drafts.csswg.org/css-transforms-1/#transform-function-lists- // If a transform function causes the current transformation matrix of an object to be- // non-invertible, the object and its content do not get displayed. Content whose transform- // is animated is retained so the compositor can reveal it without a main-thread repaint.- fn stacking_context_paints(&self, owner: NodeSlotId) -> bool {- !(self.data(owner).has_flag(PaintableFlag::HasNonInvertibleCssTransform)- && self.source.node_flags_if_live(owner) & NodeFlag::HasAnimatedOpacityOrTransform as u32 == 0)- }-// The transparent fill that triggers a content-generating SVG filter, and the mask// contents of a stacking context, recorded before its content.fn record_scope_preamble(&mut self, owner: NodeSlotId) {@@ -178,7 +168,8 @@ impl<O: Observer> PaintRecorder<'_, O> {impl<O: Observer> AssemblyHost for PaintRecorder<'_, O> {fn plan_scope(&mut self, scope: PaintScope) -> ScopePlan {let plan = PaintScopePlan::build(self.source, scope, self.inputs.should_paint_overlay);- let active = !plan.establishes_stacking_context || self.stacking_context_paints(scope.owner);+ let active = !plan.establishes_stacking_context+ || crate::painting::hit_test::walk::stacking_context_paints(self.source, scope.owner);ScopePlan {active,items: if active { plan.items } else { SmallVec::new() },diff --git a/Libraries/LibWeb/Rust/src/painting/selection.rs b/Libraries/LibWeb/Rust/src/painting/selection.rsindex 416eda36367..04aaf8c7922 100644--- a/Libraries/LibWeb/Rust/src/painting/selection.rs+++ b/Libraries/LibWeb/Rust/src/painting/selection.rs@@ -716,9 +716,6 @@ fn set_highlight_pseudo_styles_of_rows(}fn request_ink_for_highlight_style_rows(arena: &mut LayoutNodeArena, rows: &[NodeSlotId]) {- if !crate::painting::ink_overflow::maintenance_enabled() {- return;- }for &row in rows {arena.request_ink_overflow_recalculation(row);arena.request_inline_ink_overflow_recalculation(row);diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex ccd9b457494..aa86b13af1b 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -105,6 +105,7 @@ RENDER_STATE_ALLOWED = {"layout/run_repeatability.rs:ENABLED","layout/run_repeatability.rs:VERIFICATION","layout/tree_builder/list_unit.rs:ENABLED",+ "painting/hit_test/walk.rs:VERIFIED","painting/paint_passes.rs:PAINTING_TIMING_ENABLED","painting/record/ink_bounds.rs:VERIFICATION","render_state/clock/hover.rs:LOGS",diff --git a/Tests/LibWeb/Text/expected/hit_testing/content-outside-its-ancestors-box.txt b/Tests/LibWeb/Text/expected/hit_testing/content-outside-its-ancestors-box.txtnew file mode 100644index 00000000000..e1536115fbb--- /dev/null+++ b/Tests/LibWeb/Text/expected/hit_testing/content-outside-its-ancestors-box.txt@@ -0,0 +1,9 @@+absolute box past a clipping ancestor it is not contained by: escaper [escaper body html]+clipped part of the clipping ancestor: positioned [positioned body html]+translated child outside its parent: translated [translated body html]+where the translated child was laid out: small [small body html]+below the parent where the translated child was laid out: body [body html]+float overflowing its container: float [float body html]+child pulled out by negative margins: negative [negative body html]+fixed box contained by a transformed box: fixed [fixed body html]+fixed box under a positioned stacking context: viewport-fixed [viewport-fixed body html]diff --git a/Tests/LibWeb/Text/expected/hit_testing/many-siblings-after-insert-and-remove.txt b/Tests/LibWeb/Text/expected/hit_testing/many-siblings-after-insert-and-remove.txtnew file mode 100644index 00000000000..0772b9452ab--- /dev/null+++ b/Tests/LibWeb/Text/expected/hit_testing/many-siblings-after-insert-and-remove.txt@@ -0,0 +1,10 @@+first row: row-0 [row-0 list body html]+row 250: row-250 [row-250 list body html]+overlay over row 100: overlay [overlay row-100 list body html]+after removing an earlier row: row-251 [row-251 list body html]+the inserted row: tall [tall list body html]+after inserting a tall row: row-201 [row-201 list body html]+where a translated row was: list [list body html]+where the translated row is: row-150 [row-150 list body html]+after scrolling: row-2101 [row-2101 list body html]+overlay after scrolling: overlay [overlay row-2101 list body html]diff --git a/Tests/LibWeb/Text/expected/hit_testing/targets-that-paint-nothing.txt b/Tests/LibWeb/Text/expected/hit_testing/targets-that-paint-nothing.txtnew file mode 100644index 00000000000..8f11bec56d1--- /dev/null+++ b/Tests/LibWeb/Text/expected/hit_testing/targets-that-paint-nothing.txt@@ -0,0 +1,11 @@+transparent box over an opaque one: transparent [transparent opaque-under html]+box with zero opacity: zero-opacity [zero-opacity html]+visible child of a hidden box: visible-child [visible-child html]+hidden box beside its visible child: html [html]+child that takes events in a box that takes none: events-child [events-child html]+box that takes no events: html [html]+transparent child far from its small parent: far-child [far-child html]+edge of a wide stroke: stroked [stroked svg html]+inside an unfilled rect: svg [svg html]+stroke of the unfilled rect: unfilled [unfilled svg html]+bounding box of a group between its children: group [group svg html]diff --git a/Tests/LibWeb/Text/input/hit_testing/content-outside-its-ancestors-box.html b/Tests/LibWeb/Text/input/hit_testing/content-outside-its-ancestors-box.htmlnew file mode 100644index 00000000000..bd86967f437--- /dev/null+++ b/Tests/LibWeb/Text/input/hit_testing/content-outside-its-ancestors-box.html@@ -0,0 +1,51 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ div { box-sizing: border-box; }+ #positioned { position: relative; width: 300px; height: 40px; background: lightblue; }+ #clipper { width: 100px; height: 20px; overflow: hidden; background: orange; }+ #escaper { position: absolute; left: 200px; top: 100px; width: 50px; height: 50px; background: green; }+ #small { width: 60px; height: 20px; margin-top: 150px; background: yellow; }+ #translated { transform: translate(300px, 10px); width: 40px; height: 40px; background: pink; }+ #float-holder { width: 60px; height: 10px; margin-top: 60px; background: silver; }+ #float { float: left; margin-left: 150px; width: 80px; height: 70px; background: teal; }+ #negative-holder { clear: both; width: 50px; height: 10px; margin-left: 400px; margin-top: 90px; background: gray; }+ #negative { margin-left: -90px; margin-top: -30px; width: 60px; height: 25px; background: purple; }+ #transformed { transform: translateX(10px); width: 30px; height: 10px; margin-top: 20px; background: brown; }+ #fixed { position: fixed; left: 500px; top: 5px; width: 40px; height: 40px; background: red; }+ #stacked { position: relative; z-index: 1; width: 30px; height: 10px; background: olive; }+ #viewport-fixed { position: fixed; left: 600px; top: 100px; width: 40px; height: 40px; background: navy; }+</style>+<div id="positioned"><div id="clipper"><div><div id="escaper"></div></div></div></div>+<div id="small"><div id="translated"></div></div>+<div id="float-holder"><div id="float"></div></div>+<div id="negative-holder"><div id="negative"></div></div>+<div id="transformed"><div id="fixed"></div></div>+<div id="stacked"><div id="viewport-fixed"></div></div>+<script>+ function describe(element) {+ return element ? element.id || element.dataset.index || element.localName : "null";+ }+ function probe(label, x, y) {+ const all = document.elementsFromPoint(x, y).map(describe).join(" ");+ println(`${label}: ${describe(document.elementFromPoint(x, y))} [${all}]`);+ }+ // Probes a point given relative to the top left corner of where the element is drawn.+ function probeAt(label, element, dx, dy) {+ const rect = element.getBoundingClientRect();+ probe(label, rect.left + dx, rect.top + dy);+ }+ test(() => {+ const element = id => document.getElementById(id);+ probeAt("absolute box past a clipping ancestor it is not contained by", element("escaper"), 25, 25);+ probeAt("clipped part of the clipping ancestor", element("clipper"), 150, 10);+ probeAt("translated child outside its parent", element("translated"), 20, 30);+ probeAt("where the translated child was laid out", element("small"), 20, 10);+ probeAt("below the parent where the translated child was laid out", element("small"), 20, 30);+ probeAt("float overflowing its container", element("float"), 40, 50);+ probeAt("child pulled out by negative margins", element("negative"), 5, 5);+ probeAt("fixed box contained by a transformed box", element("fixed"), 20, 20);+ probeAt("fixed box under a positioned stacking context", element("viewport-fixed"), 20, 20);+ });+</script>diff --git a/Tests/LibWeb/Text/input/hit_testing/many-siblings-after-insert-and-remove.html b/Tests/LibWeb/Text/input/hit_testing/many-siblings-after-insert-and-remove.htmlnew file mode 100644index 00000000000..7161a82cf0a--- /dev/null+++ b/Tests/LibWeb/Text/input/hit_testing/many-siblings-after-insert-and-remove.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ #list > div { height: 2px; }+ #overlay { position: absolute; left: 100px; top: 0; width: 50px; height: 6000px; }+</style>+<div id="list"></div>+<div id="overlay"></div>+<script>+ function describe(element) {+ return element ? element.id || element.dataset.index || element.localName : "null";+ }+ function probe(label, x, y) {+ const all = document.elementsFromPoint(x, y).map(describe).join(" ");+ println(`${label}: ${describe(document.elementFromPoint(x, y))} [${all}]`);+ }+ // Probes a point given relative to the top left corner of where the element is drawn.+ function probeAt(label, element, dx, dy) {+ const rect = element.getBoundingClientRect();+ probe(label, rect.left + dx, rect.top + dy);+ }+ test(() => {+ const list = document.getElementById("list");+ for (let index = 0; index < 3000; ++index) {+ const row = document.createElement("div");+ row.dataset.index = `row-${index}`;+ list.appendChild(row);+ }+ window.scrollTo(0, 0);+ probe("first row", 10, 1);+ probe("row 250", 10, 501);+ probe("overlay over row 100", 120, 201);+ list.children[10].remove();+ probe("after removing an earlier row", 10, 501);+ const tall = document.createElement("div");+ tall.dataset.index = "tall";+ tall.style.height = "100px";+ list.insertBefore(tall, list.children[5]);+ probe("the inserted row", 10, 60);+ probe("after inserting a tall row", 10, 501);+ const translated = list.children[150];+ const whereItWas = translated.getBoundingClientRect();+ translated.style.transform = "translateX(400px)";+ probe("where a translated row was", 10, whereItWas.top + 1);+ probeAt("where the translated row is", translated, 10, 1);+ window.scrollTo(0, 4000);+ probe("after scrolling", 10, 301);+ probe("overlay after scrolling", 120, 301);+ window.scrollTo(0, 0);+ });+</script>diff --git a/Tests/LibWeb/Text/input/hit_testing/targets-that-paint-nothing.html b/Tests/LibWeb/Text/input/hit_testing/targets-that-paint-nothing.htmlnew file mode 100644index 00000000000..3aee78729f3--- /dev/null+++ b/Tests/LibWeb/Text/input/hit_testing/targets-that-paint-nothing.html@@ -0,0 +1,51 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ .row { position: absolute; left: 0; width: 400px; height: 40px; }+ #transparent { top: 0; }+ #opaque-under { top: 0; background: orange; z-index: -1; }+ #zero-opacity { top: 50px; opacity: 0; background: green; }+ #hidden { top: 100px; visibility: hidden; background: red; }+ #visible-child { visibility: visible; width: 100px; height: 20px; }+ #no-events { top: 150px; pointer-events: none; background: silver; }+ #events-child { pointer-events: auto; width: 100px; height: 20px; }+ #far-child-holder { top: 200px; width: 10px; height: 10px; }+ #far-child { position: absolute; left: 300px; top: 0; width: 50px; height: 30px; }+ svg { position: absolute; left: 0; top: 260px; }+</style>+<div id="opaque-under" class="row"></div>+<div id="transparent" class="row"></div>+<div id="zero-opacity" class="row"></div>+<div id="hidden" class="row"><div id="visible-child"></div></div>+<div id="no-events" class="row"><div id="events-child"></div></div>+<div id="far-child-holder" class="row"><div id="far-child"></div></div>+<svg id="svg" width="300" height="120">+ <line id="stroked" x1="20" y1="20" x2="200" y2="20" stroke="black" stroke-width="16" />+ <rect id="unfilled" x="20" y="50" width="100" height="40" fill="none" stroke="black" stroke-width="2" />+ <g id="group" pointer-events="bounding-box"><rect id="in-group" x="200" y="60" width="20" height="20" fill="none" /><rect x="260" y="100" width="20" height="20" fill="none" /></g>+</svg>+<script>+ function describe(element) {+ return element ? element.id || element.localName : "null";+ }+ function probe(label, x, y) {+ const all = document.elementsFromPoint(x, y).map(describe).join(" ");+ println(`${label}: ${describe(document.elementFromPoint(x, y))} [${all}]`);+ }+</script>+<script>+ test(() => {+ probe("transparent box over an opaque one", 200, 20);+ probe("box with zero opacity", 200, 70);+ probe("visible child of a hidden box", 50, 110);+ probe("hidden box beside its visible child", 200, 110);+ probe("child that takes events in a box that takes none", 50, 160);+ probe("box that takes no events", 200, 160);+ probe("transparent child far from its small parent", 320, 215);+ probe("edge of a wide stroke", 100, 287);+ probe("inside an unfilled rect", 70, 330);+ probe("stroke of the unfilled rect", 20, 330);+ probe("bounding box of a group between its children", 240, 350);+ });+</script>