Truly independent web browser
LibWeb: Resolve caretPositionFromPoint inside the hit block's lines
Aliaksandr Kalenik6ebff99ddbc4
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 43cc32d1a99..f6c478e82a4 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -12357,28 +12357,12 @@ Optional<Painting::HitTestResult> Document::hit_test(Layout::BegunRead const& rereturn {};}-Optional<Painting::CaretPosition> Document::caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint position)+Optional<Painting::CaretPosition> Document::caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint position, GC::Ptr<Node const> constraint_scope){auto query = prepare_hit_test_query(read);if (!query.has_value())return {};- return query->list().caret_position_from_point(read, position, *query, Painting::CaretPositionMode::Normal);-}--Optional<Painting::CaretPosition> Document::caret_position_from_point_for_selection_start(Layout::BegunRead const& read, CSSPixelPoint position)-{- auto query = prepare_hit_test_query(read);- if (!query.has_value())- return {};- return query->list().caret_position_from_point(read, position, *query, Painting::CaretPositionMode::SelectionStart);-}--Optional<Painting::CaretPosition> Document::caret_position_from_point_for_selection(Layout::BegunRead const& read, CSSPixelPoint position, GC::Ptr<Node const> constraint_scope)-{- auto query = prepare_hit_test_query(read);- if (!query.has_value())- return {};- return query->list().caret_position_from_point(read, position, *query, Painting::CaretPositionMode::Selection, constraint_scope);+ return query->list().caret_position_from_point(read, position, *query, constraint_scope);}TraversalDecision Document::hit_test_all(Layout::BegunRead const& read, CSSPixelPoint position, Function<TraversalDecision(Painting::HitTestResult)> const& callback)diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex a1c72aa20f0..b1971cfbab5 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1698,9 +1698,7 @@ public:// frame of the compositor's shows them.Optional<Painting::HitTestQuery> prepare_hit_test_query(Layout::BegunRead const& read, Optional<i64> visual_animation_sample_time_nanoseconds = {});Optional<Painting::HitTestResult> hit_test(Layout::BegunRead const& read, CSSPixelPoint, Optional<i64> visual_animation_sample_time_nanoseconds = {});- Optional<Painting::CaretPosition> caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint);- Optional<Painting::CaretPosition> caret_position_from_point_for_selection_start(Layout::BegunRead const& read, CSSPixelPoint);- Optional<Painting::CaretPosition> caret_position_from_point_for_selection(Layout::BegunRead const& read, CSSPixelPoint, GC::Ptr<Node const> constraint_scope = nullptr);+ Optional<Painting::CaretPosition> caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint, GC::Ptr<Node const> constraint_scope = nullptr);using CaretPositionFromPointOptions = Bindings::CaretPositionFromPointOptions;GC::Ptr<CaretPosition> caret_position_from_point(double x, double y, CaretPositionFromPointOptions const&);TraversalDecision hit_test_all(Layout::BegunRead const& read, CSSPixelPoint, Function<TraversalDecision(Painting::HitTestResult)> const&);diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex 51794c8a3be..432318d3dbc 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -3728,11 +3728,11 @@ Optional<Painting::CaretPosition> EventHandler::caret_position_for_mouse_selectiauto& text_control_element = text_control->text_control_to_html_element();if (text_control_element.is_shadow_including_inclusive_ancestor_of(*editable_hit_node_before_focus)) {if (auto selection_scope = text_control->mouse_selection_scope())- caret_position = document.caret_position_from_point_for_selection(read, visual_viewport_position, selection_scope);+ caret_position = document.caret_position_from_point(read, visual_viewport_position, selection_scope);}}if (!caret_position.has_value())- caret_position = document.caret_position_from_point_for_selection_start(read, visual_viewport_position);+ caret_position = document.caret_position_from_point(read, visual_viewport_position);if (editable_hit_node_before_focus && editable_hit_node_before_focus->is_connected() && editing_host_before_focus && should_use_caret_position_from_editable_hit_node(caret_position, *editable_hit_node_before_focus, *editing_host_before_focus)) {if (auto caret_position_from_hit_node = caret_position_from_editable_hit_node(read, *editable_hit_node_before_focus); caret_position_from_hit_node.has_value())caret_position = caret_position_from_hit_node;@@ -3745,6 +3745,18 @@ Optional<Painting::CaretPosition> EventHandler::caret_position_for_mouse_selecticaret_position = beside;}+ // INTEROP: A click outside an editing host that resolves to a position beside it, in content that is not editable,+ // places no selection.+ if (caret_position->secondary_boundary.has_value()) {+ auto boundary = caret_position->boundary_point();+ auto secondary_boundary = caret_position->secondary_boundary->resolve(document);+ if (boundary.has_value() && secondary_boundary.has_value() && !boundary->node->is_editable_or_editing_host()) {+ auto* beside = boundary->node->child_at_index(min(boundary->offset, secondary_boundary->offset));+ if (beside && beside->is_editing_host())+ return {};+ }+ }+return caret_position;}@@ -3894,7 +3906,7 @@ void EventHandler::finish_selection_from_preserved_mousedown(DOM::Document& docuif (!has_committed_root_box())return;- auto caret_position = document.caret_position_from_point_for_selection_start(read, visual_viewport_position);+ auto caret_position = document.caret_position_from_point(read, visual_viewport_position);if (!caret_position.has_value())return;@@ -4400,7 +4412,7 @@ Optional<Editing::ContextMenuMisspelling> EventHandler::select_context_menu_miss{if (!document.has_spelling_markers())return {};- auto caret_position = document.caret_position_from_point_for_selection_start(read, coordinates.visual_viewport_position);+ auto caret_position = document.caret_position_from_point(read, coordinates.visual_viewport_position);if (!caret_position.has_value())return {};auto* text = as_if<DOM::Text>(caret_position->boundary_node().ptr());@@ -4531,7 +4543,7 @@ bool EventHandler::initiate_paragraph_selection(DOM::Document& document, Paintinbool EventHandler::select_context_menu_text(Layout::BegunRead const& read, DOM::Document& document, MouseEventCoordinates const& coordinates){- auto caret_position = document.caret_position_from_point_for_selection_start(read, coordinates.visual_viewport_position);+ auto caret_position = document.caret_position_from_point(read, coordinates.visual_viewport_position);if (!caret_position.has_value() || selection_contains_position(document, *caret_position))return false;@@ -4675,7 +4687,7 @@ void EventHandler::apply_mouse_selection(Layout::BegunRead const& read, CSSPixelif (m_mouse_selection_target)constraint_scope = m_mouse_selection_target->mouse_selection_scope();- auto caret_position = document.caret_position_from_point_for_selection(read, visual_viewport_position, constraint_scope);+ auto caret_position = document.caret_position_from_point(read, visual_viewport_position, constraint_scope);if (!caret_position.has_value())return;diff --git a/Libraries/LibWeb/Painting/Forward.h b/Libraries/LibWeb/Painting/Forward.hindex c9738bb8128..e10a4c051f5 100644--- a/Libraries/LibWeb/Painting/Forward.h+++ b/Libraries/LibWeb/Painting/Forward.h@@ -14,7 +14,6 @@ namespace Web::Painting {class DocumentPaintState;class HitTestDisplayList;class HitTestQuery;-enum class CaretPositionMode : u8;enum class HitTestListAdoption : u8;struct CaretPosition;struct DisplayListRecording;diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp b/Libraries/LibWeb/Painting/HitTestDisplayList.cppindex 574e9e606c7..ad2c3bf0093 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp@@ -63,13 +63,11 @@ HitTestDisplayList::Item HitTestDisplayList::item(Layout::BegunRead const& read,struct HitTestDisplayList::QueryContext {HitTestQuery const* query { nullptr };- GC::Ptr<DOM::Document> document;Layout::RustFFI::FfiHitTestQueryCallbacks callbacks(){auto scroll_offsets = query ? query->scroll_state().device_offsets() : ReadonlySpan<Gfx::FloatPoint> {};Layout::RustFFI::FfiHitTestQueryCallbacks callbacks {- .context = this,.device_pixels_per_css_pixel = query ? query->device_pixels_per_css_pixel() : 1,.scroll_offsets = scroll_offsets.data(),.scroll_offsets_len = scroll_offsets.size(),@@ -78,14 +76,6 @@ struct HitTestDisplayList::QueryContext {.chrome_metrics = {},.has_visual_animation_sample_time = query && query->visual_animation_sample_time_nanoseconds().has_value(),.visual_animation_sample_time_ns = query ? query->visual_animation_sample_time_nanoseconds().value_or(0) : 0,- .contains = [](void* context_pointer, Layout::RustFFI::FfiNodeIdentity ancestor, Layout::RustFFI::FfiNodeIdentity node) -> bool {- auto& context = *static_cast<QueryContext*>(context_pointer);- if (!context.document)- return false;- auto ancestor_node = node_identity_of(ancestor).resolve(*context.document);- auto dom_node = node_identity_of(node).resolve(*context.document);- return ancestor_node && dom_node && ancestor_node->is_inclusive_ancestor_of(*dom_node);- },};if (query)callbacks.chrome_metrics = query->chrome_metrics();@@ -93,12 +83,6 @@ struct HitTestDisplayList::QueryContext {}};-static Layout::RustFFI::FfiNodeIdentity ffi_identity_of(DOM::Node const* node)-{- auto identity = DOM::NodeIdentity::of(node);- return { .style_node = identity.style_node().value(), .is_document = identity == DOM::NodeIdentity::of_document() };-}-Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Layout::RustFFI::FfiTopmostItem const& item){if (!item.has_item)@@ -108,7 +92,7 @@ Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::find_topmost_item(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const{- QueryContext context { &query, m_arena->document() };+ QueryContext context { &query };Layout::RustFFI::FfiTopmostItem item;Layout::RustFFI::layout_hit_test_find_topmost_item(m_arena->host(), &read, context.callbacks(), point, &item);return topmost_item_from(item);@@ -116,7 +100,7 @@ Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::find_topmost_item(Vector<HitTestDisplayList::TopmostItem> HitTestDisplayList::hit_items_topmost_first(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const{- QueryContext context { &query, m_arena->document() };+ QueryContext context { &query };Vector<TopmostItem> hits;Layout::RustFFI::layout_hit_test_all(m_arena->host(), &read, context.callbacks(), point, &hits, [](void* sink, size_t index, CSSPixelPoint local_point) {static_cast<Vector<TopmostItem>*>(sink)->append({ index, local_point });@@ -257,11 +241,13 @@ Optional<CaretPosition> HitTestDisplayList::caret_position_from(Layout::RustFFI:};}-Optional<CaretPosition> HitTestDisplayList::caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query, CaretPositionMode mode, GC::Ptr<DOM::Node const> constraint_scope) const+Optional<CaretPosition> HitTestDisplayList::caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query, GC::Ptr<DOM::Node const> constraint_scope) const{- QueryContext context { &query, m_arena->document() };+ QueryContext context { &query };+ auto const* scope_layout_node = constraint_scope ? constraint_scope->unsafe_layout_node(read) : nullptr;+ auto scope = scope_layout_node ? Layout::Node::slot_id(scope_layout_node) : Compositing::RustFFI::NodeSlotId { Compositing::RustFFI::INVALID_NODE_SLOT_INDEX };Layout::RustFFI::FfiCaretAt caret_at;- Layout::RustFFI::layout_hit_test_caret_position_from_point(m_arena->host(), &read, context.callbacks(), point, to_underlying(mode), ffi_identity_of(constraint_scope.ptr()), &caret_at);+ Layout::RustFFI::layout_hit_test_caret_position_from_point(m_arena->host(), &read, context.callbacks(), point, scope, &caret_at);return caret_position_from(caret_at);}diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.h b/Libraries/LibWeb/Painting/HitTestDisplayList.hindex a775fdb120e..09bbd339743 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.h+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.h@@ -21,13 +21,6 @@namespace Web::Painting {-enum class CaretPositionMode : u8 {- Normal,- // Starting or extending selection should feel more eager than the public caret-position API in inter-line gaps.- SelectionStart,- Selection,-};-class HitTestDisplayList;// A query of a document's hit test list, with what it reads besides the list: the visual context tree and the scroll@@ -72,9 +65,9 @@ public:u64 visual_context_tree_structural_epoch() const { return m_visual_context_tree_structural_epoch; }[[nodiscard]] bool is_current() const;[[nodiscard]] Optional<HitTestResult> hit_test(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&) const;- // When constraint_scope is given, the caret position is constrained to lines inside that node, and points- // outside it resolve to the closest position within it.- [[nodiscard]] Optional<CaretPosition> caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&, CaretPositionMode = CaretPositionMode::Normal, GC::Ptr<DOM::Node const> constraint_scope = nullptr) const;+ // The caret position the box hit at the point gives it, or when constraint_scope is given, the one that node's box+ // gives it wherever the point is.+ [[nodiscard]] Optional<CaretPosition> caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&, GC::Ptr<DOM::Node const> constraint_scope = nullptr) const;TraversalDecision hit_test_all(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&, Function<TraversalDecision(HitTestResult)> const&) const;private:diff --git a/Libraries/LibWeb/Rust/src/css/style/drag_selection.rs b/Libraries/LibWeb/Rust/src/css/style/drag_selection.rsindex bd98fda1d1d..aafb55b722f 100644--- a/Libraries/LibWeb/Rust/src/css/style/drag_selection.rs+++ b/Libraries/LibWeb/Rust/src/css/style/drag_selection.rs@@ -15,8 +15,6 @@ use super::StyleEngine;use super::tree::StyleNodeID;use crate::css::computed_value_views::ComputedValuesView;use crate::layout::node_data::DomPaintFact;-use crate::painting::hit_test::caret::NodeScopes;-use crate::painting::host::FfiNodeIdentity;use smallvec::SmallVec;use std::collections::HashSet;@@ -204,24 +202,3 @@ impl SelectionStyles {self.styled.insert(element);}}--/// What `HitTestList`'s caret queries read of the DOM on the Render thread: the mirror, where the host asks the DOM.-pub(crate) struct MirrorNodeScopes<'a>(pub(crate) &'a StyleEngine);--impl NodeScopes for MirrorNodeScopes<'_> {- fn contains(&self, ancestor: FfiNodeIdentity, node: FfiNodeIdentity) -> bool {- let identity = |identity: FfiNodeIdentity| StyleNodeID::from_raw(identity.style_node);- match (ancestor.is_document, node.is_document) {- (_, true) => ancestor.is_document,- // A shadow tree's nodes are not the document's descendants.- (true, false) => identity(node).is_none_or(|node| {- let root = self.0.drag_root(node);- self.0.retained.host_of(root).is_none()- }),- (false, false) => match (identity(ancestor), identity(node)) {- (Some(ancestor), Some(node)) => self.0.drag_is_inclusive_ancestor(ancestor, node),- _ => false,- },- }- }-}diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rsindex 3df37e20a52..ae2531a220a 100644--- a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs@@ -465,7 +465,8 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {Some(if horizontal { caret.rect.x } else { caret.rect.y })}- /// The fragments of `line` that `accepts` takes, in line order.+ /// The fragments of `line` that `accepts` takes, in line order. The block ellipsis is left out, since it shows none+ /// of the text whose offsets it carries.fn fragments_on_line<'b>(&self,side: &'b crate::painting::paintable_data::CommittedSideData,@@ -475,7 +476,9 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {let range = side.lines().get(line.index as usize).map_or(0..0, |record| {record.first_fragment as usize..(record.first_fragment + record.fragment_count) as usize});- side.fragments()[range].iter().filter(move |fragment| accepts(fragment))+ side.fragments()[range]+ .iter()+ .filter(move |fragment| !fragment.is_block_ellipsis && accepts(fragment))}/// The position in front of the <br> or preserved newline that ends `line`.@@ -538,7 +541,19 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {}}).collect();- (extents, logical)+ // A point covers the pixel after it, which is before it in a reversed block direction.+ let logical_point = move |point: CssPixelPoint| {+ let (inline, block) = logical(point);+ (+ inline,+ if block_axis_is_reverse {+ block - CssPixels::from_integer(1)+ } else {+ block+ },+ )+ };+ (extents, logical_point)}/// The columns the lines of `extents` lie in, as the inline extent of their lines and the index of their first line.@@ -615,76 +630,196 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {let mut last = first;for index in std::iter::once(first).chain(lines) {if block < extents[index].block_end {- return self.position_at_inline_coordinate(line(index), inline, accepts);+ return self+ .position_in_float_beside_empty_line(root, line(index), extents[index], inline, &logical)+ .or_else(|| self.position_on_line(line(index), point, accepts));}last = index;}self.line_edge(line(last), LineEdge::End, accepts)}- /// The caret position on `line` nearest the inline coordinate `x`, in the fragment `accepts` takes that is the last- /// to start before `x`, or else the first, or in front of the line's forced break where it takes none.+ // A line with no content of its own, such as one a <br> ends, holds the floats placed on it, which take a point over+ // their inline extent.+ fn position_in_float_beside_empty_line(+ &self,+ root: NodeSlotId,+ line: InlineLine,+ extent: LineExtent,+ inline: CssPixels,+ logical: &impl Fn(CssPixelPoint) -> (CssPixels, CssPixels),+ ) -> Option<CaretPosition> {+ let arena = self.arena;+ if arena.committed_side_data(root).lines()[line.index as usize].fragment_count > 0 {+ return None;+ }+ let float = arena.children(root).find(|&child| {+ if !arena.node(child).is_some_and(|row| row.is_floating()) || !arena.paintable_row_is_populated(child) {+ return false;+ }+ let rect = paintable_geometry::absolute_rect(arena, child);+ let (inline_start, block_start) = logical(rect.location());+ let (inline_end, block_end) = logical(CssPixelPoint::new(rect.right(), rect.bottom()));+ inline_start.min(inline_end) <= inline+ && inline < inline_start.max(inline_end)+ && block_start.min(block_end) < extent.block_end+ && extent.block_start < block_start.max(block_end)+ })?;+ Some(CaretPosition::StartOfBox { node: float })+ }++ /// The caret position on `line` nearest the inline coordinate `x`, which a move between lines kept, as for a point+ /// at the block start of the line.pub(crate) fn position_at_inline_coordinate(&self,line: InlineLine,x: CssPixels,accepts: impl Fn(&FragmentRecord) -> bool,+ ) -> Option<CaretPosition> {+ let side = self.arena.committed_side_data(line.root);+ let record = side.lines().get(line.index as usize)?;+ let rect = self.line_rect(line, record);+ let x = self.inline_coordinate_in_column_of(line, x);+ let point = match record.writing_mode {+ writing_mode::HORIZONTAL_TB => CssPixelPoint::new(x, rect.y),+ writing_mode::VERTICAL_RL | writing_mode::SIDEWAYS_RL => {+ CssPixelPoint::new(rect.right() - CssPixels::from_integer(1), x)+ }+ _ => CssPixelPoint::new(rect.x, x),+ };+ self.position_on_line(line, point, &accepts)+ }++ /// The caret position for `point` on `line`, in the fragment `accepts` takes that is the last to start before the+ /// point along the line, or else the first, or in front of the line's forced break where it takes none.+ fn position_on_line(+ &self,+ line: InlineLine,+ point: CssPixelPoint,+ accepts: &dyn Fn(&FragmentRecord) -> bool,) -> Option<CaretPosition> {let arena = self.arena;let side = arena.committed_side_data(line.root);let horizontal = self.line_is_horizontal(line);- let x = self.inline_coordinate_in_column_of(line, x);+ let x = if horizontal { point.x } else { point.y };let inline_start = |rect: CssPixelRect| if horizontal { rect.x } else { rect.y };let mut chosen = None;- for fragment in self.fragments_on_line(&side, line, &accepts) {+ for fragment in self.fragments_on_line(&side, line, accepts) {let rect = text_fragment::absolute_rect(arena, fragment);if chosen.is_none() || inline_start(rect) <= x {chosen = Some((fragment, rect));}}- let Some((fragment, rect)) = chosen else {+ let Some((mut fragment, mut rect)) = chosen else {return self.position_before_forced_break(line);};- // An inline-block takes the position in its own lines, or at its start where it has no content.- if fragment.is_atomic_inline && node_painting::has_lines(arena, fragment.layout_node) {- let line_rect = self.line_rect(line, &side.lines()[line.index as usize]);- let point = if horizontal {- CssPixelPoint::new(x, line_rect.y)- } else {- CssPixelPoint::new(line_rect.x, x)+ // INTEROP: A point in the gap between two atomic inlines goes to the one after it.+ let inline_end = |rect: CssPixelRect| if horizontal { rect.right() } else { rect.bottom() };+ if fragment.is_atomic_inline+ && x >= inline_end(rect)+ && let Some(next) = self+ .fragments_on_line(&side, line, accepts)+ .find(|next| inline_start(text_fragment::absolute_rect(arena, next)) > x)+ && next.is_atomic_inline+ {+ fragment = next;+ rect = text_fragment::absolute_rect(arena, next);+ }+ // INTEROP: Past the end of a line, the position is at its end, after whitespace that hangs there, but before+ // collapsible whitespace, which the line removes.+ if let Some(last) = self.fragments_on_line(&side, line, accepts).last()+ && !last.is_atomic_inline+ {+ let last_rect = text_fragment::absolute_rect(arena, last);+ let past_line_end = match (horizontal, last.direction == crate::css::css_enums::direction::LTR) {+ (true, true) => x >= last_rect.right(),+ (true, false) => x < last_rect.x,+ (false, true) => x >= last_rect.bottom(),+ (false, false) => x < last_rect.y,};- if let Some(position) = self.position_for_point(fragment.layout_node, point, &accepts) {- return Some(position);+ if past_line_end {+ let collapsible = matches!(+ last.white_space_collapse,+ white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS+ );+ let offset = if collapsible {+ last.dom_end_offset_in_node+ } else {+ last.dom_end_offset_with_trailing_whitespace+ };+ return Some(self.text_position_in_fragment(last, offset));}}- if fragment.is_atomic_inline && self.is_empty_inline_block(fragment.layout_node) {- return Some(CaretPosition::StartOfBox {- node: fragment.layout_node,- });- }if fragment.is_atomic_inline {- let center = if horizontal { rect.center().x } else { rect.center().y };- let reverse = arena- .node_style_if_live(fragment.layout_node)- .is_some_and(|style| style.inline_axis_is_reverse());- return Some(CaretPosition::BesideAtomicInline {- node: fragment.layout_node,- after: (x > center) != reverse,- });+ return Some(self.position_for_point_at_atomic_inline(fragment.layout_node, line, point, accepts));}- let mut point = rect.center();+ let mut point_in_fragment = point;if horizontal {- point.x = rect.x.max(x);+ point_in_fragment.x = rect.x.max(x);} else {- point.y = rect.y.max(x);+ point_in_fragment.y = rect.y.max(x);}- let offset = text_fragment::index_in_node_for_point(arena, fragment, point);+ let offset = text_fragment::index_in_node_for_point(arena, fragment, point_in_fragment);Some(self.text_position_in_fragment(fragment, offset))}- /// Whether `node` is an atomic inline box with no content of its own, which holds a caret position inside it.- fn is_empty_inline_block(&self, node: NodeSlotId) -> bool {- !crate::painting::style_queries::is_replaced_box(self.arena, node) && self.arena.children(node).next().is_none()+ /// The caret position for `point` at the atomic inline `node` on `line`. Replaced content takes it beside itself, on+ /// the side of the half it is over or of the line it is past, and so does a text control for a point outside it.+ /// Other boxes take it in their own lines, or at their start where they have no content.+ fn position_for_point_at_atomic_inline(+ &self,+ node: NodeSlotId,+ line: InlineLine,+ point: CssPixelPoint,+ accepts: &dyn Fn(&FragmentRecord) -> bool,+ ) -> CaretPosition {+ let arena = self.arena;+ let style = arena.node_style_if_live(node);+ let horizontal = style.is_none_or(|style| style.writing_mode() == writing_mode::HORIZONTAL_TB);+ let reverse = style.is_some_and(|style| style.inline_axis_is_reverse());+ let block_axis_is_reverse = style.is_some_and(|style| style.block_axis_is_reverse());+ let beside = |after| CaretPosition::BesideAtomicInline { node, after };+ // Whether the point is past `rect` in the block direction, if it is outside it that way. A point covers the+ // pixel after it, which is before it in a reversed block direction.+ let block_side = |rect: CssPixelRect| match (horizontal, block_axis_is_reverse) {+ (true, _) if point.y < rect.y => Some(false),+ (true, _) if point.y >= rect.bottom() => Some(true),+ (false, false) if point.x < rect.x => Some(false),+ (false, false) if point.x >= rect.right() => Some(true),+ (false, true) if point.x > rect.right() => Some(false),+ (false, true) if point.x <= rect.x => Some(true),+ _ => None,+ };+ let rect = paintable_geometry::absolute_border_box_rect(arena, node);+ let (inline, inline_start, inline_end) = if horizontal {+ (point.x, rect.x, rect.right())+ } else {+ (point.y, rect.y, rect.bottom())+ };+ let past_middle = (inline - inline_start > (inline_end - inline_start).scaled(0.5)) != reverse;+ if crate::painting::style_queries::is_replaced_box(arena, node) {+ let side = self.arena.committed_side_data(line.root);+ let line_rect = self.line_rect(line, &side.lines()[line.index as usize]);+ return beside(block_side(line_rect).unwrap_or(past_middle));+ }+ if matches!(+ arena.node_kind_if_live(node),+ Some(NodeKind::TextAreaBox | NodeKind::TextInputBox)+ ) {+ if inline < inline_start || inline >= inline_end {+ return beside((inline >= inline_end) != reverse);+ }+ return beside(block_side(rect).unwrap_or(past_middle));+ }+ if node_painting::has_lines(arena, node)+ && let Some(position) = self.position_for_point(node, point, accepts)+ {+ return position;+ }+ if arena.children(node).next().is_none() {+ return CaretPosition::StartOfBox { node };+ }+ beside(past_middle)}/// The caret position at `edge` of `line`, among the fragments `accepts` takes, or in front of the line's forceddiff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex 3f68b435a3c..d2c9b0757c1 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -9,7 +9,6 @@//! a token nor call an entry that does.use super::*;-use crate::painting::hit_test::caret::HostNodeScopes;use crate::painting::host::FfiCaretAt;use crate::painting::host::FfiVisualContextTreeInputs;use crate::painting::paint_passes::{PassEffect, pending_preparation, run as run_paint_pass};@@ -824,7 +823,6 @@ fn with_hit_test_list_items_only<R>(fn with_hit_test_list_spatial_indexes_and_visual_context_tree<R>(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,- needs_caret_lines: bool,default: R,query: impl FnOnce(&crate::painting::hit_test::HitTestList,@@ -836,12 +834,7 @@ fn with_hit_test_list_spatial_indexes_and_visual_context_tree<R>(host,read,None,- |list, source| {- list.build_spatial_indexes_if_needed();- if needs_caret_lines {- list.build_caret_lines_if_needed(source);- }- },+ |list, _| list.build_spatial_indexes_if_needed(),|list, rows, source| {let tree = rows.visual_context_tree.as_deref()?;Some(query(list, tree, source))@@ -971,7 +964,6 @@ pub unsafe extern "C" fn layout_hit_test_find_topmost_item(*out = with_hit_test_list_spatial_indexes_and_visual_context_tree(host,read,- false,Default::default(),|list, tree, arena| {let mut sampled = None;@@ -994,55 +986,40 @@ pub unsafe extern "C" fn layout_hit_test_all(push_context: *mut c_void,push: unsafe extern "C" fn(*mut c_void, usize, FfiCssPixelPoint),) {- let hits = with_hit_test_list_spatial_indexes_and_visual_context_tree(- host,- read,- false,- Vec::new(),- |list, tree, arena| {+ 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 {// SAFETY: The C++ sink consumes the hit synchronously.unsafe { push(push_context, hit.index, hit.local_point.into()) };}}-/// The caret position at `point`, constrained to `constraint_scope` when it names a node.+/// The caret position at `point`, or where `constraint_scope` is a box, the one that box gives it.////// # Safety///-/// `host` must be a live document host, on its document's thread; the callbacks must stay valid for this synchronous-/// call.+/// `host` must be a live document host, on its document's thread.#[unsafe(no_mangle)]pub unsafe extern "C" fn layout_hit_test_caret_position_from_point(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,callbacks: crate::painting::host::FfiHitTestQueryCallbacks,point: FfiCssPixelPoint,- mode: u8,- constraint_scope: crate::painting::host::FfiNodeIdentity,+ constraint_scope: NodeSlotId,out: &mut FfiCaretAt,) {- // SAFETY: Guaranteed by the entry point's contract.- let main_thread = unsafe { main_thread(host) };- let mode = crate::painting::hit_test::caret::CaretPositionMode::from_u8(mode);- *out = with_hit_test_list_spatial_indexes_and_visual_context_tree(host, read, true, None, |list, tree, arena| {+ *out = with_hit_test_list_spatial_indexes_and_visual_context_tree(host, read, None, |list, tree, arena| {let world = callbacks.build_world_transforms(tree);list.caret_position_from_point(- &HostNodeScopes {- main_thread: &main_thread,- callbacks: &callbacks,- },arena,tree,&callbacks.with_world_transforms(&world),point.into(),- mode,constraint_scope,)})diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rsindex a79cbbb91c3..bd416daec5c 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs@@ -5,804 +5,341 @@*/use super::*;-use crate::painting::host::{- FfiCaretAt, FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiNodeIdentity, FfiResolvedCaret,-};-use crate::painting::paint_read::PaintRead;-use crate::painting::viewport_mapping::ViewportSpace;-use crate::painting::visual_context::{ClipBehavior, SpatialNodeIndex};+use crate::layout::node_data::{DomPaintFact, NodeFlag, NodeKind};+use crate::layout::query::inline_cursor::{CaretPosition, InlineCursor};+use crate::painting::host::{FfiCaretAt, FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiResolvedCaret};+use crate::painting::paint_read::{PaintRead, PaintRow};+use crate::painting::paintable_data::FragmentRecord;+use crate::painting::viewport_mapping::{ViewportMapping, ViewportSpace};+use crate::painting::visual_context::ClipBehavior;+use crate::painting::{node_painting, paintable_geometry, style_queries};-/// What a caret query reads of the DOM: which nodes a scope holds.-pub(crate) trait NodeScopes {- /// Whether `node` is `ancestor` or one of its descendants in the DOM.- fn contains(&self, ancestor: FfiNodeIdentity, node: FfiNodeIdentity) -> bool;-}--/// The host's answers, which only its thread reaches.-pub(crate) struct HostNodeScopes<'a> {- pub(crate) main_thread: &'a crate::stage::MainThread<'a>,- pub(crate) callbacks: &'a FfiHitTestQueryCallbacks,-}--impl NodeScopes for HostNodeScopes<'_> {- fn contains(&self, ancestor: FfiNodeIdentity, node: FfiNodeIdentity) -> bool {- self.callbacks.contains(self.main_thread, ancestor, node)- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum CaretPositionType {- Closest,- Before,- After,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-pub enum CaretPositionMode {- Normal = 0,- SelectionStart = 1,- Selection = 2,-}--impl CaretPositionMode {- pub fn from_u8(value: u8) -> Self {- match value {- value if value == Self::SelectionStart as u8 => Self::SelectionStart,- value if value == Self::Selection as u8 => Self::Selection,- _ => Self::Normal,+impl HitTestList {+ /// The caret position at `point`: the one the box the point hits gives it, as editing resolves a point, or with a+ /// `constraint_scope` box, the one that box gives it wherever the point is.+ pub(crate) fn caret_position_from_point(+ &self,+ arena: &impl PaintRead,+ tree: &VisualContextTree,+ callbacks: &FfiHitTestQueryCallbacks,+ point: CssPixelPoint,+ constraint_scope: NodeSlotId,+ ) -> Option<FfiCaretAt> {+ let resolver = PointResolver {+ arena,+ mapping: callbacks.viewport_mapping(tree),+ point,+ };+ if !constraint_scope.is_invalid() {+ let mut scope = constraint_scope;+ while !arena.paintable_row_is_populated(scope) {+ scope = arena.node_parent_if_live(scope)?;+ }+ return resolver.in_box(scope);}- }-}--// Treat small block-axis gaps between caret line fragments as the same visual row.-const CARET_LINE_BLOCK_AXIS_RANGE_SLOP: i64 = 4;-// Prefer a nearby line in the same visual column over a slightly closer line in another column.-const CARET_LINE_BLOCK_AXIS_COMPARE_SLOP: i64 = 12;-// Within the chosen line, tolerate larger block-axis differences before snapping across inline gaps.-const CARET_ITEM_BLOCK_AXIS_COMPARE_SLOP: i64 = 32;--fn px(value: i64) -> CssPixels {- CssPixels::from_integer(value)-}-fn distance_to_range(coordinate: CssPixels, start: CssPixels, end: CssPixels) -> CssPixels {- if coordinate < start {- return start - coordinate;- }- if coordinate > end {- return coordinate - end;- }- CssPixels::from_raw(0)-}--fn block_axis_distance_to_line_rect(rect: CssPixelRect, point: CssPixelPoint, writing_mode: u8) -> CssPixels {- distance_to_range(- block_axis_coordinate(point, writing_mode),- block_axis_start(rect, writing_mode) - px(CARET_LINE_BLOCK_AXIS_RANGE_SLOP),- block_axis_end(rect, writing_mode) + px(CARET_LINE_BLOCK_AXIS_RANGE_SLOP),- )-}--fn inline_axis_distance_to_rect(rect: CssPixelRect, point: CssPixelPoint, writing_mode: u8) -> CssPixels {- distance_to_range(- inline_axis_coordinate(point, writing_mode),- inline_axis_start(rect, writing_mode),- inline_axis_end(rect, writing_mode),- )-}--fn absolute_difference(a: CssPixels, b: CssPixels) -> CssPixels {- if a > b { a - b } else { b - a }-}--fn caret_line_is_better_candidate(- block_distance: CssPixels,- inline_distance: CssPixels,- closest_block_distance: CssPixels,- closest_inline_distance: CssPixels,- block_axis_compare_slop: CssPixels,-) -> bool {- if absolute_difference(block_distance, closest_block_distance) <= block_axis_compare_slop {- if inline_distance != closest_inline_distance {- return inline_distance < closest_inline_distance;+ // A point that hits nothing, such as one past the edge of the viewport during a drag, goes to the viewport.+ let Some(hit) = self.find_topmost_item(arena, tree, callbacks, point) else {+ let mut viewport = self.items.first()?.paintable;+ while let Some(parent) = arena.node_parent_if_live(viewport) {+ viewport = parent;+ }+ return resolver.in_box(viewport);+ };+ let item = &self.items[hit.index];+ let caret = match item.kind {+ HitTestItemKind::TextFragment => resolver.in_lines_of(item.paintable),+ HitTestItemKind::Box | HitTestItemKind::EmptyEditable | HitTestItemKind::ChromeWidget => {+ resolver.in_box(item.paintable)+ }+ HitTestItemKind::SvgPath | HitTestItemKind::EmptyLine => Some(resolver.at_start_of(item.paintable)),+ };+ if let Some(caret) = caret.filter(|caret| caret.caret.has_position) {+ return Some(caret);}- return block_distance < closest_block_distance;+ // Generated content, such as a list marker, gives no position, and the nearest box around it that stands for a+ // node takes the point.+ let mut node = arena.node_parent_if_live(item.paintable)?;+ while !arena.node_is_dom_backed(node) {+ node = arena.node_parent_if_live(node)?;+ }+ resolver.in_box(node)}- block_distance < closest_block_distance}-#[derive(Clone, Copy, Debug)]-pub struct ClosestLine {- pub index: Option<usize>,- pub local_point: CssPixelPoint,- pub block_distance: CssPixels,- pub block_start_distance: CssPixels,- pub inline_distance: CssPixels,- pub block_container: NodeSlotId,- pub box_fragment: u32,- pub fragment_inline_distance: CssPixels,- pub is_before_point: bool,- pub contains_point_in_block_axis: bool,+/// Resolves a point, in the viewport, to a caret position the way a box gives one for a point over it.+struct PointResolver<'a, A: PaintRead> {+ arena: &'a A,+ mapping: ViewportMapping<'a>,+ point: CssPixelPoint,}-impl Default for ClosestLine {- fn default() -> Self {- Self {- index: None,- local_point: CssPixelPoint::default(),- block_distance: CssPixels::from_raw(i32::MAX),- block_start_distance: CssPixels::from_raw(i32::MAX),- inline_distance: CssPixels::from_raw(i32::MAX),- block_container: NodeSlotId::INVALID,- box_fragment: 0,- fragment_inline_distance: CssPixels::default(),- is_before_point: false,- contains_point_in_block_axis: false,- }+impl<A: PaintRead> PointResolver<'_, A> {+ /// The point in the space `node` lays out its descendants in.+ fn point_in_descendants_space_of(&self, node: NodeSlotId) -> Option<CssPixelPoint> {+ let context = self+ .arena+ .paintable_data(node)+ .accumulated_visual_context_for_descendants;+ self.mapping+ .point_to_local(context, self.point, ViewportSpace::VisualViewport, ClipBehavior::Ignore)+ .map(to_css_point)}-}-impl HitTestList {- pub fn box_point_is_before(&self, item_index: usize, local_point: CssPixelPoint) -> bool {- let item = &self.items[item_index];- debug_assert_eq!(item.kind, HitTestItemKind::Box);+ fn in_lines_of(&self, root: NodeSlotId) -> Option<FfiCaretAt> {+ let arena = self.arena;+ let point = self.point_in_descendants_space_of(root)?;+ let produces_caret = |fragment: &FragmentRecord| arena.node_is_dom_backed(fragment.layout_node);+ let position = InlineCursor::new(arena).position_for_point(root, point, &produces_caret)?;+ Some(self.caret_at(root, position))+ }- let block_coordinate = block_axis_coordinate(local_point, item.writing_mode);- if block_coordinate < block_axis_start(item.rect, item.writing_mode) {- return !item.block_axis_is_reverse;+ /// The caret position the box `node` gives the point: in its lines, beside it where it is replaced, in the block+ /// child the point is over or next to, or at its start.+ fn in_box(&self, node: NodeSlotId) -> Option<FfiCaretAt> {+ let arena = self.arena;+ if style_queries::is_replaced_box(arena, node) {+ return self.beside_replaced_box(node);}- if block_coordinate >= block_axis_end(item.rect, item.writing_mode) {- return item.block_axis_is_reverse;+ if node_painting::is_fragmented_inline(arena, node) {+ return self.in_box(arena.node_containing_block_if_live(node)?);}-- let inline_start = inline_axis_start(item.rect, item.writing_mode);- let inline_end = inline_axis_end(item.rect, item.writing_mode);- let inline_middle = inline_start + (inline_end - inline_start).scaled(0.5);- let inline_coordinate = inline_axis_coordinate(local_point, item.writing_mode);- if item.inline_axis_is_reverse {- inline_coordinate > inline_middle- } else {- inline_coordinate <= inline_middle+ if arena.node_flags_if_live(node) & NodeFlag::ChildrenAreInline as u32 != 0 {+ return self.in_lines_of(node).or_else(|| Some(self.at_start_of(node)));+ }+ if let Some(caret) = self.in_block_child_of(node) {+ return Some(caret);}+ Some(self.at_start_of(node))}- fn first_item_of_line(&self, line: &CaretLine) -> &HitTestItem {- &self.items[self.caret_item_indices[line.first_caret_item_index]]+ // A point before the line of a replaced box in the block direction, or over its first half, is before it.+ fn beside_replaced_box(&self, node: NodeSlotId) -> Option<FfiCaretAt> {+ let arena = self.arena;+ let context = arena.paintable_data(node).accumulated_visual_context;+ let point = self+ .mapping+ .point_to_local(context, self.point, ViewportSpace::VisualViewport, ClipBehavior::Ignore)+ .map(to_css_point)?;+ let rect = paintable_geometry::absolute_rect(arena, node);+ let style = arena.node_style_if_live(node)?;+ let horizontal = style.writing_mode() == crate::css::css_enums::writing_mode::HORIZONTAL_TB;+ let (inline, inline_start, inline_size, block, block_start, block_end) = if horizontal {+ (point.x, rect.x, rect.width, point.y, rect.y, rect.bottom())+ } else {+ (point.y, rect.y, rect.height, point.x, rect.x, rect.right())+ };+ let after = if block < block_start {+ style.block_axis_is_reverse()+ } else if block >= block_end {+ !style.block_axis_is_reverse()+ } else {+ (inline - inline_start > inline_size.scaled(0.5)) != style.inline_axis_is_reverse()+ };+ Some(self.caret_at(node, CaretPosition::BesideAtomicInline { node, after }))}- pub fn item_at_line_edge(&self, line_index: usize, position_type: CaretPositionType) -> usize {- // Choose the furthest caret-capable painted item along the logical inline axis. Display-list order and DOM- // order don't necessarily describe that edge.- debug_assert!(self.caret_lines_built);- let line = self.caret_lines[line_index].clone();- let first_item = self.first_item_of_line(&line);- let writing_mode = first_item.writing_mode;- let inline_axis_is_reverse = first_item.inline_axis_is_reverse;- let coordinate_for_item = |item: &HitTestItem| -> CssPixels {- if position_type == CaretPositionType::Before {- return if inline_axis_is_reverse {- inline_axis_end(item.caret_rect, writing_mode)- } else {- inline_axis_start(item.caret_rect, writing_mode)- };- }- if inline_axis_is_reverse {- inline_axis_start(item.caret_rect, writing_mode)- } else {- inline_axis_end(item.caret_rect, writing_mode)- }+ /// The caret position the block child of `node` that the point is over, or the last one it is past, gives it. A+ /// child whose editability differs from that of `node` takes it beside itself instead.+ fn in_block_child_of(&self, node: NodeSlotId) -> Option<FfiCaretAt> {+ let arena = self.arena;+ let point = self.point_in_descendants_space_of(node)?;+ let style = arena.node_style_if_live(node)?;+ let horizontal = style.writing_mode() == crate::css::css_enums::writing_mode::HORIZONTAL_TB;+ let block_axis_is_reverse = style.block_axis_is_reverse();+ // Block coordinates that grow in the block direction.+ let block_extent = |rect: CssPixelRect| match (horizontal, block_axis_is_reverse) {+ (true, _) => (rect.y, rect.bottom()),+ (false, false) => (rect.x, rect.right()),+ (false, true) => (-rect.right(), -rect.x),};- let coordinate_is_closer_to_line_edge = |coordinate: CssPixels, best_coordinate: CssPixels| -> bool {- if position_type == CaretPositionType::Before {- return if inline_axis_is_reverse {- coordinate > best_coordinate- } else {- coordinate < best_coordinate- };- }- if inline_axis_is_reverse {- coordinate < best_coordinate+ let inline_extent = |rect: &CssPixelRect| {+ if horizontal {+ (rect.x, rect.right())} else {- coordinate > best_coordinate+ (rect.y, rect.bottom())}};- let first_index = self.caret_item_indices[line.first_caret_item_index];- let mut best_item_index = first_index;- let mut best_coordinate = coordinate_for_item(&self.items[first_index]);- let item_is_on_line = |item: &HitTestItem| -> bool {- if let Some(recorded_line) = first_item.recorded_caret_line() {- return item.recorded_caret_line() == Some(recorded_line);- }- if line.context != item.context || first_item.containing_block != item.containing_block {- return false;- }- if item.caret_line_index.is_none() {- return rects_overlap_in_block_axis(line.rect, item.caret_rect, writing_mode);- }- false+ let fragments_of = |child: NodeSlotId| {+ (0..paintable_geometry::fragment_count(arena, child))+ .map(move |index| (child, paintable_geometry::absolute_fragment_rect(arena, child, index)))};- // Items without a recorded line identity can still belong to the same- // inferred visual line even when other caret runs separate them.- for item_index in &self.caret_item_indices {- let item = &self.items[*item_index];- if !item_is_on_line(item) {- continue;- }- let coordinate = coordinate_for_item(item);- if coordinate_is_closer_to_line_edge(coordinate, best_coordinate) {- best_item_index = *item_index;- best_coordinate = coordinate;- }- }- best_item_index- }-- pub(crate) fn caret_item_for_line(- &self,- arena: &impl PaintRead,- line_index: usize,- local_point: CssPixelPoint,- mode: CaretPositionMode,- ) -> Option<(usize, CaretPositionType)> {- debug_assert!(self.caret_lines_built);- let rows = arena;- let line = self.caret_lines[line_index].clone();- let first_item = self.first_item_of_line(&line);- let writing_mode = first_item.writing_mode;- let inline_axis_is_reverse = first_item.inline_axis_is_reverse;-- let block_coordinate = block_axis_coordinate(local_point, writing_mode);- // Once a line has been selected, points before or after its block-axis range resolve to- // the logical line edges. Points inside the line range resolve to the closest caret-capable- // item on that line.- if block_coordinate < block_axis_start(line.rect, writing_mode) {- return Some((- self.item_at_line_edge(line_index, CaretPositionType::Before),- CaretPositionType::Before,- ));- }- let inline_coordinate = inline_axis_coordinate(local_point, writing_mode);- if mode == CaretPositionMode::Selection && block_coordinate >= block_axis_end(line.rect, writing_mode) {- return Some((- self.item_at_line_edge(line_index, CaretPositionType::After),- CaretPositionType::After,- ));- }- if block_coordinate >= block_axis_end(line.rect, writing_mode) + px(CARET_LINE_BLOCK_AXIS_COMPARE_SLOP) {- return Some((- self.item_at_line_edge(line_index, CaretPositionType::After),- CaretPositionType::After,- ));- }- if block_coordinate >= block_axis_end(line.rect, writing_mode)- && (inline_coordinate < inline_axis_start(line.rect, writing_mode)- || inline_coordinate >= inline_axis_end(line.rect, writing_mode))- {- return Some((- self.item_at_line_edge(line_index, CaretPositionType::After),- CaretPositionType::After,- ));- }- // Points past either inline edge resolve to the corresponding logical line edge.- if inline_coordinate < inline_axis_start(line.rect, writing_mode) {- let position_type = if inline_axis_is_reverse {- CaretPositionType::After- } else {- CaretPositionType::Before+ let children = || {+ arena+ .children(node)+ .filter(|&child| arena.paintable_row_is_populated(child))+ };+ let mut candidates: Vec<(NodeSlotId, CssPixelRect)> = children()+ .filter(|&child| {+ arena+ .node(child)+ .is_some_and(|row| !row.is_out_of_flow() && !row.is_floating())+ })+ .flat_map(fragments_of)+ .filter(|(_, rect)| !rect.is_empty())+ .collect();+ // A block flow takes the first child that ends past the point in the block direction, or the last one where the+ // point is past its start; other boxes take the child nearest the point.+ let is_block_flow = !matches!(style.display(), display if display.is_flex_inside() || display.is_grid_inside() || display.is_table_inside());+ // Children laid out in columns take the point in the column it is in, or else the one nearest to it.+ let inline = if horizontal { point.x } else { point.y };+ // Children are in columns where two of them side by side overlap in the block direction.+ let mut extents: Vec<_> = candidates+ .iter()+ .map(|(_, rect)| (block_extent(*rect), inline_extent(rect)))+ .collect();+ extents.sort_by_key(|((block_start, _), _)| *block_start);+ let in_columns = is_block_flow+ && extents.windows(2).any(|pair| {+ let (+ ((_, first_block_end), (first_start, first_end)),+ ((second_block_start, _), (second_start, second_end)),+ ) = (pair[0], pair[1]);+ second_block_start < first_block_end && (second_start >= first_end || first_start >= second_end)+ });+ if in_columns {+ let distance = |rect: &CssPixelRect| {+ let (start, end) = inline_extent(rect);+ (start - inline)+ .max(inline - end + CssPixels::from_integer(1))+ .max(CssPixels::default())};- return Some((self.item_at_line_edge(line_index, position_type), position_type));+ let nearest = candidates+ .iter()+ .map(|(_, rect)| distance(rect))+ .min()+ .unwrap_or_default();+ candidates.retain(|(_, rect)| distance(rect) == nearest);}- if inline_coordinate >= inline_axis_end(line.rect, writing_mode) {- let position_type = if inline_axis_is_reverse {- CaretPositionType::Before- } else {- CaretPositionType::After+ // The point covers the pixel after it.+ let one = CssPixels::from_integer(1);+ let point_rect = CssPixelRect::new(point.x, point.y, one, one);+ let block = block_extent(point_rect).0;+ let distance = |rect: &CssPixelRect| {+ let gap = |start: CssPixels, end: CssPixels, point_start: CssPixels, point_end: CssPixels| {+ (start - point_start)+ .max(point_end - end)+ .max(CssPixels::default())+ .to_double()};- return Some((self.item_at_line_edge(line_index, position_type), position_type));- }-- let mut closest_item_index: Option<usize> = None;- let mut closest_block_distance = CssPixels::from_raw(i32::MAX);- let mut closest_inline_distance = CssPixels::from_raw(i32::MAX);- for caret_item_index in line.first_caret_item_index..=line.last_caret_item_index {- let item_index = self.caret_item_indices[caret_item_index];- let item = &self.items[item_index];- let item_writing_mode = item.writing_mode;- let block_distance = block_axis_distance_to_line_rect(- Self::caret_line_rect_for_item(rows, item),- local_point,- item_writing_mode,- );- let inline_distance = inline_axis_distance_to_rect(item.caret_rect, local_point, item_writing_mode);- if closest_item_index.is_none()- || caret_line_is_better_candidate(- block_distance,- inline_distance,- closest_block_distance,- closest_inline_distance,- px(CARET_ITEM_BLOCK_AXIS_COMPARE_SLOP),- )- {- closest_item_index = Some(item_index);- closest_block_distance = block_distance;- closest_inline_distance = inline_distance;- }- }- closest_item_index.map(|index| (index, CaretPositionType::Closest))- }-- pub fn item_is_inline_adjacent_to_line(&self, item_index: usize, line_index: usize) -> bool {- debug_assert!(self.caret_lines_built);- let item = &self.items[item_index];- let line = &self.caret_lines[line_index];- if item.context != line.context || item.rect.is_empty() {- return false;- }- let writing_mode = self.first_item_of_line(line).writing_mode;- if !rects_overlap_in_block_axis(item.rect, line.rect, writing_mode) {- return false;- }- inline_axis_end(item.rect, writing_mode) <= inline_axis_start(line.rect, writing_mode)- || inline_axis_end(line.rect, writing_mode) <= inline_axis_start(item.rect, writing_mode)- }-- fn line_in_scope(- &self,- scopes: &impl NodeScopes,- arena: &impl PaintRead,- line_index: usize,- scope: FfiNodeIdentity,- ) -> bool {- let line = &self.caret_lines[line_index];- for caret_item_index in line.first_caret_item_index..=line.last_caret_item_index {- let node = self.item_target(arena, self.caret_item_indices[caret_item_index]);- if !node.is_none() && scopes.contains(scope, node) {- return true;- }+ let horizontal_gap = gap(rect.x, rect.right(), point_rect.x, point_rect.right());+ let vertical_gap = gap(rect.y, rect.bottom(), point_rect.y, point_rect.bottom());+ horizontal_gap * horizontal_gap + vertical_gap * vertical_gap+ };+ if candidates.is_empty() {+ return self.in_nearest_positioned_child_of(node, point, &distance);}- false- }-- #[allow(clippy::too_many_arguments)]- pub(crate) fn find_closest_line(- &self,- scopes: &impl NodeScopes,- arena: &impl PaintRead,- visual_context_tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- point: CssPixelPoint,- mode: CaretPositionMode,- scope: FfiNodeIdentity,- respect_clip: bool,- block_container: NodeSlotId,- ) -> ClosestLine {- debug_assert!(self.caret_lines_built);- let rows = arena;- let mut closest_line = ClosestLine::default();- let mut closest_line_after_point = ClosestLine::default();- let mut closest_line_before_point = ClosestLine::default();-- let line_after_point_is_better_candidate = |block_start_distance: CssPixels,- inline_distance: CssPixels,- closest_block_start_distance: CssPixels,- closest_inline_distance: CssPixels|- -> bool {- if absolute_difference(block_start_distance, closest_block_start_distance)- <= px(CARET_LINE_BLOCK_AXIS_COMPARE_SLOP)- {- if inline_distance != closest_inline_distance {- return inline_distance < closest_inline_distance;- }- return block_start_distance < closest_block_start_distance;- }- block_start_distance < closest_block_start_distance+ let &(child, rect) = if is_block_flow {+ candidates+ .last()+ .filter(|(_, rect)| block >= block_extent(*rect).0)+ .or_else(|| candidates.iter().find(|(_, rect)| block < block_extent(*rect).1))?+ } else {+ candidates+ .iter()+ .min_by(|(_, a), (_, b)| distance(a).total_cmp(&distance(b)))?};-- for line_index in 0..self.caret_lines.len() {- if !scope.is_none() && !self.line_in_scope(scopes, arena, line_index, scope) {- continue;- }- if !block_container.is_invalid() && self.caret_lines[line_index].block_container != block_container {- continue;- }- let line = self.caret_lines[line_index].clone();- let Some(local) = callbacks.viewport_mapping(visual_context_tree).point_to_local(- line.context,- point,- ViewportSpace::VisualViewport,- ClipBehavior::from_respect_clip(respect_clip),- ) else {- continue;- };- let local_point = to_css_point(local);- let writing_mode = self.first_item_of_line(&line).writing_mode;- let block_distance = block_axis_distance_to_line_rect(line.rect, local_point, writing_mode);- let block_coordinate = block_axis_coordinate(local_point, writing_mode);- let inline_distance = inline_axis_distance_to_rect(line.rect, local_point, writing_mode);- let contains_point_in_block_axis = block_coordinate >= block_axis_start(line.rect, writing_mode)- && block_coordinate < block_axis_end(line.rect, writing_mode);- let fragment_inline_distance = if line.block_container.is_invalid()- || !rows.paintable_row_is_populated(line.block_container)- || crate::painting::paintable_geometry::fragment_count(rows, line.block_container) == 1- {- CssPixels::default()+ let is_editable = |node| arena.node_has_dom_paint_fact(node, DomPaintFact::EditableOrEditingHost);+ let is_root_element = arena+ .node_parent_if_live(node)+ .is_some_and(|parent| arena.node_kind_if_live(parent) == Some(NodeKind::Viewport));+ // A column stands for no node, and so the boxes in it keep the point whatever their editability.+ if arena.node_is_dom_backed(child)+ && arena.node_is_dom_backed(node)+ && !is_root_element+ && !in_columns+ && is_editable(child) != is_editable(node)+ {+ let (inline, inline_start, inline_size) = if horizontal {+ (point.x, rect.x, rect.width)} else {- inline_axis_distance_to_rect(- crate::painting::paintable_geometry::absolute_fragment_rect(- rows,- line.block_container,- line.box_fragment as usize,- ),- local_point,- writing_mode,- )- };- let in_other_fragment_of_same_block_container = |closest: &ClosestLine| {- !line.block_container.is_invalid()- && line.block_container == closest.block_container- && line.box_fragment != closest.box_fragment- && fragment_inline_distance != closest.fragment_inline_distance- };- let is_better_candidate = {- if closest_line.index.is_none() {- true- } else if in_other_fragment_of_same_block_container(&closest_line) {- fragment_inline_distance < closest_line.fragment_inline_distance- } else {- // Between lines of the same block container, a line whose block-axis range- // contains the point always beats lines that do not.- let same_block_container =- !line.block_container.is_invalid() && line.block_container == closest_line.block_container;- if same_block_container && contains_point_in_block_axis != closest_line.contains_point_in_block_axis- {- contains_point_in_block_axis- } else {- caret_line_is_better_candidate(- block_distance,- inline_distance,- closest_line.block_distance,- closest_line.inline_distance,- px(CARET_LINE_BLOCK_AXIS_COMPARE_SLOP),- )- }- }+ (point.y, rect.y, rect.height)};- if is_better_candidate {- closest_line.index = Some(line_index);- closest_line.local_point = local_point;- closest_line.block_distance = block_distance;- closest_line.inline_distance = inline_distance;- closest_line.block_container = line.block_container;- closest_line.box_fragment = line.box_fragment;- closest_line.fragment_inline_distance = fragment_inline_distance;- closest_line.is_before_point = block_axis_end(line.rect, writing_mode) < block_coordinate;- closest_line.contains_point_in_block_axis = contains_point_in_block_axis;- }-- if block_axis_end(line.rect, writing_mode) < block_coordinate- && (closest_line_before_point.index.is_none()- || if in_other_fragment_of_same_block_container(&closest_line_before_point) {- fragment_inline_distance < closest_line_before_point.fragment_inline_distance- } else {- caret_line_is_better_candidate(- block_distance,- inline_distance,- closest_line_before_point.block_distance,- closest_line_before_point.inline_distance,- px(CARET_LINE_BLOCK_AXIS_COMPARE_SLOP),- )- })- {- closest_line_before_point.index = Some(line_index);- closest_line_before_point.local_point = local_point;- closest_line_before_point.block_distance = block_distance;- closest_line_before_point.inline_distance = inline_distance;- closest_line_before_point.block_container = line.block_container;- closest_line_before_point.box_fragment = line.box_fragment;- closest_line_before_point.fragment_inline_distance = fragment_inline_distance;- closest_line_before_point.is_before_point = true;- }-- let block_start = block_axis_start(line.rect, writing_mode);- if block_start <= block_coordinate {- continue;- }- // Keep track of the nearest following line separately.- let block_start_distance = block_start - block_coordinate;- if closest_line_after_point.index.is_none()- || line_after_point_is_better_candidate(- block_start_distance,- inline_distance,- closest_line_after_point.block_start_distance,- closest_line_after_point.inline_distance,- )- {- closest_line_after_point.index = Some(line_index);- closest_line_after_point.local_point = local_point;- closest_line_after_point.block_distance = block_distance;- closest_line_after_point.block_start_distance = block_start_distance;- closest_line_after_point.inline_distance = inline_distance;- closest_line_after_point.block_container = line.block_container;- }- }-- if mode == CaretPositionMode::SelectionStart- && !closest_line.contains_point_in_block_axis- && closest_line_before_point.index.is_some()- && closest_line.index != closest_line_before_point.index- && closest_line_before_point.block_distance <= px(CARET_ITEM_BLOCK_AXIS_COMPARE_SLOP)- {- return closest_line_before_point;- }-- if let Some(closest_index) = closest_line.index- && closest_line.is_before_point- && closest_line_after_point.index.is_some()- && closest_line_after_point.block_distance <= px(CARET_LINE_BLOCK_AXIS_COMPARE_SLOP)- && closest_line_after_point.inline_distance <= closest_line.inline_distance- {- let line = &self.caret_lines[closest_index];- let writing_mode = self.first_item_of_line(line).writing_mode;- let block_coordinate = block_axis_coordinate(closest_line.local_point, writing_mode);- let point_is_in_closest_line_block_container_margin = super::geometry::block_container_margin_rect(- rows,- closest_line.block_container,- closest_line.box_fragment,- )- .is_some_and(|rect| block_coordinate < block_axis_end(rect, writing_mode));- let lines_share_block_container = !closest_line.block_container.is_invalid()- && closest_line.block_container == closest_line_after_point.block_container;- // A point still inside the previous block container's margin box should not jump to- // text in a different block container, even if that following line is close.- if point_is_in_closest_line_block_container_margin && !lines_share_block_container {- return closest_line;- }- return closest_line_after_point;+ let after = inline - inline_start >= inline_size.scaled(0.5);+ return Some(self.caret_at(node, CaretPosition::BesideAtomicInline { node: child, after }));}- closest_line- }-}--impl FfiCaretAt {- // Moves the debug rect from the local space of `spatial` into the viewport.- fn with_debug_rect_in_viewport(- mut self,- tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- spatial: SpatialNodeIndex,- ) -> Self {- if self.caret.has_debug_rect {- self.caret.debug_rect = callbacks- .viewport_mapping(tree)- .rect_in_space_to_viewport(spatial, self.caret.debug_rect.into(), ViewportSpace::VisualViewport)- .into();- }- self- }-}--impl HitTestList {- fn item_is_direct_caret_target(&self, arena: &impl PaintRead, item_index: usize) -> bool {- let target = self.item_target(arena, item_index);- !target.is_none() && target == self.item_dispatch_target(arena, item_index)+ self.in_box(child)}- fn caret_at_item(+ // INTEROP: A box with no in-flow child that has a size takes the point in the child nearest to it, of any kind, by+ // its geometry before its transform.+ fn in_nearest_positioned_child_of(&self,- arena: &impl PaintRead,- item_index: usize,- local_point: CssPixelPoint,- position_type: CaretPositionType,+ node: NodeSlotId,+ point: CssPixelPoint,+ distance: &dyn Fn(&CssPixelRect) -> f64,) -> Option<FfiCaretAt> {- let caret = self.resolve_caret(arena, item_index, local_point, position_type);- caret.has_position.then_some(FfiCaretAt {- paintable: self.items[item_index].paintable,- caret,- })+ let arena = self.arena;+ let child = arena+ .children(node)+ .filter(|&child| arena.paintable_row_is_populated(child) && arena.node_is_dom_backed(child))+ .min_by(|&a, &b| {+ distance(&paintable_geometry::absolute_rect(arena, a))+ .total_cmp(&distance(&paintable_geometry::absolute_rect(arena, b)))+ })?;+ let produces_caret = |fragment: &FragmentRecord| arena.node_is_dom_backed(fragment.layout_node);+ let position = node_painting::has_lines(arena, child)+ .then(|| InlineCursor::new(arena).position_for_point(child, point, &produces_caret))+ .flatten()+ .unwrap_or(CaretPosition::StartOfBox { node: child });+ Some(self.caret_at(child, position))}- fn caret_at_line(- &self,- arena: &impl PaintRead,- line_index: usize,- local_point: CssPixelPoint,- mode: CaretPositionMode,- ) -> Option<FfiCaretAt> {- let (item_index, position_type) = self.caret_item_for_line(arena, line_index, local_point, mode)?;- self.caret_at_item(arena, item_index, local_point, position_type)+ fn at_start_of(&self, node: NodeSlotId) -> FfiCaretAt {+ self.caret_at(node, CaretPosition::StartOfBox { node })}- // The start of the node the item stands for, for a hit on an item that produces no caret position itself.- fn caret_at_hit_container(&self, arena: &impl PaintRead, item_index: usize) -> Option<FfiCaretAt> {- let node = self.item_target(arena, item_index);- if node.is_none() {- return None;- }- let item = &self.items[item_index];- Some(FfiCaretAt {- paintable: item.paintable,- caret: FfiResolvedCaret {- has_position: true,- node,- has_debug_rect: true,- debug_rect: item.caret_rect.into(),+ fn caret_at(&self, paintable: NodeSlotId, position: CaretPosition) -> FfiCaretAt {+ let arena = self.arena;+ let identity = |node| resolve::row_node_identity(arena, node, false);+ let mut caret = match position {+ CaretPosition::Text {+ text,+ offset,+ downstream,+ } => FfiResolvedCaret {+ node: identity(text),+ boundary: FfiCaretBoundaryKind::Offset,+ offset,+ affinity_is_upstream: !downstream,+ ..Default::default()+ },+ CaretPosition::BesideAtomicInline { node, after } => FfiResolvedCaret {+ node: identity(node),+ boundary: if after {+ FfiCaretBoundaryKind::AfterNode+ } else {+ FfiCaretBoundaryKind::BeforeNode+ },+ ..Default::default()+ },+ CaretPosition::BeforeForcedBreak { node } => FfiResolvedCaret {+ node: identity(node),+ boundary: FfiCaretBoundaryKind::IndexOfNodeInParent,+ ..Default::default()+ },+ CaretPosition::StartOfBox { node } => FfiResolvedCaret {+ node: identity(node),+ boundary: FfiCaretBoundaryKind::Offset,..Default::default()},- })- }-- // Whether the node of the caret's boundary is `ancestor` or one of its descendants. A boundary beside a node is- // inside that node's parent.- fn caret_boundary_is_inside(scopes: &impl NodeScopes, ancestor: FfiNodeIdentity, caret: &FfiResolvedCaret) -> bool {- let boundary_is_beside_node = caret.boundary != FfiCaretBoundaryKind::Offset;- (!boundary_is_beside_node || ancestor != caret.node) && scopes.contains(ancestor, caret.node)- }-- /// The caret position at `point`. When `constraint_scope` names a node, the position is constrained to lines inside- /// it, and points outside it resolve to the closest position within it.- #[allow(clippy::too_many_arguments)]- pub(crate) fn caret_position_from_point(- &self,- scopes: &impl NodeScopes,- arena: &impl PaintRead,- tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- point: CssPixelPoint,- mode: CaretPositionMode,- constraint_scope: FfiNodeIdentity,- ) -> Option<FfiCaretAt> {- let constrained = !constraint_scope.is_none();- // First find both the topmost hit-test item and the topmost item that can directly produce a caret.- // Non-caret items are still needed to keep later line fallback scoped to the hit content.- // FIXME: Caret placement compares items by record order alone, ignoring the depth-sorted paint order of- // planes inside 3D rendering contexts.- let (mut topmost_item, topmost_hit_item) = self.find_topmost_items_for_caret(arena, tree, callbacks, point);-- // A constrained search only accepts direct hits inside the constraint scope.- if constrained && let Some(item) = topmost_item {- let node = self.item_target(arena, item.index);- if node.is_none() || !scopes.contains(constraint_scope, node) {- topmost_item = None;- }- }-- // Direct caret hits win unless another non-caret item is visibly on top of them.- if let Some(item) = topmost_item {- let matches_hit_item = topmost_hit_item- .is_some_and(|hit| hit.index == item.index && self.item_is_direct_caret_target(arena, item.index));- if constrained || topmost_hit_item.is_none() || matches_hit_item {- // NB: A point inside an inline-block resolves to a position in the box's own lines, if it has any, as- // a point over any other block container's content does, rather than to a boundary beside the- // whole box.- if self.items[item.index].kind == HitTestItemKind::Box {- let inner_line = self.find_closest_line(- scopes,- arena,- tree,- callbacks,- point,- mode,- FfiNodeIdentity::default(),- !constrained,- self.items[item.index].paintable,- );- if let Some(line_index) = inner_line.index- && let Some(caret) = self.caret_at_line(arena, line_index, inner_line.local_point, mode)- {- return Some(caret.with_debug_rect_in_viewport(- tree,- callbacks,- self.caret_lines[line_index].context.spatial,- ));- }- }- if let Some(caret) = self.caret_at_item(arena, item.index, item.local_point, CaretPositionType::Closest)- {- return Some(caret.with_debug_rect_in_viewport(- tree,- callbacks,- self.items[item.index].context.spatial,- ));- }- }- }-- // If the point is over a non-caret item, only consider caret lines inside that item's event-dispatch node first.- // This prevents overlays or side content from snapping the caret to unrelated nearby text.- let line_scope = match topmost_hit_item {- _ if constrained => constraint_scope,- Some(hit)- if !self.items[hit.index].can_produce_caret_position- || !self.item_is_direct_caret_target(arena, hit.index) =>- {- self.item_dispatch_target(arena, hit.index)- }- _ => FfiNodeIdentity::default(),- };-- // A constrained search must find a line even when the point is outside the scope's clipped area (e.g. dragging- // a selection outside a textarea), so it transforms points without rejecting them against clips.- let respect_clip = !constrained;- let find_closest_line = |scope| {- self.find_closest_line(- scopes,- arena,- tree,- callbacks,- point,- mode,- scope,- respect_clip,- NodeSlotId::INVALID,- )- };- let mut closest_line = find_closest_line(line_scope);- let closest_line_in_scope = closest_line;- let point_is_in_column_of_closest_line = closest_line.index.is_some()- && closest_line.fragment_inline_distance == CssPixels::default()- && arena.paintable_row_is_populated(closest_line.block_container)- && crate::painting::paintable_geometry::fragment_count(arena, closest_line.block_container) > 1;- if !line_scope.is_none() && !constrained && !point_is_in_column_of_closest_line {- // The scoped search is only a guard against unrelated nearby content. If there is a plainly closer line- // outside the scope, use it instead.- let unscoped_closest_line = find_closest_line(FfiNodeIdentity::default());- if closest_line.index.is_none()- || (unscoped_closest_line.index.is_some()- && unscoped_closest_line.block_distance < closest_line.block_distance)- {- closest_line = unscoped_closest_line;- }- }-- let Some(line_index) = closest_line.index else {- let hit = topmost_hit_item.filter(|_| !constrained)?;- return self.caret_at_hit_container(arena, hit.index).map(|caret| {- caret.with_debug_rect_in_viewport(tree, callbacks, self.items[hit.index].context.spatial)- });};- let caret = self- .caret_at_line(arena, line_index, closest_line.local_point, mode)?- .with_debug_rect_in_viewport(tree, callbacks, self.caret_lines[line_index].context.spatial);-- if !constrained && let Some(hit) = topmost_hit_item {- let hit_target = self.item_dispatch_target(arena, hit.index);- if !hit_target.is_none()- && !caret.caret.node.is_none()- && !Self::caret_boundary_is_inside(scopes, hit_target, &caret.caret)- {- if self.items[hit.index].can_produce_caret_position- && self.item_is_direct_caret_target(arena, hit.index)- {- return self- .caret_at_item(arena, hit.index, hit.local_point, CaretPositionType::Closest)- .map(|caret| {- caret.with_debug_rect_in_viewport(tree, callbacks, self.items[hit.index].context.spatial)- });- }- if self.item_is_inline_adjacent_to_line(hit.index, line_index) {- return Some(caret);- }- // A selection doesn't follow the point into an overlay or side content: It stays in the hit element's- // own content, on its line closest to the point, as a closer line outside it took the place of. But a- // plain caret query over an element whose content has no line near the point (an empty line, e.g.)- // puts the caret at the start of that element, rather than on a line outside it.- if mode != CaretPositionMode::Normal {- let line_index_in_scope = closest_line_in_scope.index.filter(|&index| index != line_index)?;- return self- .caret_at_line(arena, line_index_in_scope, closest_line_in_scope.local_point, mode)- .map(|caret| {- caret.with_debug_rect_in_viewport(- tree,- callbacks,- self.caret_lines[line_index_in_scope].context.spatial,- )- });- }- return self.caret_at_hit_container(arena, hit.index).map(|caret| {- caret.with_debug_rect_in_viewport(tree, callbacks, self.items[hit.index].context.spatial)- });+ caret.has_position = !caret.node.is_none();+ if let Some(rect) = InlineCursor::new(arena).caret_rect(position) {+ caret.has_debug_rect = true;+ caret.debug_rect = if rect.owner == rect.node {+ self.mapping+ .rect_to_viewport(arena, rect.owner, rect.rect, ViewportSpace::VisualViewport)+ } else {+ self.mapping.line_content_rect_to_viewport(+ arena,+ rect.owner,+ rect.node,+ rect.rect,+ ViewportSpace::VisualViewport,+ )}+ .into();}- Some(caret)+ FfiCaretAt { paintable, caret }}}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/geometry.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/geometry.rsdeleted file mode 100644index c9781f0ede3..00000000000--- a/Libraries/LibWeb/Rust/src/painting/hit_test/geometry.rs+++ /dev/null@@ -1,94 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Geometry that belongs to a row other than the item's own: its block container and the line-//! box its caret sits on. Items carry only the ids of those rows, and a query resolves the-//! rects against the committed layout, so a copied item never goes stale when a containing-//! block or line root changes without the item's own row changing.--use super::{HitTestItem, HitTestItemKind};-use crate::css::css_pixels::{CssPixelRect, CssPixels};-use crate::layout::node_data::NodeSlotId;-use crate::painting::paint_read::PaintRead;-use crate::painting::{node_painting, paintable_geometry, text_fragment};--pub(crate) fn populated_block_container(rows: &impl PaintRead, block_container: NodeSlotId) -> NodeSlotId {- if block_container.is_invalid() || !rows.paintable_row_is_populated(block_container) {- return NodeSlotId::INVALID;- }- block_container-}--pub(crate) fn block_container_margin_rect(- rows: &impl PaintRead,- block_container: NodeSlotId,- box_fragment: u32,-) -> Option<CssPixelRect> {- if populated_block_container(rows, block_container).is_invalid() {- return None;- }- if box_fragment != 0 {- let margin = paintable_geometry::unbroken_box_model(rows, block_container).0;- let is_last_fragment = box_fragment as usize + 1 == paintable_geometry::fragment_count(rows, block_container);- return Some(- paintable_geometry::absolute_fragment_border_box_rect(rows, block_container, box_fragment as usize)- .inflated(- CssPixels::default(),- margin.right,- if is_last_fragment {- margin.bottom- } else {- CssPixels::default()- },- margin.left,- ),- );- }- let absolute = paintable_geometry::absolute_rect(rows, block_container);- let margin = paintable_geometry::committed_margin(rows, block_container);- let border = paintable_geometry::committed_border(rows, block_container);- let padding = paintable_geometry::committed_padding(rows, block_container);- let content_size = paintable_geometry::committed_content_size(rows, block_container);- let top = margin.top + border.top + padding.top;- let right = margin.right + border.right + padding.right;- let bottom = margin.bottom + border.bottom + padding.bottom;- let left = margin.left + border.left + padding.left;- Some(CssPixelRect::new(- absolute.x - left,- absolute.y - top,- content_size.width + left + right,- content_size.height + top + bottom,- ))-}--fn absolute_containing_line_box_rect(rows: &impl PaintRead, paintable: NodeSlotId) -> Option<CssPixelRect> {- let containing_line_box_index = paintable_geometry::committed_containing_line_box_index(rows, paintable)?;- let block = rows.paintable_data(paintable).containing_block;- if block.is_invalid() || !rows.paintable_row_is_populated(block) || !node_painting::has_lines(rows, block) {- return None;- }- let side_data = rows.committed_side_data(block);- let line = side_data.lines().get(containing_line_box_index)?;- Some(- CssPixelRect::from(line.rect).translated_by(paintable_geometry::absolute_line_root_position(- rows,- block,- containing_line_box_index,- )),- )-}--/// The line box the item's caret belongs to, for items whose line root is another row.-pub(crate) fn containing_line_box_rect(rows: &impl PaintRead, item: &HitTestItem) -> Option<CssPixelRect> {- match item.kind {- HitTestItemKind::TextFragment => super::resolve::with_item_fragment(rows, item, |fragment| {- text_fragment::absolute_line_box_rect(rows, item.paintable, fragment)- }),- HitTestItemKind::EmptyLine => Some(item.caret_rect),- HitTestItemKind::Box => absolute_containing_line_box_rect(rows, item.paintable),- HitTestItemKind::SvgPath | HitTestItemKind::EmptyEditable | HitTestItemKind::ChromeWidget => None,- }-}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rsindex bdc3b5503a5..b4a2728fdff 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/mod.rs@@ -5,7 +5,6 @@*/pub mod caret;-pub mod geometry;pub mod query;pub mod resolve;@@ -14,7 +13,6 @@ use crate::css::css_pixels::{CssPixelPoint, CssPixelRect};use crate::css::style::fast_hash::FastMap;use crate::layout::node_data::NodeSlotId;use crate::painting::display_list::commands::ContextRef;-use crate::painting::paint_read::PaintRead;use crate::painting::visual_context::VisualContextTree;use std::sync::Arc;@@ -65,13 +63,6 @@ pub struct HitTestItem {pub can_produce_caret_position: bool,}-impl HitTestItem {- fn recorded_caret_line(&self) -> Option<(ContextRef, NodeSlotId, usize)> {- self.caret_line_index- .map(|index| (self.context, self.block_container, index))- }-}-/// The areas of an SVG graphics element that pointer events can target.pub mod svg_hit_area {pub const FILL: u8 = 1 << 0;@@ -126,19 +117,6 @@ pub struct SpatialIndex {pub unbucketed_items: Vec<usize>,}-// A visual line assembled from caret-capable display-list items. Caret lines preserve painted-// topology independently of the spatial hit-test index so keyboard navigation can reason about lines that contain-// empty or zero-area caret targets. The block container is the first populated one among the line's items.-#[derive(Clone, Debug)]-pub struct CaretLine {- pub rect: CssPixelRect,- pub block_container: NodeSlotId,- pub box_fragment: u32,- pub context: ContextRef,- pub first_caret_item_index: usize,- pub last_caret_item_index: usize,-}-const SPATIAL_INDEX_CELL_SIZE: f64 = 128.0;const MAX_BUCKETED_CELLS_PER_ITEM: u64 = 64;@@ -150,31 +128,6 @@ pub fn spatial_index_cell_key(x: i32, y: i32) -> u64 {((x as u32 as u64) << 32) | (y as u32 as u64)}-pub fn writing_mode_is_horizontal(writing_mode: u8) -> bool {- writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB-}--pub fn block_axis_start(rect: CssPixelRect, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- rect.top()- } else {- rect.left()- }-}--pub fn block_axis_end(rect: CssPixelRect, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- rect.bottom()- } else {- rect.right()- }-}--pub fn rects_overlap_in_block_axis(a: CssPixelRect, b: CssPixelRect, writing_mode: u8) -> bool {- block_axis_start(a, writing_mode) < block_axis_end(b, writing_mode)- && block_axis_start(b, writing_mode) < block_axis_end(a, writing_mode)-}-#[derive(Default)]pub struct HitTestList {pub generation: u64,@@ -182,12 +135,8 @@ pub struct HitTestList {pub recorded_structural_epoch: u64,pub items: Arc<Vec<HitTestItem>>,pub item_capacity_hint_from_previous_list: usize,- /// Point queries read only the spatial indexes, and caret navigation reads only the caret lines,- /// which resolve line box geometry for every caret-capable item. Each is built on first use.+ /// Point queries read only the spatial indexes, which are built on first use.pub spatial_indexes_built: bool,- pub caret_lines_built: bool,- pub caret_item_indices: Vec<usize>,- pub caret_lines: Vec<CaretLine>,pub spatial_indexes_by_context: Vec<(ContextRef, SpatialIndex)>,pub spatial_index_position_by_context: FastMap<ContextRef, usize>,}@@ -195,8 +144,8 @@ pub struct HitTestList {impl HitTestList {pub fn append(&mut self, item: HitTestItem) {assert!(- !self.spatial_indexes_built && !self.caret_lines_built,- "hit-test item appended after the derived structures were built"+ !self.spatial_indexes_built,+ "hit-test item appended after the spatial indexes were built");let items = Arc::make_mut(&mut self.items);if items.capacity() == 0 {@@ -207,8 +156,8 @@ impl HitTestList {pub(crate) fn append_copies_of(&mut self, source: &[HitTestItem]) {assert!(- !self.spatial_indexes_built && !self.caret_lines_built,- "hit-test item appended after the derived structures were built"+ !self.spatial_indexes_built,+ "hit-test item appended after the spatial indexes were built");if source.is_empty() {return;@@ -220,37 +169,6 @@ impl HitTestList {items.extend_from_slice(source);}- fn box_fragment_of_caret_item(rows: &impl PaintRead, item: &HitTestItem) -> u32 {- let Some(line_index) = item.caret_line_index else {- return 0;- };- let line_root = match item.kind {- HitTestItemKind::TextFragment | HitTestItemKind::EmptyLine => item.paintable,- HitTestItemKind::Box => rows.paintable_data(item.paintable).containing_block,- HitTestItemKind::SvgPath | HitTestItemKind::EmptyEditable | HitTestItemKind::ChromeWidget => return 0,- };- if line_root.is_invalid() || !rows.paintable_row_is_populated(line_root) {- return 0;- }- rows.committed_side_data(line_root)- .lines()- .get(line_index)- .map_or(0, |line| line.box_fragment)- }-- pub(crate) fn caret_line_rect_for_item(rows: &impl PaintRead, item: &HitTestItem) -> CssPixelRect {- let Some(line_rect) = geometry::containing_line_box_rect(rows, item) else {- return item.caret_rect;- };- let mut rect = item.caret_rect;- if writing_mode_is_horizontal(item.writing_mode) {- rect.unite_vertically(line_rect);- } else {- rect.unite_horizontally(line_rect);- }- rect- }-pub(crate) fn build_spatial_indexes_if_needed(&mut self) {if self.spatial_indexes_built {return;@@ -264,38 +182,6 @@ impl HitTestList {}}- pub(crate) fn build_caret_lines_if_needed(&mut self, arena: &impl PaintRead) {- if self.caret_lines_built {- return;- }- self.caret_lines_built = true;- let rows = arena;- // Inline boxes and text from one layout line can be separated in paint order.- // Gather that line's caret targets together while preserving the order in- // which lines first appeared, and the paint order of targets within each line.- let mut group_by_line = FastMap::default();- let mut groups: Vec<smallvec::SmallVec<[usize; 4]>> = Vec::new();- for (item_index, item) in self.items.iter().enumerate() {- if item.caret_rect.is_empty() || !item.can_produce_caret_position {- continue;- }- let mut new_group = || {- groups.push(smallvec::SmallVec::new());- groups.len() - 1- };- let group = match item.recorded_caret_line() {- Some(line) => *group_by_line.entry(line).or_insert_with(new_group),- None => new_group(),- };- groups[group].push(item_index);- }- for group in groups {- for item_index in group {- self.add_item_to_caret_items(rows, item_index);- }- }- }-fn spatial_index_for(&mut self, context: ContextRef) -> &mut SpatialIndex {let items_arrive_in_runs_sharing_a_context = self.spatial_indexes_by_context@@ -350,76 +236,6 @@ impl HitTestList {}}}-- fn add_item_to_caret_items(&mut self, rows: &impl PaintRead, item_index: usize) {- let item = &self.items[item_index];- let caret_item_index = self.caret_item_indices.len();- self.caret_item_indices.push(item_index);-- let writing_mode = item.writing_mode;- let item_line_rect = Self::caret_line_rect_for_item(rows, item);- let item_block_container = geometry::populated_block_container(rows, item.block_container);- if let Some(line) = self.caret_lines.last_mut() {- let first_line_item = &self.items[self.caret_item_indices[line.first_caret_item_index]];- // Recorded lines belong to a line-producing block. Its layout containing- // block can be shared by several paragraphs, including their empty lines.- let same_recorded_line = item.recorded_caret_line().is_some()- && first_line_item.recorded_caret_line() == item.recorded_caret_line();- let same_inferred_line = first_line_item.caret_line_index.is_none()- && item.caret_line_index.is_none()- && first_line_item.containing_block == item.containing_block- && rects_overlap_in_block_axis(line.rect, item.caret_rect, writing_mode);- if line.context == item.context && (same_recorded_line || same_inferred_line) {- line.rect.unite(item_line_rect);- if line.block_container.is_invalid() {- line.block_container = item_block_container;- }- line.last_caret_item_index = caret_item_index;- return;- }- }-- self.caret_lines.push(CaretLine {- rect: item_line_rect,- block_container: item_block_container,- box_fragment: Self::box_fragment_of_caret_item(rows, item),- context: item.context,- first_caret_item_index: caret_item_index,- last_caret_item_index: caret_item_index,- });- }-}--pub fn block_axis_coordinate(point: CssPixelPoint, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- point.y- } else {- point.x- }-}--pub fn inline_axis_start(rect: CssPixelRect, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- rect.left()- } else {- rect.top()- }-}--pub fn inline_axis_end(rect: CssPixelRect, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- rect.right()- } else {- rect.bottom()- }-}--pub fn inline_axis_coordinate(point: CssPixelPoint, writing_mode: u8) -> CssPixels {- if writing_mode_is_horizontal(writing_mode) {- point.x- } else {- point.y- }}pub(crate) fn to_css_point(local: libgfx_rust::FloatPoint) -> CssPixelPoint {diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/query.rsindex 12be143beb5..fc5c04c5df3 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/query.rs@@ -88,11 +88,6 @@ pub struct TopmostItem {pub local_point: CssPixelPoint,}-struct TopmostSearch<'a> {- index: &'a mut Option<usize>,- caret_capable_only: bool,-}-impl HitTestList {fn item_contains(&self,@@ -169,21 +164,16 @@ impl HitTestList {callbacks: &FfiHitTestQueryCallbacks,item_indices: &[usize],local: FloatPoint,- search: TopmostSearch<'_>,+ topmost: &mut Option<usize>,) {for item_index in item_indices.iter().rev() {- if search.index.is_some_and(|topmost| *item_index <= topmost) {+ if topmost.is_some_and(|topmost| *item_index <= topmost) {return;}- let item = &self.items[*item_index];- if search.caret_capable_only && !item.can_produce_caret_position {- continue;- }- if !self.item_contains(layout_arena, callbacks, item, local) {- continue;+ if self.item_contains(layout_arena, callbacks, &self.items[*item_index], local) {+ *topmost = Some(*item_index);+ return;}- *search.index = Some(*item_index);- return;}}@@ -203,13 +193,10 @@ impl HitTestList {visual_context_tree: &VisualContextTree,callbacks: &FfiHitTestQueryCallbacks,point: CssPixelPoint,- with_caret_item: bool,- ) -> (Option<TopmostItem>, Option<TopmostItem>) {+ ) -> Option<TopmostItem> {debug_assert!(self.spatial_indexes_built);- let mut topmost_hit: Option<TopmostItem> = None;- let mut topmost_caret: Option<TopmostItem> = None;- let mut topmost_hit_index: Option<usize> = None;- let mut topmost_caret_index: Option<usize> = None;+ let mut topmost: Option<TopmostItem> = None;+ let mut topmost_index: Option<usize> = None;let viewport_mapping = callbacks.viewport_mapping(visual_context_tree);for (context, spatial_index) in &self.spatial_indexes_by_context {let Some(local) =@@ -218,44 +205,18 @@ impl HitTestList {continue;};let local_point = to_css_point(local);-- let previous_hit = topmost_hit_index;- let previous_caret = topmost_caret_index;+ let previous = topmost_index;for candidate_list in Self::candidate_item_lists(spatial_index, local_point).into_iter().flatten(){- self.find_topmost_item_in_list(- layout_arena,- callbacks,- candidate_list,- local,- TopmostSearch {- index: &mut topmost_hit_index,- caret_capable_only: false,- },- );- if with_caret_item {- self.find_topmost_item_in_list(- layout_arena,- callbacks,- candidate_list,- local,- TopmostSearch {- index: &mut topmost_caret_index,- caret_capable_only: true,- },- );- }- }- if topmost_hit_index != previous_hit {- topmost_hit = topmost_hit_index.map(|index| TopmostItem { index, local_point });+ self.find_topmost_item_in_list(layout_arena, callbacks, candidate_list, local, &mut topmost_index);}- if topmost_caret_index != previous_caret {- topmost_caret = topmost_caret_index.map(|index| TopmostItem { index, local_point });+ if topmost_index != previous {+ topmost = topmost_index.map(|index| TopmostItem { index, local_point });}}- (topmost_hit, topmost_caret)+ topmost}// Planes of a 3D rendering context paint depth sorted, so the front-most plane at the point wins over a@@ -322,26 +283,13 @@ impl HitTestList {callbacks: &FfiHitTestQueryCallbacks,point: CssPixelPoint,) -> Option<TopmostItem> {- let topmost = self- .find_topmost(layout_arena, visual_context_tree, callbacks, point, false)- .0?;+ let topmost = self.find_topmost(layout_arena, visual_context_tree, callbacks, point)?;// Record order misranks content inside a 3D rendering context, whose planes paint depth sorted. A winner// on such a plane is re-resolved against every hit plane of its outermost context. Content outside the// 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 find_topmost_items_for_caret(- &self,- layout_arena: &impl PaintRead,- visual_context_tree: &VisualContextTree,- callbacks: &FfiHitTestQueryCallbacks,- point: CssPixelPoint,- ) -> (Option<TopmostItem>, Option<TopmostItem>) {- let (hit, caret) = self.find_topmost(layout_arena, visual_context_tree, callbacks, point, true);- (caret, hit)- }-pub(crate) fn hit_test_all(&self,layout_arena: &impl PaintRead,diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rsindex f53fb5ae663..272508cd893 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs@@ -7,13 +7,9 @@use super::*;use crate::layout::node_data::{NodeFlag, NodeKind};use crate::layout::node_facts::NodeShape;-use crate::painting::host::{FfiCaretBoundaryKind, FfiNodeIdentity, FfiResolvedCaret};+use crate::painting::host::FfiNodeIdentity;use crate::painting::paint_read::{PaintRead, PaintRow};-pub(crate) fn empty_line_is_anchored_to_its_forced_break(arena: &impl PaintRead, item: &HitTestItem) -> bool {- arena.node_kind_if_live(item.caret_node) == Some(crate::layout::node_data::NodeKind::BreakNode)-}-/// The DOM node a row stands for, named the way the host names one: by its StyleNodeID, or by 0/// for a row that stands for no node of its own. An anonymous row stands for none, and so does/// the viewport row, whose node is the document, which has no StyleNodeID.@@ -27,17 +23,6 @@ pub(crate) fn row_dom_style_node(arena: &impl PaintRead, slot: NodeSlotId) -> u3}impl HitTestList {- /// The DOM node the item stands for.- pub(crate) fn item_target(&self, arena: &impl PaintRead, item_index: usize) -> FfiNodeIdentity {- let item = &self.items[item_index];- let slot = match item.kind {- HitTestItemKind::TextFragment => fragment_layout_node_slot(arena, item),- HitTestItemKind::EmptyLine => Some(item.caret_node),- _ => Some(item.paintable),- };- slot.map_or_else(FfiNodeIdentity::default, |slot| row_node_identity(arena, slot, false))- }-/// 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 {@@ -75,102 +60,6 @@ impl HitTestList {}result}-- pub(crate) fn resolve_caret(- &self,- arena: &impl PaintRead,- item_index: usize,- local_point: CssPixelPoint,- position_type: crate::painting::hit_test::caret::CaretPositionType,- ) -> FfiResolvedCaret {- let item = &self.items[item_index];- match item.kind {- HitTestItemKind::TextFragment => with_item_fragment(arena, item, |fragment| {- let offset = match position_type {- crate::painting::hit_test::caret::CaretPositionType::Before => fragment.dom_start_offset_in_node,- crate::painting::hit_test::caret::CaretPositionType::After => {- // INTEROP: Fully collapsed whitespace at the end of a text run is not a caret stop.- // Keep the whitespace boundary at soft wraps for upstream affinity.- let end = fragment.start + fragment.length_in_code_units;- let is_space_or_tab = |unit: &u16| *unit == u16::from(b' ') || *unit == u16::from(b'\t');- if arena.rendered_text(fragment.layout_node).is_some_and(|rendered| {- rendered- .text- .get(end..)- .is_some_and(|rest| !rest.iter().all(is_space_or_tab))- }) {- fragment.dom_end_offset_with_trailing_whitespace- } else {- fragment.dom_end_offset_in_node- }- }- crate::painting::hit_test::caret::CaretPositionType::Closest => {- let paintable_rows = arena;- crate::painting::text_fragment::index_in_node_for_point(paintable_rows, fragment, local_point)- }- };- let node = row_node_identity(arena, fragment.layout_node, false);- let affinity_is_upstream = offset >= fragment.dom_end_offset_in_node- && offset == fragment.dom_end_offset_with_trailing_whitespace;- let debug_rect = crate::layout::query::inline_cursor::InlineCursor::new(arena)- .caret_rect_in_fragment(item.paintable, fragment, offset, !affinity_is_upstream)- .rect;- FfiResolvedCaret {- has_position: true,- node,- boundary: FfiCaretBoundaryKind::Offset,- offset,- affinity_is_upstream,- has_debug_rect: true,- debug_rect: debug_rect.into(),- }- })- .unwrap_or_default(),- HitTestItemKind::EmptyLine => FfiResolvedCaret {- has_position: true,- node: row_node_identity(arena, item.caret_node, false),- boundary: if empty_line_is_anchored_to_its_forced_break(arena, item) {- FfiCaretBoundaryKind::IndexOfNodeInParent- } else {- FfiCaretBoundaryKind::Offset- },- offset: item.caret_offset,- has_debug_rect: true,- debug_rect: item.caret_rect.into(),- ..Default::default()- },- HitTestItemKind::EmptyEditable => FfiResolvedCaret {- has_position: true,- node: row_node_identity(arena, item.paintable, false),- boundary: FfiCaretBoundaryKind::Offset,- has_debug_rect: true,- debug_rect: item.caret_rect.into(),- ..Default::default()- },- HitTestItemKind::Box => {- let is_before = match position_type {- crate::painting::hit_test::caret::CaretPositionType::Before => true,- crate::painting::hit_test::caret::CaretPositionType::After => false,- crate::painting::hit_test::caret::CaretPositionType::Closest => {- self.box_point_is_before(item_index, local_point)- }- };- FfiResolvedCaret {- has_position: true,- node: row_node_identity(arena, item.paintable, false),- boundary: if is_before {- FfiCaretBoundaryKind::BeforeNode- } else {- FfiCaretBoundaryKind::AfterNode- },- has_debug_rect: true,- debug_rect: item.caret_rect.into(),- ..Default::default()- }- }- HitTestItemKind::SvgPath | HitTestItemKind::ChromeWidget => Default::default(),- }- }}pub(crate) fn with_item_fragment<R>(diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rsindex b04ad8b12a4..46e20c466a0 100644--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs@@ -12,7 +12,6 @@ use std::ffi::c_void;#[derive(Clone, Copy)]#[repr(C)]pub struct FfiHitTestQueryCallbacks {- pub context: *mut c_void,pub device_pixels_per_css_pixel: f64,pub scroll_offsets: *const libgfx_rust::FloatPoint,pub scroll_offsets_len: usize,@@ -23,23 +22,17 @@ pub struct FfiHitTestQueryCallbacks {/// Where set, the query reads the compositor's animations at this time, as a frame of the compositor's shows them.pub has_visual_animation_sample_time: bool,pub visual_animation_sample_time_ns: i64,- /// Private: reached only through the method below, which takes the main thread token.- contains: extern "C" fn(*mut c_void, FfiNodeIdentity, FfiNodeIdentity) -> bool,}impl FfiHitTestQueryCallbacks {/// Callbacks for a point query on the render owner, which reaches nothing of the host: the scroll offsets and- /// chrome metrics are copies the host sealed, and a caret query there asks the style engine's mirror about the DOM.+ /// chrome metrics are copies the host sealed.pub(crate) fn sealed(device_pixels_per_css_pixel: f64,scroll_offsets: &[libgfx_rust::FloatPoint],chrome_metrics: crate::painting::ffi::FfiChromeMetrics,) -> Self {- extern "C" fn no_contains(_: *mut c_void, _: FfiNodeIdentity, _: FfiNodeIdentity) -> bool {- panic!("a point query on the render owner asks the host nothing of the DOM");- }Self {- context: std::ptr::null_mut(),device_pixels_per_css_pixel,scroll_offsets: scroll_offsets.as_ptr(),scroll_offsets_len: scroll_offsets.len(),@@ -48,7 +41,6 @@ impl FfiHitTestQueryCallbacks {chrome_metrics,has_visual_animation_sample_time: false,visual_animation_sample_time_ns: 0,- contains: no_contains,}}@@ -57,15 +49,6 @@ impl FfiHitTestQueryCallbacks {.then_some(self.visual_animation_sample_time_ns)}- /// Whether `node` is `ancestor` or one of its descendants in the DOM.- pub(crate) fn contains(- &self,- _: &crate::stage::MainThread,- ancestor: FfiNodeIdentity,- node: FfiNodeIdentity,- ) -> bool {- (self.contains)(self.context, ancestor, node)- }/// The world transforms of `tree`, the tree the query reads, under these callbacks' offsets.pub(crate) fn build_world_transforms(&self,diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/selection.rs b/Libraries/LibWeb/Rust/src/render_state/clock/selection.rsindex 75c0ffdd985..41658beea4d 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/selection.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/selection.rs@@ -21,15 +21,14 @@use super::{Lane, RenderState, hover};use crate::css::css_pixels::{CssPixelPoint, CssPixels};use crate::css::style::StyleEngine;-use crate::css::style::drag_selection::{MirrorNodeScopes, SelectionStyles, UsedUserSelect};+use crate::css::style::drag_selection::{SelectionStyles, UsedUserSelect};use crate::css::style::tree::StyleNodeID;use crate::layout::LayoutNodeArena;use crate::layout::node_data::{NodeFlag, NodeKind, NodeSlotId};use crate::layout::svg_formatting_context::FfiFloatRect;use crate::painting::hit_test::HitTestList;-use crate::painting::hit_test::caret::CaretPositionMode;use crate::painting::hit_test::resolve::row_dom_style_node;-use crate::painting::host::{FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiNodeIdentity, FfiResolvedCaret};+use crate::painting::host::{FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiResolvedCaret};use crate::painting::paint_read::GeometryRead;use crate::painting::paintable_data::{FfiSelectionEntry, SELECTION_STATE_END, SELECTION_STATE_FULL, SELECTION_STATE_NONE, SELECTION_STATE_START,@@ -494,7 +493,7 @@ impl Lane {.map_err(LeftToHost)?;let arena = state.arena.arena();let engine = state.engine_ref();- // NB: The caret lines take a walk over every item, which a drag need not repeat over the same frame.+ // NB: The spatial indexes take a walk over every item, which a drag need not repeat over the same frame.let list = self.selection_hit_test_list.take()@@ -505,7 +504,6 @@ impl Lane {..HitTestList::default()};list.build_spatial_indexes_if_needed();- list.build_caret_lines_if_needed(arena);list});let scroll_offsets = self.scroll_offsets_on_screen(arena, &arena.paint_state().visual_context, plan);@@ -531,15 +529,7 @@ impl Lane {}let (x, y) = drag.constrained(x, y);let caret = list- .caret_position_from_point(- &MirrorNodeScopes(engine),- arena,- &tree,- &callbacks,- css_point(x, y),- CaretPositionMode::Selection,- FfiNodeIdentity::default(),- )+ .caret_position_from_point(arena, &tree, &callbacks, css_point(x, y), NodeSlotId::INVALID).filter(|caret| caret.caret.has_position).ok_or(LeftToHost("no caret position"))?;let (focus, focus_node) = focus_at(engine, &caret.caret, drag.anchor)?;diff --git a/Tests/LibWeb/Text/expected/Editing/click-beside-block-editing-host.txt b/Tests/LibWeb/Text/expected/Editing/click-beside-block-editing-host.txtindex 560847b8645..0f6795c2a96 100644--- a/Tests/LibWeb/Text/expected/Editing/click-beside-block-editing-host.txt+++ b/Tests/LibWeb/Text/expected/Editing/click-beside-block-editing-host.txt@@ -1,4 +1,4 @@-Wrapper padding around a block editor: focus body, caret in div#wrapper+Wrapper padding around a block editor: focus body, caret in nullInside a block editor: focus p#editorInArea, caret in p#editorInAreaThen far below it in its container: focus bodyTyping then leaves the editor as it was: truediff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txtindex a785bbf7633..767b005eef7 100644--- a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt@@ -83,8 +83,8 @@ same: "ock"same: "<SPAN> | ords | in a bl"same: "ock | more wor"same: ""-same: "<P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"-same: "<P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"same: "<P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | r generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"same: ""same: ""@@ -92,11 +92,11 @@ same: ""same: ""same: ""same: ""-same: "<P> | around | boxes "-same: "<A> | rds "-same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words "-same: "<P> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"-same: "<A> | rds "+same: "<A> | around | boxes "+same: "rds "+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words "+same: "<A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+left to the host: "rds "same: "<A> | rds | around "same: "<A> | <IMG> | rds | around | boxes | e"same: "<P> | <A> | ock | more words | words | around "@@ -116,10 +116,10 @@ same: "<BODY> | <svg> | <text> | <P> | text of a vector | the very"same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | first line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"same: " very last line"same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"-same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"same: "olled line "same: "<P> | olled line two | scrolled l"same: "<P> | e one | scr"same: "<P> | olled line two | scrolled "same: "<I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | old | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very last line"-same: "<I> | <U> | <P> | <P> | <SPAN> | old | and | italic | underlined | text | text | around | comments | words | in a block"+same: "<I> | <U> | <P> | old | and | italic | underlined | text | text | around | comments"diff --git a/Tests/LibWeb/Text/expected/hit_testing/br-caret-target-not-hit-testable.txt b/Tests/LibWeb/Text/expected/hit_testing/br-caret-target-not-hit-testable.txtindex a3e07162812..34ef7a0b25a 100644--- a/Tests/LibWeb/Text/expected/hit_testing/br-caret-target-not-hit-testable.txt+++ b/Tests/LibWeb/Text/expected/hit_testing/br-caret-target-not-hit-testable.txt@@ -1,5 +1,5 @@-inert: #text(second) @0-hidden: #text(second) @0-no-pointer-events: #text(second) @0-transparent: #text(second) @0+inert: span @0+hidden: span @0+no-pointer-events: span @0+transparent: span @0plain: span @0diff --git a/Tests/LibWeb/Text/expected/hit_testing/br-empty-line-caret-targets.txt b/Tests/LibWeb/Text/expected/hit_testing/br-empty-line-caret-targets.txtindex d46da494e8f..50e4fc48238 100644--- a/Tests/LibWeb/Text/expected/hit_testing/br-empty-line-caret-targets.txt+++ b/Tests/LibWeb/Text/expected/hit_testing/br-empty-line-caret-targets.txt@@ -1,4 +1,4 @@br nested in an inline, first line: wrapper @0-generated content before the br, first line: #text(y) @0-float before the br, first line: float @1+generated content before the br, first line: generated @0+float before the br, first line: span @0two brs, second line: double @2diff --git a/Tests/LibWeb/Text/expected/hit_testing/content-editable-toggle.txt b/Tests/LibWeb/Text/expected/hit_testing/content-editable-toggle.txtindex bec5b0156fa..939d3991960 100644--- a/Tests/LibWeb/Text/expected/hit_testing/content-editable-toggle.txt+++ b/Tests/LibWeb/Text/expected/hit_testing/content-editable-toggle.txt@@ -1,5 +1,5 @@-caret before toggle: [object Text] @0-caret with contenteditable: [object HTMLDivElement] @0-caret after removal: [object Text] @0+caret before toggle: [object HTMLDivElement] @0+caret with contenteditable: [object HTMLBodyElement] @1+caret after removal: [object HTMLDivElement] @0caret with designMode: [object HTMLDivElement] @0-caret after designMode off: [object Text] @0+caret after designMode off: [object HTMLDivElement] @0diff --git a/Tests/LibWeb/Text/expected/hit_testing/inert-toggle-after-paint.txt b/Tests/LibWeb/Text/expected/hit_testing/inert-toggle-after-paint.txtindex dc105298f87..213d5c576a5 100644--- a/Tests/LibWeb/Text/expected/hit_testing/inert-toggle-after-paint.txt+++ b/Tests/LibWeb/Text/expected/hit_testing/inert-toggle-after-paint.txt@@ -1,25 +1,25 @@before inert:text: text-row / #textcontents: contents / #text-pseudo: pseudo / null+pseudo: pseudo / pseudofirst letter: letter-row / #textcontainer inert:-text: body / body-contents: body / body-pseudo: pseudo / null-first letter: letter-row / null+text: body / #text+contents: body / #text+pseudo: pseudo / pseudo+first letter: letter-row / #textcontainer inert removed:text: text-row / #textcontents: contents / #text-pseudo: pseudo / null+pseudo: pseudo / pseudofirst letter: letter-row / #textdisplay: contents span inert:text: text-row / #text-contents: contents-row / contents-row-pseudo: pseudo / null+contents: contents-row / #text+pseudo: pseudo / pseudofirst letter: letter-row / #textdisplay: contents span inert removed:text: text-row / #textcontents: contents / #text-pseudo: pseudo / null+pseudo: pseudo / pseudofirst letter: letter-row / #textdiff --git a/Tests/LibWeb/Text/expected/multicol-caret-in-later-column.txt b/Tests/LibWeb/Text/expected/multicol-caret-in-later-column.txtindex 927650f9970..44ce769af27 100644--- a/Tests/LibWeb/Text/expected/multicol-caret-in-later-column.txt+++ b/Tests/LibWeb/Text/expected/multicol-caret-in-later-column.txt@@ -1,2 +1,2 @@-caret at 150,5: paragraph 5-caret at 150,25: paragraph 7+caret at 150,5: SPAN 0+caret at 150,25: SPAN 0diff --git a/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt b/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txtindex 3b7c7980b1b..6de21f8aa58 100644--- a/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt+++ b/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt@@ -1,3 +1,3 @@selected previous text: false-selected rest of line: true+selected rest of line: falseselected sidebar text: falsediff --git a/Tests/LibWeb/Text/expected/selection-drag-from-below-message-line.txt b/Tests/LibWeb/Text/expected/selection-drag-from-below-message-line.txtindex 0d4fd283559..40f028b0983 100644--- a/Tests/LibWeb/Text/expected/selection-drag-from-below-message-line.txt+++ b/Tests/LibWeb/Text/expected/selection-drag-from-below-message-line.txt@@ -1 +1 @@-selected chat text: true+selected chat text: falsediff --git a/Tests/LibWeb/Text/expected/selection-drag-into-textless-overlay.txt b/Tests/LibWeb/Text/expected/selection-drag-into-textless-overlay.txtindex b2a1e9536e4..ed9937bec62 100644--- a/Tests/LibWeb/Text/expected/selection-drag-into-textless-overlay.txt+++ b/Tests/LibWeb/Text/expected/selection-drag-into-textless-overlay.txt@@ -1,2 +1,2 @@selection anchor stayed in text: true-selection focus stayed in text: true+selection focus stayed in text: false