Truly independent web browser
LibWeb: Add InlineCursor and compute every caret rect with it
Aliaksandr Kalenik6932d8eb04dc
diff --git a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cppindex 7e1d063e0c8..b1a5e63960f 100644--- a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp+++ b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp@@ -246,17 +246,19 @@ static bool fill_text_geometry(WebView::AccessibilityNodeData& node_data, DOM::Tauto* layout = text_node.layout_node(read);- // The caret rect at a DOM offset is document-absolute and spans the height of the line the offset+ // The caret rect at a DOM offset is document-absolute and spans the height of the text on the line the offset// renders on, which is what a line's geometry is read from here.auto line_rect_at_offset = [&](size_t offset) -> Optional<CSSPixelRect> {if (!layout)return {};- Layout::RustFFI::FfiOptionalCssPixelRect result;- Layout::RustFFI::layout_script_text_caret_rect_in_dom_range(- layout->document_host(), Layout::Node::slot_id(layout), offset, &result);- if (!result.has_value)+ Compositing::RustFFI::NodeSlotId const no_slot { Compositing::RustFFI::INVALID_NODE_SLOT_INDEX };+ Layout::RustFFI::FfiCaret caret;+ Layout::RustFFI::layout_script_caret(layout->document_host(),+ { .node = Layout::Node::slot_id(layout), .offset = offset, .downstream = true, .child_before = no_slot, .child_before_length = 0, .child_after = no_slot },+ {}, &caret);+ if (!caret.found)return {};- return result.rect;+ return caret.rect;};struct RenderedLine {diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 8bc2d77ee77..d5e34670c69 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -11845,40 +11845,16 @@ Optional<CSSPixelRect> Document::current_caret_rect()auto position = cursor_position();if (!position)return {};- auto& dom_node = *position->node();update_layout(UpdateLayoutReason::InputCaretRect);- auto* layout_node = dom_node.layout_node(read);- if (!layout_node)+ auto caret = Painting::caret_at_position(read, *position, Painting::viewport_mapping(*this));+ if (!caret.found)return {};-- // The caret rects computed here are document-relative (absolute). Platform IME overlays are positioned relative to- // the viewport — so translate by scroll offset and map through any containing navigables to the local page viewport.- auto to_viewport_rect = [this](CSSPixelRect rect) -> CSSPixelRect {- auto navigable = this->navigable();- if (!navigable)- return rect;- auto scroll = navigable->viewport_scroll_offset();- CSSPixelRect viewport_rect { rect.x() - scroll.x(), rect.y() - scroll.y(), rect.width(), rect.height() };- return navigable->to_page_rect(viewport_rect);- };-- if (is<DOM::Text>(dom_node)) {- Layout::RustFFI::FfiCaretRectResult result;- Layout::RustFFI::layout_script_text_caret_rect_for_position(- layout_node->document_host(), Layout::Node::slot_id(layout_node), position->offset(), position->affinity() == TextAffinity::Downstream, &result);- if (result.found)- return to_viewport_rect(result.rect);- }-- // Empty editable elements have no fragments; use the same child-offset position and font metrics as caret- // painting, including empty lines rendered by <br>.- if (auto* node_with_style = as_if<Layout::NodeWithStyle>(*layout_node)) {- if (Painting::has_committed_box(*node_with_style))- return to_viewport_rect(Painting::caret_rect_for_child_offset(read, *node_with_style, position->offset()));- }- return {};+ // Map through any containing navigables to the local page viewport.+ if (auto navigable = this->navigable())+ return navigable->to_page_rect(caret.viewport_rect);+ return caret.viewport_rect;}void Document::reset_cursor_blink_cycle()diff --git a/Libraries/LibWeb/HTML/HTMLBRElement.cpp b/Libraries/LibWeb/HTML/HTMLBRElement.cppindex f0c9cab26be..411c4dffbc0 100644--- a/Libraries/LibWeb/HTML/HTMLBRElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLBRElement.cpp@@ -59,9 +59,8 @@ bool HTMLBRElement::represents_empty_line(Layout::BegunRead const& read) constauto const* layout_node = this->layout_node(read);if (!layout_node || !layout_node->containing_block())return false;- CSSPixelPoint line_position;- return Layout::RustFFI::layout_script_empty_line_ended_by_forced_break_position(layout_node->document_host(),- Layout::Node::slot_id(layout_node->containing_block()), Layout::Node::slot_id(layout_node), &line_position);+ return Layout::RustFFI::layout_script_forced_break_ends_empty_line(layout_node->document_host(),+ Layout::Node::slot_id(layout_node->containing_block()), Layout::Node::slot_id(layout_node));}}diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cppindex 88a11b49904..22a31819012 100644--- a/Libraries/LibWeb/Painting/BoxViews.cpp+++ b/Libraries/LibWeb/Painting/BoxViews.cpp@@ -13,7 +13,6 @@#include <LibWeb/DOM/Text.h>#include <LibWeb/HTML/FormAssociatedElement.h>#include <LibWeb/HTML/HTMLAreaElement.h>-#include <LibWeb/HTML/HTMLBRElement.h>#include <LibWeb/HTML/HTMLHtmlElement.h>#include <LibWeb/HTML/HTMLImageElement.h>#include <LibWeb/HTML/HTMLMapElement.h>@@ -22,7 +21,6 @@#include <LibWeb/Layout/Box.h>#include <LibWeb/Layout/LayoutRustBridge.h>#include <LibWeb/Layout/Node.h>-#include <LibWeb/Layout/TextNode.h>#include <LibWeb/Layout/Viewport.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Painting/BoxViews.h>@@ -373,230 +371,66 @@ CSSPixelPoint box_type_agnostic_position(Layout::Node const& node)return absolute_position(node);}-static bool has_content(Layout::Node const& node)+Layout::RustFFI::FfiCaret caret_at_position(Layout::BegunRead const& read, DOM::Position const& position, Layout::RustFFI::FfiViewportMapping viewport_mapping){- // Interrupting block-in-inline children produce only placeholder pieces, so any child- // paintable also counts as content.- return Layout::RustFFI::render_state_inline_paintable_has_content_pieces(node.document_host(), committed_row_slot(node))- || Layout::RustFFI::layout_row_paintable_has_child_paintables(node.document_host(), committed_row_slot(node));-}--static CSSPixelRect caret_rect_for_empty_line(Layout::NodeWithStyle const& node, CSSPixelPoint position)-{- // NB: Match the font-height caret used by text fragments, centered in the empty line's line-height box.- auto const& font_metrics = node.first_available_font().pixel_metrics();- auto line_height = node.line_height();- auto caret_height = min(line_height, CSSPixels::nearest_value_for(font_metrics.ascent + font_metrics.descent));- return { position.x(), position.y() + (line_height - caret_height) / 2, 1, caret_height };-}--static Optional<Layout::RustFFI::FfiCaretRectResult> caret_at_atomic_child(Layout::Node const& layout_node, size_t offset)-{- auto const& read = layout_node.held_read();- auto* node = layout_node.dom_node();- if (!node)- return {};- auto resolve = [&](size_t child_offset) -> Optional<Layout::RustFFI::FfiCaretRectResult> {- auto const* child = node->child_at_index(child_offset);- auto* child_layout_node = child ? child->unsafe_layout_node(read) : nullptr;- if (!child_layout_node || !child_layout_node->is_atomic_inline())- return {};- Layout::RustFFI::FfiCaretRectResult result;- Layout::RustFFI::layout_script_atomic_inline_caret_rect_for_position(- layout_node.document_host(), Layout::Node::slot_id(child_layout_node), child_offset < offset, &result);- if (!result.found)- return {};- return result;- };- if (offset > 0) {- if (auto result = resolve(offset - 1); result.has_value())- return result;- }- return resolve(offset);-}--// Caret rect for a cursor parked on this paintable's DOM node at the given child offset, e.g. on an empty line-// rendered by a <br> child or in an empty editable element.-CSSPixelRect caret_rect_for_child_offset(Layout::BegunRead const& read, Layout::Node const& block, size_t offset)-{- if (!has_committed_box(block))- return {};- auto const& styled_block = as<Layout::NodeWithStyle>(block);-- auto content_box = absolute_padding_box_rect(block);- auto line_height = styled_block.line_height();- auto rect = caret_rect_for_empty_line(styled_block, content_box.location());- auto caret_offset_in_line = rect.y() - content_box.y();-- auto dom_node = block.dom_node();- if (!dom_node)- return rect;-- if (auto atomic_caret = caret_at_atomic_child(block, offset); atomic_caret.has_value())- return atomic_caret->rect;-- // NB: A boundary beside a text child has the same geometry as the corresponding text offset.- // Editors can leave the selection on the parent after inserting their first character.- // Use the text fragment's position and font metrics instead of the empty-block fallback.- auto caret_rect_in_text = [&](DOM::Node const* node, size_t text_offset) -> Optional<CSSPixelRect> {- auto const* text = as_if<DOM::Text>(node);- auto const* layout_node = text ? text->unsafe_layout_node(read) : nullptr;- if (!layout_node)- return {};- Layout::RustFFI::FfiCaretRectResult result;- Layout::RustFFI::layout_script_text_caret_rect_for_position(- block.document_host(), Layout::Node::slot_id(layout_node), text_offset, true, &result);- if (result.found)- return result.rect;- return {};+ Layout::RustFFI::FfiCaret caret {};+ auto const& node = *position.node();+ auto const* layout_node = node.unsafe_layout_node(read);+ if (!layout_node)+ return caret;+ auto slot_of = [&](DOM::Node const* child) {+ auto const* child_layout_node = child ? child->unsafe_layout_node(read) : nullptr;+ return child_layout_node ? Layout::Node::slot_id(child_layout_node) : Compositing::RustFFI::NodeSlotId { Compositing::RustFFI::INVALID_NODE_SLOT_INDEX };};- if (offset > 0) {- auto const* previous_child = dom_node->child_at_index(offset - 1);- if (auto text_rect = caret_rect_in_text(previous_child, previous_child ? previous_child->length() : 0); text_rect.has_value())- return *text_rect;- }- if (auto text_rect = caret_rect_in_text(dom_node->child_at_index(offset), 0); text_rect.has_value())- return *text_rect;-- auto* child = dom_node->child_at_index(offset);- if (!child || !is<HTML::HTMLBRElement>(*child))- return rect;-- if (auto const* break_layout_node = child->unsafe_layout_node(read)) {- CSSPixelPoint line_position;- if (Layout::RustFFI::layout_script_empty_line_ended_by_forced_break_position(block.document_host(), committed_row_slot(block), Layout::Node::slot_id(break_layout_node), &line_position))- return caret_rect_for_empty_line(styled_block, line_position);- }-- // A caret parked before a <br> sits on the line below the content preceding the <br>. Layout produces no- // fragments for <br>, so start below the fragments of any preceding content, and add one line height for each- // empty line rendered by earlier <br>s.- struct PrecedingContentContext {- GC::Ref<DOM::Node> child;- Layout::BegunRead const& read;- Optional<CSSPixels> preceding_content_bottom;- } preceding_context {- .child = const_cast<DOM::Node&>(*child),- .read = read,- .preceding_content_bottom = {},+ auto offset = position.offset();+ auto const* child_before = offset > 0 ? node.child_at_index(offset - 1) : nullptr;+ Layout::RustFFI::FfiCaretPosition ffi_position {+ .node = Layout::Node::slot_id(layout_node),+ .offset = offset,+ .downstream = position.affinity() == TextAffinity::Downstream,+ .child_before = slot_of(child_before),+ .child_before_length = child_before ? child_before->length() : 0,+ .child_after = slot_of(node.child_at_index(offset)),};- Layout::RustFFI::render_state_for_each_subtree_fragment_rect(- block.document_host(), committed_row_slot(block), &preceding_context,- [](void* context_pointer, Compositing::RustFFI::NodeSlotId fragment_slot, CSSPixelRect rect) {- auto& context = *static_cast<PrecedingContentContext*>(context_pointer);- auto const* fragment_layout_node = context.child->document().layout_node_arena().node_if_live(context.read, fragment_slot);- auto* fragment_dom_node = fragment_layout_node ? const_cast<DOM::Node*>(fragment_layout_node->dom_node()) : nullptr;- if (!fragment_dom_node || !(context.child->compare_document_position(fragment_dom_node) & DOM::Node::DOCUMENT_POSITION_PRECEDING))- return;- auto bottom = rect.bottom();- if (!context.preceding_content_bottom.has_value() || bottom > *context.preceding_content_bottom)- context.preceding_content_bottom = bottom;- });- auto& preceding_content_bottom = preceding_context.preceding_content_bottom;-- size_t preceding_empty_lines = 0;- dom_node->for_each_in_subtree_of_type<HTML::HTMLBRElement>([&](auto& br) {- if (&br == child)- return TraversalDecision::Break;- if (br.represents_empty_line(read))- ++preceding_empty_lines;- return TraversalDecision::Continue;- });-- rect.set_y(preceding_content_bottom.value_or(content_box.y()) + line_height * preceding_empty_lines + caret_offset_in_line);- return rect;+ Layout::RustFFI::layout_script_caret(layout_node->document_host(), ffi_position, viewport_mapping, &caret);+ return caret;}Layout::RustFFI::FfiCaretPaint resolve_document_caret_paint(Layout::BegunRead const& read, DOM::Document& document){- Layout::RustFFI::FfiCaretPaint caret {};+ Layout::RustFFI::FfiCaretPaint caret_paint {};Compositing::RustFFI::NodeSlotId const no_slot { Compositing::RustFFI::INVALID_NODE_SLOT_INDEX };- caret.kind = Layout::RustFFI::FfiCaretPaintKind::None;- caret.block = no_slot;- caret.owner = no_slot;+ caret_paint.kind = Layout::RustFFI::FfiCaretPaintKind::None;+ caret_paint.block = no_slot;+ caret_paint.owner = no_slot;auto cursor_position = document.cursor_position();if (!cursor_position)- return caret;+ return caret_paint;// The caret paints only while the cursor node is editable (or a mutable text control has focus), and the recorder- // paints it only while the window has focus; every candidate box below has a committed box.- auto const* cursor_node = cursor_position->node().ptr();- if (!cursor_node)- return caret;+ // paints it only while the window has focus.bool cursor_is_editable = false;if (auto const* text_control = as_if<HTML::FormAssociatedTextControlElement>(document.focused_area().ptr()); text_control && text_control->text_control_to_html_element().is_mutable())cursor_is_editable = true;else- cursor_is_editable = cursor_node->is_editable_or_editing_host();+ cursor_is_editable = cursor_position->node()->is_editable_or_editing_host();if (!cursor_is_editable)- return caret;-- auto fill = [&](Layout::RustFFI::FfiCaretPaintKind kind, Compositing::RustFFI::NodeSlotId block, Compositing::RustFFI::NodeSlotId owner, CSSPixelRect rect, Color color) {- caret.kind = kind;- caret.block = block;- caret.owner = owner;- caret.rect = rect;- caret.color = color;- caret.blink_cycle_start_time_ns = document.cursor_blink_cycle_start_time_ns();- caret.should_blink = !HTML::Window::in_test_mode();- };-- if (auto const* text = as_if<DOM::Text>(cursor_node)) {- auto const* text_layout_node = text->unsafe_layout_node(read);- if (!text_layout_node)- return caret;- auto* host = text_layout_node->document_host();- Layout::RustFFI::FfiCaretRectResult result;- Layout::RustFFI::layout_script_text_caret_rect_for_position(- host, Layout::Node::slot_id(text_layout_node), cursor_position->offset(),- cursor_position->affinity() == TextAffinity::Downstream, &result);- if (result.found) {- auto const* style_source = static_cast<Layout::NodeWithStyle const*>(text_layout_node->node_arena().node_if_live(read, result.style_source));- if (style_source && layout_node_is_visible(*style_source))- fill(Layout::RustFFI::FfiCaretPaintKind::InBlock, result.owner_paintable, result.nearest_self_painting_inline, result.rect, style_source->caret_color());- return caret;- }- // No fragment holds the position: the caret sits on an empty line of the block that lays the text out.- for (auto const* block = text_layout_node->parent(); block; block = block->parent()) {- if (!has_committed_box(*block) || !is_visible(*block))- continue;- Layout::RustFFI::FfiEmptyLineCaretRect empty_line;- Layout::RustFFI::layout_script_paintable_empty_line_caret_rect(- host, committed_row_slot(*block), Layout::Node::slot_id(text_layout_node), cursor_position->offset(), &empty_line);- if (!empty_line.has_value)- continue;- auto const* style_source = static_cast<Layout::NodeWithStyle const*>(text_layout_node->node_arena().node_if_live(read, empty_line.style_source));- if (!style_source)- return caret;- auto empty_line_rect = empty_line.rect;- fill(Layout::RustFFI::FfiCaretPaintKind::InBlock, committed_row_slot(*block), no_slot, CSSPixelRect { empty_line_rect.x(), empty_line_rect.y(), 1, empty_line_rect.height() }, style_source->caret_color());- return caret;- }- return caret;- }-- // The cursor is parked on an element: its own box paints the caret at the child offset, or, for an- // empty editable inline, at the box's position.- auto const* layout_node = cursor_node->layout_node(read);- if (!layout_node || !has_committed_box(*layout_node))- return caret;- auto const& styled_node = as<Layout::NodeWithStyle>(*layout_node);- if (is_inline_paintable(*layout_node)) {- if (auto atomic_caret = caret_at_atomic_child(*layout_node, cursor_position->offset()); atomic_caret.has_value()) {- if (layout_node_is_visible(styled_node))- fill(Layout::RustFFI::FfiCaretPaintKind::InBlock, atomic_caret->owner_paintable, atomic_caret->nearest_self_painting_inline, atomic_caret->rect, styled_node.caret_color());- return caret;- }- if (has_content(*layout_node))- return caret;- auto position = box_type_agnostic_position(*layout_node);- fill(Layout::RustFFI::FfiCaretPaintKind::EmptyInline, committed_row_slot(*layout_node), no_slot, caret_rect_for_empty_line(styled_node, position), styled_node.caret_color());- return caret;- }- if (!is_visible(*layout_node))- return caret;- fill(Layout::RustFFI::FfiCaretPaintKind::InBlock, committed_row_slot(*layout_node), no_slot, caret_rect_for_child_offset(read, *layout_node, cursor_position->offset()), styled_node.caret_color());- return caret;+ return caret_paint;++ auto caret = caret_at_position(read, *cursor_position, {});+ if (!caret.found)+ return caret_paint;+ auto const* style_source = static_cast<Layout::NodeWithStyle const*>(document.layout_node_arena().node_if_live(read, caret.style_source));+ if (!style_source || !layout_node_is_visible(*style_source))+ return caret_paint;+ caret_paint.kind = caret.paint;+ caret_paint.block = caret.block;+ caret_paint.owner = caret.owner;+ caret_paint.rect = caret.rect;+ caret_paint.color = style_source->caret_color();+ caret_paint.blink_cycle_start_time_ns = document.cursor_blink_cycle_start_time_ns();+ caret_paint.should_blink = !HTML::Window::in_test_mode();+ return caret_paint;}Layout::RustFFI::FfiFocusedTextControlSelection resolve_focused_text_control_selection(Layout::BegunRead const& read, DOM::Document const& document)diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.hindex 4a2df2f84bc..891ab45b00c 100644--- a/Libraries/LibWeb/Painting/BoxViews.h+++ b/Libraries/LibWeb/Painting/BoxViews.h@@ -89,7 +89,8 @@ WEB_API Optional<String> grid_layout_json(Layout::Node const&, UniqueNodeID);WEB_API Optional<String> flex_layout_json(Layout::Node const&, UniqueNodeID);WEB_API CSSPixelPoint box_type_agnostic_position(Layout::Node const&);-WEB_API CSSPixelRect caret_rect_for_child_offset(Layout::BegunRead const&, Layout::Node const&, size_t offset);+// The caret layout gives a cursor position, its viewport rect mapped through `viewport_mapping`.+WEB_API Layout::RustFFI::FfiCaret caret_at_position(Layout::BegunRead const&, DOM::Position const&, Layout::RustFFI::FfiViewportMapping);// Per-document paint facts the recording inputs carry, resolved once per recording.WEB_API Layout::RustFFI::FfiCaretPaint resolve_document_caret_paint(Layout::BegunRead const&, DOM::Document&);diff --git a/Libraries/LibWeb/Rust/src/layout/mod.rs b/Libraries/LibWeb/Rust/src/layout/mod.rsindex 1dd95015c53..be17bb15b7e 100644--- a/Libraries/LibWeb/Rust/src/layout/mod.rs+++ b/Libraries/LibWeb/Rust/src/layout/mod.rs@@ -50,6 +50,7 @@ pub use libcompositing_rust::node_slot_id;pub(crate) mod frameset_formatting_context;mod partial_relayout;pub(crate) mod prepared_inline_content;+pub(crate) mod query;pub(crate) mod quote_depth;pub(crate) mod rendered_text;pub(crate) mod replaced_sizing;diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rsnew file mode 100644index 00000000000..0b15d422792--- /dev/null+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs@@ -0,0 +1,441 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Caret positions on the lines layout produced: the line a position is on and its caret there. Geometry is in the+//! pre-transform space of absolute rects; a caller maps it into the viewport through the context the line content is+//! painted in.++use crate::css::css_enums::writing_mode;+use crate::css::css_pixels::{CssPixelRect, CssPixels};+use crate::layout::RenderedTextBoundary;+use crate::layout::inline_content::LineRecord;+use crate::layout::node_data::{NodeKind, NodeSlotId};+use crate::layout::node_facts;+use crate::painting::paint_read::{PaintRead, PaintRow};+use crate::painting::paintable_data::{FragmentRecord, SELECTION_STATE_START_AND_END};+use crate::painting::paintable_geometry::{self, LineRootPositions};+use crate::painting::paintable_rows::with_inline_pieces;+use crate::painting::text_fragment::{self, CaretMatch};+use crate::painting::{node_painting, paint_order};++/// A line of the line root `root`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct InlineLine {+ pub(crate) root: NodeSlotId,+ pub(crate) index: u32,+}++/// Where on its line a position is: in the fragment with this index in the line root's fragments, or on a line that+/// has none.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct LinePosition {+ pub(crate) line: InlineLine,+ pub(crate) fragment: Option<u32>,+}++#[derive(Clone, Copy)]+pub(crate) enum CaretPosition {+ /// `offset` in the DOM text whose layout node is `text`. Where one line ends and the next starts at `offset`,+ /// `downstream` picks the next.+ Text {+ text: NodeSlotId,+ offset: usize,+ downstream: bool,+ },+ BesideAtomicInline {+ node: NodeSlotId,+ after: bool,+ },+ /// Before the <br> `node`, at the end of the line it ends.+ BeforeForcedBreak {+ node: NodeSlotId,+ },+ /// At the start of the box `node`, which lays out no line content around the position.+ StartOfBox {+ node: NodeSlotId,+ },+}++pub(crate) struct CaretRect {+ pub(crate) rect: CssPixelRect,+ /// The box whose caret color the caret takes.+ pub(crate) style_source: NodeSlotId,+ /// The line root whose line holds the caret, or the box at whose start it is.+ pub(crate) owner: NodeSlotId,+ /// The node of the line content beside the caret.+ pub(crate) node: NodeSlotId,+}++/// A line of a text node: the DOM offsets it renders, with the whitespace hanging at its soft wrap between `end_offset`+/// and `end_offset_with_trailing_whitespace`. A line that a preserved newline ends with nothing on it has no fragments.+pub(crate) struct TextLine {+ pub(crate) line: InlineLine,+ pub(crate) start_offset: usize,+ pub(crate) end_offset: usize,+ pub(crate) end_offset_with_trailing_whitespace: usize,+ pub(crate) has_fragments: bool,+}++pub(crate) struct InlineCursor<'a, A: PaintRead> {+ arena: &'a A,+}++impl<'a, A: PaintRead> InlineCursor<'a, A> {+ pub(crate) fn new(arena: &'a A) -> Self {+ Self { arena }+ }++ /// The line `offset` in the DOM text whose layout node is `text` is on.+ pub(crate) fn line_of(&self, text: NodeSlotId, offset: usize, downstream: bool) -> Option<LinePosition> {+ let arena = self.arena;+ let fragments = arena.text_fragments(text);+ let nodes = fragments.as_slice();+ let mut fallback = None;+ let mut direct = None;+ text_fragment::for_each_fragment_of_nodes(arena, nodes, |root, index, fragment| {+ // A caret at the end of the text in front of a writing suggestion is in front of the suggestion, whichever+ // way it leans: The text after the caret starts only after the suggestion.+ match text_fragment::caret_match(fragment, offset, downstream) {+ CaretMatch::None => true,+ CaretMatch::SoftWrapFallback if !arena.text_precedes_writing_suggestion(fragment.layout_node) => {+ fallback = fallback.or(Some((root, index, fragment.line_index)));+ true+ }+ CaretMatch::SoftWrapFallback | CaretMatch::Direct => {+ direct = Some((root, index, fragment.line_index));+ false+ }+ }+ });+ if let Some((root, fragment, index)) = direct.or(fallback) {+ return Some(LinePosition {+ line: InlineLine { root, index },+ fragment: Some(fragment),+ });+ }+ // A preserved newline that ends a line with nothing on it gives the line no fragment.+ nodes.iter().find_map(|&node| {+ let root = text_fragment::containing_block_paintable_of_node(arena, node)?;+ let side = arena.committed_side_data(root);+ let index = side.lines().iter().position(|line| {+ line.fragment_count == 0+ && line.forced_break.is_some_and(|position| {+ nodes.contains(&position.node)+ && arena.dom_offset_for_rendered_text_offset(+ position.node,+ position.rendered_offset as usize,+ RenderedTextBoundary::Start,+ ) == offset+ })+ })?;+ Some(LinePosition {+ line: InlineLine {+ root,+ index: index as u32,+ },+ fragment: None,+ })+ })+ }++ pub(crate) fn caret_rect(&self, position: CaretPosition) -> Option<CaretRect> {+ match position {+ CaretPosition::Text {+ text,+ offset,+ downstream,+ } => {+ let position = self.line_of(text, offset, downstream)?;+ match position.fragment {+ Some(index) => {+ let side = self.arena.committed_side_data(position.line.root);+ let fragment = &side.fragments()[index as usize];+ Some(self.caret_rect_in_fragment(position.line.root, fragment, offset, downstream))+ }+ None => self.caret_rect_on_empty_line(position.line),+ }+ }+ CaretPosition::BesideAtomicInline { node, after } => self.caret_rect_beside_atomic_inline(node, after),+ CaretPosition::BeforeForcedBreak { node } => self.caret_rect_before_forced_break(node),+ CaretPosition::StartOfBox { node } => self.caret_rect_at_start_of_box(node),+ }+ }++ /// The caret at `offset` in the DOM text of the text fragment `fragment` of the line root `root`.+ pub(crate) fn caret_rect_in_fragment(+ &self,+ root: NodeSlotId,+ fragment: &FragmentRecord,+ offset: usize,+ downstream: bool,+ ) -> CaretRect {+ let arena = self.arena;+ let mut rect = CssPixelRect::default();+ if let Some(offsets) =+ text_fragment::compute_selection_offsets(arena, fragment, SELECTION_STATE_START_AND_END, offset, offset)+ {+ rect = text_fragment::rect_for_selection_offsets(arena, fragment, offsets);+ if let Some(coordinate) = fragment+ .glyph_run+ .as_ref()+ .and_then(|run| run.cluster_geometry().x_for_offset(offsets.start, downstream))+ {+ let origin = text_fragment::absolute_rect(arena, fragment);+ let coordinate = CssPixels::nearest_value_for_f32(coordinate);+ if text_fragment::is_horizontal(fragment) {+ rect.x = origin.x + coordinate;+ } else {+ rect.y = origin.y + coordinate;+ }+ }+ }+ CaretRect {+ rect,+ style_source: fragment.style_source,+ owner: root,+ node: fragment.layout_node,+ }+ }++ fn line_rect(&self, line: InlineLine, record: &LineRecord) -> CssPixelRect {+ let position = LineRootPositions::new(self.arena, line.root).of_fragment(record.box_fragment);+ CssPixelRect::from(record.rect).translated_by(position)+ }++ /// A caret as tall as the font of `style_source`, at the inline start of `area` and where layout puts text across a+ /// line of `line_height` from its block start, or across its block extent: the smaller half of the leading is on+ /// the ascent side.+ fn caret_rect_at_inline_start(+ &self,+ area: CssPixelRect,+ line_height: Option<CssPixels>,+ style_source: NodeSlotId,+ ) -> Option<CssPixelRect> {+ let style = self.arena.node_style_if_live(style_source)?;+ let horizontal = style.writing_mode() == writing_mode::HORIZONTAL_TB;+ let line_height = line_height.unwrap_or(if horizontal { area.height } else { area.width });+ let font_height = CssPixels::from_integer((style.font_ascent() + style.font_descent()) as i64);+ let height = font_height.min(line_height);+ let leading = line_height - height;+ let leading_above = leading.scaled(0.5).floor();+ let one = CssPixels::from_integer(1);+ let at_end = style.inline_axis_is_reverse();+ Some(if horizontal {+ CssPixelRect {+ x: if at_end { area.right() - one } else { area.x },+ y: area.y + leading_above,+ width: one,+ height,+ }+ } else {+ CssPixelRect {+ x: area.x + leading - leading_above,+ y: if at_end { area.bottom() - one } else { area.y },+ width: height,+ height: one,+ }+ })+ }++ fn caret_rect_on_empty_line(&self, line: InlineLine) -> Option<CaretRect> {+ let side = self.arena.committed_side_data(line.root);+ let record = side.lines().get(line.index as usize)?;+ let node = record.forced_break?.node;+ let style_source = if self.arena.node_kind_if_live(node) == Some(NodeKind::BreakNode) {+ node+ } else {+ self.arena.node_parent_if_live(node)?+ };+ Some(CaretRect {+ rect: self.caret_rect_at_inline_start(self.line_rect(line, record), None, style_source)?,+ style_source,+ owner: line.root,+ node,+ })+ }++ // INTEROP: A caret beside an atomic inline spans its line box, with the inline coordinate at the box's edge.+ fn caret_rect_beside_atomic_inline(&self, node: NodeSlotId, after: bool) -> Option<CaretRect> {+ let arena = self.arena;+ let owner = text_fragment::containing_block_paintable_of_node(arena, node)?;+ let side = arena.committed_side_data(owner);+ let fragment = side+ .fragments()+ .iter()+ .find(|fragment| fragment.layout_node == node && fragment.is_atomic_inline)?;+ let fragment_rect = text_fragment::absolute_rect(arena, fragment);+ let item_rect = paintable_geometry::absolute_border_box_rect(arena, node);+ let mut rect = text_fragment::absolute_line_box_rect(arena, owner, fragment);+ // The line box is unpositioned; move its block-axis extent with the atomic box and its inline ancestors.+ rect.x += item_rect.x - fragment_rect.x + fragment.relpos_delta.x;+ rect.y += item_rect.y - fragment_rect.y + fragment.relpos_delta.y;+ let at_end = after != arena.node_style_if_live(node)?.inline_axis_is_reverse();+ let thickness = CssPixels::from_integer(1);+ if text_fragment::is_horizontal(fragment) {+ rect.x = if at_end { item_rect.right() } else { item_rect.x };+ rect.width = thickness;+ } else {+ rect.y = if at_end { item_rect.bottom() } else { item_rect.y };+ rect.height = thickness;+ }+ Some(CaretRect {+ rect,+ style_source: node,+ owner,+ node,+ })+ }++ fn caret_rect_before_forced_break(&self, node: NodeSlotId) -> Option<CaretRect> {+ let root = text_fragment::containing_block_paintable_of_node(self.arena, node)?;+ let side = self.arena.committed_side_data(root);+ let index = side+ .lines()+ .iter()+ .position(|line| line.forced_break.is_some_and(|position| position.node == node))?;+ let record = &side.lines()[index];+ if record.fragment_count == 0 {+ return self.caret_rect_on_empty_line(InlineLine {+ root,+ index: index as u32,+ });+ }+ let last = &side.fragments()[(record.first_fragment + record.fragment_count - 1) as usize];+ if last.is_atomic_inline {+ return self.caret_rect_beside_atomic_inline(last.layout_node, true);+ }+ Some(self.caret_rect_in_fragment(root, last, last.dom_end_offset_with_trailing_whitespace, false))+ }++ fn caret_rect_at_start_of_box(&self, node: NodeSlotId) -> Option<CaretRect> {+ let arena = self.arena;+ if !arena.paintable_row_is_populated(node) {+ return None;+ }+ // An inline box with content has no caret of its own: interrupting blocks leave only placeholder pieces, but they+ // are content too.+ if node_painting::is_fragmented_inline(arena, node) {+ let mut has_content = paint_order::first_paint_child(arena, node).is_some();+ with_inline_pieces(arena, node, |piece| {+ has_content |= !piece.is_geometry_only_placeholder;+ !has_content+ });+ if has_content {+ return None;+ }+ }+ let area = paintable_geometry::absolute_rect(self.arena, node);+ let line_height = self.arena.node_style_if_live(node)?.line_height();+ Some(CaretRect {+ rect: self.caret_rect_at_inline_start(area, Some(line_height), node)?,+ style_source: node,+ owner: node,+ node,+ })+ }++ /// The lines of the DOM text whose layout node is `text`, in DOM order.+ pub(crate) fn lines_of_text(&self, text: NodeSlotId) -> Vec<TextLine> {+ let arena = self.arena;+ let fragments = arena.text_fragments(text);+ let nodes = fragments.as_slice();+ let mut lines: Vec<TextLine> = Vec::new();+ text_fragment::for_each_fragment_of_nodes(arena, nodes, |root, _, fragment| {+ let line = InlineLine {+ root,+ index: fragment.line_index,+ };+ match lines.last_mut() {+ Some(last) if last.has_fragments && last.line == line => {+ last.start_offset = last.start_offset.min(fragment.dom_start_offset_in_node);+ last.end_offset = last.end_offset.max(fragment.dom_end_offset_in_node);+ last.end_offset_with_trailing_whitespace = last+ .end_offset_with_trailing_whitespace+ .max(fragment.dom_end_offset_with_trailing_whitespace);+ }+ _ => lines.push(TextLine {+ line,+ start_offset: fragment.dom_start_offset_in_node,+ end_offset: fragment.dom_end_offset_in_node,+ end_offset_with_trailing_whitespace: fragment.dom_end_offset_with_trailing_whitespace,+ has_fragments: true,+ }),+ }+ true+ });+ let mut roots: Vec<NodeSlotId> = nodes+ .iter()+ .filter_map(|&node| text_fragment::containing_block_paintable_of_node(arena, node))+ .collect();+ roots.dedup();+ for root in roots {+ for (index, record) in arena.committed_side_data(root).lines().iter().enumerate() {+ if let Some(position) = record.forced_break+ && record.fragment_count == 0+ && nodes.contains(&position.node)+ {+ let offset = arena.dom_offset_for_rendered_text_offset(+ position.node,+ position.rendered_offset as usize,+ RenderedTextBoundary::Start,+ );+ lines.push(TextLine {+ line: InlineLine {+ root,+ index: index as u32,+ },+ start_offset: offset,+ end_offset: offset,+ end_offset_with_trailing_whitespace: offset,+ has_fragments: false,+ });+ }+ }+ }+ lines.sort_by_key(|line| line.start_offset);+ lines+ }+}++/// The caret positions a position between the children of the box `container` can take, in the order to try them:+/// beside an atomic inline child, at the end of the text `before` (whose DOM text is `before_length` long) or at the+/// start of the text `after`, before a <br>, or else at the start of the box. `before` and `after` are the boxes of the+/// children around the position, or `NodeSlotId::INVALID`.+pub(crate) fn caret_positions_between_children(+ arena: &impl PaintRead,+ container: NodeSlotId,+ before: NodeSlotId,+ before_length: usize,+ after: NodeSlotId,+) -> impl Iterator<Item = CaretPosition> {+ let is_atomic_inline = |node| arena.node(node).is_some_and(|row| row.is_atomic_inline());+ let is_text = |node| arena.node_kind_if_live(node).is_some_and(node_facts::kind_is_text);+ let is_break = |node| arena.node_kind_if_live(node) == Some(NodeKind::BreakNode);+ [+ is_atomic_inline(before).then_some(CaretPosition::BesideAtomicInline {+ node: before,+ after: true,+ }),+ is_atomic_inline(after).then_some(CaretPosition::BesideAtomicInline {+ node: after,+ after: false,+ }),+ is_text(before).then_some(CaretPosition::Text {+ text: before,+ offset: before_length,+ downstream: true,+ }),+ is_text(after).then_some(CaretPosition::Text {+ text: after,+ offset: 0,+ downstream: true,+ }),+ is_break(after).then_some(CaretPosition::BeforeForcedBreak { node: after }),+ Some(CaretPosition::StartOfBox { node: container }),+ ]+ .into_iter()+ .flatten()+}diff --git a/Libraries/LibWeb/Rust/src/layout/query/mod.rs b/Libraries/LibWeb/Rust/src/layout/query/mod.rsnew file mode 100644index 00000000000..d12efee0680--- /dev/null+++ b/Libraries/LibWeb/Rust/src/layout/query/mod.rs@@ -0,0 +1,7 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub(crate) mod inline_cursor;diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rsindex eaf71aebfaf..61317dfa086 100644--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs@@ -11,12 +11,14 @@use super::FfiCssPixelRect;use super::node_data::NodeSlotId;+use super::query::inline_cursor::{self, CaretPosition, InlineCursor};use super::used_values::{FfiCssPixelPoint, FfiCssPixelSize};use crate::css::css_pixels::CssPixelRect;use crate::css::ffi_support::FfiUtf16View;use crate::css::style::tree::StyleNodeID;use crate::layout::text_queries::FfiDomTextRange;-use crate::painting::ffi::{FfiBoxModelMetrics, FfiCaretRectResult, FfiEmptyLineCaretRect, FfiOptionalCssPixelRect};+use crate::painting::ffi::FfiBoxModelMetrics;+use crate::painting::host::FfiCaretPaintKind;use crate::painting::paint_read::{GeometryRead, PaintRead, PaintRow, PaintSource};use crate::painting::viewport_mapping::{FfiViewportMapping, ViewportSpace};use crate::render_state::{DocumentHost, ScriptForcedRead};@@ -189,30 +191,6 @@ pub unsafe extern "C" fn layout_script_text_range_rects(});}-#[unsafe(no_mangle)]-pub extern "C" fn layout_script_text_caret_rect_in_dom_range(- host: &DocumentHost,- primary: NodeSlotId,- offset: usize,- out: &mut FfiOptionalCssPixelRect,-) {- *out = read_rows(host, |arena| {- let paintable_rows = arena;- let fragments = arena.text_fragments(primary);- let node_slots = fragments.as_slice();- match crate::painting::caret::caret_rect_in_dom_range(paintable_rows, node_slots, offset) {- Some(rect) => FfiOptionalCssPixelRect {- has_value: true,- rect: rect.into(),- },- None => FfiOptionalCssPixelRect {- has_value: false,- rect: FfiCssPixelRect::default(),- },- }- });-}-/// Calls `push_source` with what the character geometry of the text node `primary` is computed from: for each of its/// layout nodes, a retained reference to its containing block's line content, and the raw document-absolute position/// of that block. The same references at the same positions mean the same geometry. The consumer owns every reference@@ -298,94 +276,96 @@ pub unsafe extern "C" fn layout_script_text_character_x_positions(});}-#[unsafe(no_mangle)]-pub extern "C" fn layout_script_text_caret_rect_for_position(- host: &DocumentHost,- primary: NodeSlotId,- offset: usize,- affinity_is_downstream: bool,- out: &mut FfiCaretRectResult,-) {- let mut result = FfiCaretRectResult {- found: false,- rect: FfiCssPixelRect::default(),- style_source: NodeSlotId::INVALID,- owner_paintable: NodeSlotId::INVALID,- nearest_self_painting_inline: NodeSlotId::INVALID,- };- *out = read_rows(host, |arena| {- let paintable_rows = arena;- let fragments = arena.text_fragments(primary);- let node_slots = fragments.as_slice();- let Some(answer) =- crate::painting::caret::caret_rect_for_position(paintable_rows, node_slots, offset, affinity_is_downstream)- else {- return result;- };- result.found = true;- result.rect = answer.rect.into();- result.style_source = answer.style_source;- result.owner_paintable = answer.owner;- result.nearest_self_painting_inline =- crate::painting::fragment_ownership::nearest_self_painting_inline_box(paintable_rows, answer.node)- .unwrap_or(NodeSlotId::INVALID);- result- });+/// A caret position as the host names it: `offset` in the DOM text whose layout node is `node`, or, where `node` is the+/// box of an element, the position between the children of the element whose boxes are `child_before` and+/// `child_after` (`NodeSlotId::INVALID` for none), where the DOM text of `child_before` is `child_before_length` long.+#[repr(C)]+pub struct FfiCaretPosition {+ pub node: NodeSlotId,+ pub offset: usize,+ pub downstream: bool,+ pub child_before: NodeSlotId,+ pub child_before_length: usize,+ pub child_after: NodeSlotId,}-#[unsafe(no_mangle)]-pub extern "C" fn layout_script_atomic_inline_caret_rect_for_position(- host: &DocumentHost,- primary: NodeSlotId,- after: bool,- out: &mut FfiCaretRectResult,-) {- let mut result = FfiCaretRectResult {- found: false,- rect: FfiCssPixelRect::default(),- style_source: NodeSlotId::INVALID,- owner_paintable: NodeSlotId::INVALID,- nearest_self_painting_inline: NodeSlotId::INVALID,- };- *out = read_rows(host, |arena| {- let paintable_rows = arena;- let Some(answer) = crate::painting::caret::caret_rect_for_atomic_inline(paintable_rows, primary, after) else {- return result;- };- result.found = true;- result.rect = answer.rect.into();- result.style_source = answer.style_source;- result.owner_paintable = answer.owner;- result.nearest_self_painting_inline =- crate::painting::fragment_ownership::nearest_self_painting_inline_box(paintable_rows, answer.node)- .unwrap_or(NodeSlotId::INVALID);- result- });+/// The caret layout gives a position, as the recorder paints it and in the layout viewport.+#[repr(C)]+pub struct FfiCaret {+ pub found: bool,+ pub paint: FfiCaretPaintKind,+ pub block: NodeSlotId,+ pub owner: NodeSlotId,+ pub rect: FfiCssPixelRect,+ pub viewport_rect: FfiCssPixelRect,+ pub style_source: NodeSlotId,}#[unsafe(no_mangle)]-pub extern "C" fn layout_script_paintable_empty_line_caret_rect(+pub extern "C" fn layout_script_caret(host: &DocumentHost,- block: NodeSlotId,- primary: NodeSlotId,- offset: usize,- out: &mut FfiEmptyLineCaretRect,+ position: FfiCaretPosition,+ viewport_mapping: FfiViewportMapping<'_>,+ out: &mut FfiCaret,) {- let mut result = FfiEmptyLineCaretRect {- has_value: false,- rect: FfiCssPixelRect::default(),- style_source: NodeSlotId::INVALID,- };*out = read_rows(host, |arena| {- let fragments = arena.text_fragments(primary);- if let Some(caret) =- crate::painting::caret::caret_rect_on_empty_line(arena, block, fragments.as_slice(), offset)+ let cursor = InlineCursor::new(arena);+ let caret = if arena+ .node_kind_if_live(position.node)+ .is_some_and(super::node_facts::kind_is_text){- result.has_value = true;- result.rect = caret.rect.into();- result.style_source = caret.style_source;+ cursor.caret_rect(CaretPosition::Text {+ text: position.node,+ offset: position.offset,+ downstream: position.downstream,+ })+ } else {+ inline_cursor::caret_positions_between_children(+ arena,+ position.node,+ position.child_before,+ position.child_before_length,+ position.child_after,+ )+ .find_map(|candidate| cursor.caret_rect(candidate))+ };+ let Some(caret) = caret else {+ return FfiCaret {+ found: false,+ paint: FfiCaretPaintKind::None,+ block: NodeSlotId::INVALID,+ owner: NodeSlotId::INVALID,+ rect: FfiCssPixelRect::default(),+ viewport_rect: FfiCssPixelRect::default(),+ style_source: NodeSlotId::INVALID,+ };+ };+ // A box with no line content around the caret paints the caret itself.+ let at_start_of_box = caret.owner == caret.node;+ FfiCaret {+ found: true,+ paint: if at_start_of_box && crate::painting::node_painting::is_fragmented_inline(arena, caret.owner) {+ FfiCaretPaintKind::EmptyInline+ } else {+ FfiCaretPaintKind::InBlock+ },+ block: caret.owner,+ owner: crate::painting::fragment_ownership::nearest_self_painting_inline_box(arena, caret.node)+ .filter(|_| !at_start_of_box)+ .unwrap_or(NodeSlotId::INVALID),+ rect: caret.rect.into(),+ viewport_rect: viewport_mapping+ .mapping()+ .line_content_rect_to_viewport(+ arena,+ caret.owner,+ caret.node,+ caret.rect,+ ViewportSpace::LayoutViewport,+ )+ .into(),+ style_source: caret.style_source,}- result});}@@ -517,30 +497,19 @@ pub extern "C" fn layout_script_paintable_unbroken_border_box_size(});}+/// Whether the forced break `forced_break` ends an empty line of `block`.#[unsafe(no_mangle)]-pub extern "C" fn layout_script_empty_line_ended_by_forced_break_position(+pub extern "C" fn layout_script_forced_break_ends_empty_line(host: &DocumentHost,block: NodeSlotId,forced_break: NodeSlotId,- out: &mut super::used_values::FfiCssPixelPoint,) -> bool {- let position = read_rows(host, |arena| {- if !arena.paintable_row_is_populated(block) {- return None;- }- let side = arena.committed_side_data(block);- let line = side.lines().iter().find(|line| {- line.forced_break.is_some_and(|position| position.node == forced_break) && line.fragment_count == 0- })?;- let root_position =- crate::painting::paintable_geometry::LineRootPositions::new(arena, block).of_fragment(line.box_fragment);- Some(CssPixelRect::from(line.rect).translated_by(root_position).location())- });- let Some(position) = position else {- return false;- };- *out = position.into();- true+ read_rows(host, |arena| {+ arena.paintable_row_is_populated(block)+ && arena.committed_side_data(block).lines().iter().any(|line| {+ line.fragment_count == 0 && line.forced_break.is_some_and(|position| position.node == forced_break)+ })+ })}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs b/Libraries/LibWeb/Rust/src/layout/shell_reads.rsindex 9c526032104..53ca0321ab6 100644--- a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs+++ b/Libraries/LibWeb/Rust/src/layout/shell_reads.rs@@ -295,13 +295,6 @@ pub extern "C" fn layout_row_paintable_is_positioned(host: &DocumentHost, slot:})}-#[unsafe(no_mangle)]-pub extern "C" fn layout_row_paintable_has_child_paintables(host: &DocumentHost, slot: NodeSlotId) -> bool {- read_rows(host, |rows| {- crate::painting::paint_order::first_paint_child(rows, slot).is_some()- })-}-#[unsafe(no_mangle)]pub extern "C" fn layout_row_paintable_is_chrome_mirrored(host: &DocumentHost, slot: NodeSlotId) -> bool {read_rows(host, |rows| {diff --git a/Libraries/LibWeb/Rust/src/painting/caret.rs b/Libraries/LibWeb/Rust/src/painting/caret.rsdeleted file mode 100644index 2c68e925202..00000000000--- a/Libraries/LibWeb/Rust/src/painting/caret.rs+++ /dev/null@@ -1,193 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use crate::css::css_pixels::{CssPixelRect, CssPixels};-use crate::layout::node_data::NodeSlotId;-use crate::painting::paint_read::PaintRead;-use crate::painting::paintable_data::{FragmentRecord, SELECTION_STATE_START_AND_END};-use crate::painting::paintable_geometry;-use crate::painting::text_fragment::{self, CaretMatch};--pub(crate) struct CaretRectResult {- pub rect: CssPixelRect,- pub style_source: NodeSlotId,- pub owner: NodeSlotId,- pub node: NodeSlotId,-}--fn caret_rect_in_fragment(- layout_arena: &impl PaintRead,- owner: NodeSlotId,- fragment: &FragmentRecord,- offset: usize,- affinity_is_downstream: bool,-) -> CaretRectResult {- let mut rect = text_fragment::range_rect(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset);- if let Some(offsets) =- text_fragment::compute_selection_offsets(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset)- && let Some(run) = &fragment.glyph_run- && let Some(coordinate) = run- .cluster_geometry()- .x_for_offset(offsets.start, affinity_is_downstream)- {- let origin = text_fragment::absolute_rect(layout_arena, fragment);- let coordinate = CssPixels::nearest_value_for_f32(coordinate);- if text_fragment::is_horizontal(fragment) {- rect.x = origin.x + coordinate;- } else {- rect.y = origin.y + coordinate;- }- }- CaretRectResult {- rect,- style_source: text_fragment::style_source(layout_arena, fragment),- owner,- node: fragment.layout_node,- }-}--pub(crate) fn caret_rect_for_position(- layout_arena: &impl PaintRead,- node_slots: &[NodeSlotId],- offset: usize,- affinity_is_downstream: bool,-) -> Option<CaretRectResult> {- let mut fallback: Option<(NodeSlotId, u32)> = None;- let mut direct: Option<(NodeSlotId, u32)> = None;- text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |block, index, fragment| {- // A caret at the end of the text in front of a writing suggestion is in front of the suggestion, whichever way- // it leans: The text after the caret starts only after the suggestion.- let caret_match = match text_fragment::caret_match(fragment, offset, affinity_is_downstream) {- CaretMatch::SoftWrapFallback if layout_arena.text_precedes_writing_suggestion(fragment.layout_node) => {- CaretMatch::Direct- }- caret_match => caret_match,- };- match caret_match {- CaretMatch::None => true,- CaretMatch::SoftWrapFallback => {- if fallback.is_none() {- fallback = Some((block, index));- }- true- }- CaretMatch::Direct => {- direct = Some((block, index));- false- }- }- });- let (block, index) = direct.or(fallback)?;- let side = layout_arena.committed_side_data(block);- let fragment = &side.fragments()[index as usize];- Some(caret_rect_in_fragment(- layout_arena,- block,- fragment,- offset,- affinity_is_downstream,- ))-}--/// The caret on an empty line of `block` that a preserved newline at `offset` in the text laid out in the fragments of-/// `node_slots` ends. No fragment holds such a position.-pub(crate) fn caret_rect_on_empty_line(- layout_arena: &impl PaintRead,- block: NodeSlotId,- node_slots: &[NodeSlotId],- offset: usize,-) -> Option<CaretRectResult> {- if !layout_arena.paintable_row_is_populated(block) {- return None;- }- let side = layout_arena.committed_side_data(block);- let (line, node) = side.lines().iter().find_map(|line| {- let position = line- .forced_break- .filter(|position| line.fragment_count == 0 && node_slots.contains(&position.node))?;- let line_offset = layout_arena.dom_offset_for_rendered_text_offset(- position.node,- position.rendered_offset as usize,- crate::layout::RenderedTextBoundary::Start,- );- (line_offset == offset).then_some((line, position.node))- })?;- let root_position = paintable_geometry::LineRootPositions::new(layout_arena, block).of_fragment(line.box_fragment);- Some(CaretRectResult {- rect: CssPixelRect::from(line.rect).translated_by(root_position),- style_source: layout_arena.node_parent_if_live(node)?,- owner: block,- node,- })-}--pub(crate) fn caret_rect_in_dom_range(- layout_arena: &impl PaintRead,- node_slots: &[NodeSlotId],- offset: usize,-) -> Option<CssPixelRect> {- let mut rect = None;- text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |_, _, fragment| {- let dom_start = fragment.dom_start_offset_in_node;- let dom_end = fragment.dom_end_offset_in_node;- if offset < dom_start || offset > dom_end {- return true;- }- rect = Some(text_fragment::range_rect(- layout_arena,- fragment,- SELECTION_STATE_START_AND_END,- offset,- offset,- ));- false- });- rect-}--// INTEROP: A caret beside an atomic inline spans its line box, with the inline coordinate at the box's edge.-pub(crate) fn caret_rect_for_atomic_inline(- layout_arena: &impl PaintRead,- node: NodeSlotId,- after: bool,-) -> Option<CaretRectResult> {- let owner = text_fragment::containing_block_paintable_of_node(layout_arena, node)?;- let side = layout_arena.committed_side_data(owner);- let fragment = side- .fragments()- .iter()- .find(|fragment| fragment.layout_node == node && fragment.is_atomic_inline)?;- let fragment_rect = text_fragment::absolute_rect(layout_arena, fragment);- let item_rect = crate::painting::paintable_geometry::absolute_border_box_rect(layout_arena, node);- let mut rect = text_fragment::absolute_line_box_rect(layout_arena, owner, fragment);- // The line box is unpositioned; move its block-axis extent with the atomic box and its inline ancestors.- rect.x += item_rect.x - fragment_rect.x + fragment.relpos_delta.x;- rect.y += item_rect.y - fragment_rect.y + fragment.relpos_delta.y;- let horizontal = text_fragment::fragment_is_horizontal(fragment);- let at_end = after != layout_arena.node_style_if_live(node)?.inline_axis_is_reverse();- let thickness = crate::css::css_pixels::CssPixels::from_integer(1);- if horizontal {- rect.x = if at_end {- item_rect.x + item_rect.width- } else {- item_rect.x- };- rect.width = thickness;- } else {- rect.y = if at_end {- item_rect.y + item_rect.height- } else {- item_rect.y- };- rect.height = thickness;- }- Some(CaretRectResult {- rect,- style_source: node,- owner,- node,- })-}diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 96f9c4a84f6..8bae0eec764 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -717,22 +717,6 @@ pub extern "C" fn render_state_paintable_svg_text_character_cells(})}-#[repr(C)]-pub struct FfiCaretRectResult {- pub found: bool,- pub rect: FfiCssPixelRect,- pub style_source: NodeSlotId,- pub owner_paintable: NodeSlotId,- pub nearest_self_painting_inline: NodeSlotId,-}--#[repr(C)]-pub struct FfiEmptyLineCaretRect {- pub has_value: bool,- pub rect: FfiCssPixelRect,- pub style_source: NodeSlotId,-}-/// The part of `rect`, in the viewport, that the content clips of the containing blocks of the box in `slot` leave.#[unsafe(no_mangle)]pub extern "C" fn render_state_visible_rect_in_containing_blocks(@@ -792,24 +776,6 @@ pub unsafe extern "C" fn render_state_collect_boxes_with_auto_content_visibility}}-#[unsafe(no_mangle)]-pub extern "C" fn render_state_inline_paintable_has_content_pieces(- host: &DocumentHost,- inline_paintable: NodeSlotId,-) -> bool {- read_arena(host, node_read(), inline_paintable, |arena, inline_paintable| {- let mut has_content = false;- with_inline_pieces(&arena.paintable_rows(), inline_paintable, |piece| {- if !piece.is_geometry_only_placeholder {- has_content = true;- return false;- }- true- });- has_content- })-}-#[repr(C)]pub struct FfiOptionalCssPixelPoint {pub has_value: bool,@@ -881,8 +847,7 @@ pub unsafe extern "C" fn render_state_text_visual_lines() {let lines = {read_arena(host, node_read(), primary, |arena, primary| {- let fragments = arena.text_fragments(primary);- crate::painting::visual_lines::collect_visual_lines(&arena.paintable_rows(), fragments.as_slice())+ crate::layout::query::inline_cursor::InlineCursor::new(&arena.paintable_rows()).lines_of_text(primary)})};for line in lines {@@ -895,8 +860,8 @@ pub unsafe extern "C" fn render_state_text_visual_lines(end_offset: line.end_offset,end_offset_with_trailing_whitespace: line.end_offset_with_trailing_whitespace,has_fragments: line.has_fragments,- owner_paintable: line.owner.index,- line_index: line.line_index,+ owner_paintable: line.line.root.index,+ line_index: line.line.index,},);}@@ -1021,12 +986,6 @@ pub extern "C" fn render_state_visual_line_offset_closest_to_inline_coordinate()}-#[repr(C)]-pub struct FfiOptionalCssPixelRect {- pub has_value: bool,- pub rect: FfiCssPixelRect,-}-/// # Safety////// `host` must be a live document host, on its document's thread.diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex 3e2c3c50dca..4d78ec000ab 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -474,40 +474,6 @@ pub unsafe extern "C" fn render_state_take_recording_trace(true}-/// # Safety-///-/// `host` must be a live document host, on its document's thread.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn render_state_for_each_subtree_fragment_rect(- host: &crate::render_state::DocumentHost,- root: NodeSlotId,- context: *mut c_void,- consume: unsafe extern "C" fn(*mut c_void, NodeSlotId, FfiCssPixelRect),-) {- let rects = {- read_arena(host, super::node_read(), root, |arena, root| {- let paintable_rows = arena.paintable_rows();- let mut rects = Vec::new();- if !paintable_rows.paintable_row_is_populated(root) {- return rects;- }- crate::painting::paint_order::for_each_in_paint_subtree(&paintable_rows, root, |current| {- for fragment in arena.committed_side_data(current).fragments() {- rects.push((- fragment.layout_node,- crate::painting::text_fragment::absolute_rect(&paintable_rows, fragment).into(),- ));- }- });- rects- })- };- for (layout_node, rect) in rects {- // SAFETY: The consumer copies its plain-data arguments synchronously.- unsafe { consume(context, layout_node, rect) };- }-}-/// The recorder state of `host`'s document, for a recording to take, once the last recording was published.fn take_recorder_for_recording(host: &crate::render_state::DocumentHost,diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rsindex 19003f03542..f53fb5ae663 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/resolve.rs@@ -9,7 +9,6 @@ use crate::layout::node_data::{NodeFlag, NodeKind};use crate::layout::node_facts::NodeShape;use crate::painting::host::{FfiCaretBoundaryKind, FfiNodeIdentity, FfiResolvedCaret};use crate::painting::paint_read::{PaintRead, PaintRow};-use crate::painting::paintable_data::SELECTION_STATE_START_AND_END;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)@@ -113,7 +112,9 @@ impl HitTestList {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 = fragment_caret_range_rect(arena, fragment, offset);+ 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,@@ -241,21 +242,3 @@ pub(crate) fn fragment_index_in_node_for_point(}).unwrap_or(0)}--fn fragment_caret_range_rect(- arena: &impl PaintRead,- fragment: &crate::painting::paintable_data::FragmentRecord,- offset: usize,-) -> CssPixelRect {- let paintable_rows = arena;- let Some(offsets) = crate::painting::text_fragment::compute_selection_offsets(- paintable_rows,- fragment,- SELECTION_STATE_START_AND_END,- offset,- offset,- ) else {- return CssPixelRect::default();- };- crate::painting::text_fragment::rect_for_selection_offsets(paintable_rows, fragment, offsets)-}diff --git a/Libraries/LibWeb/Rust/src/painting/host/paint.rs b/Libraries/LibWeb/Rust/src/painting/host/paint.rsindex 266de70a356..5112bad9017 100644--- a/Libraries/LibWeb/Rust/src/painting/host/paint.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/paint.rs@@ -211,7 +211,6 @@ impl FfiRecordingInputs {#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]-#[expect(dead_code, reason = "C++ constructs the variants")]pub enum FfiCaretPaintKind {None,/// `block` paints the caret, in the fragment run owned by the self-painting inline `owner`diff --git a/Libraries/LibWeb/Rust/src/painting/mod.rs b/Libraries/LibWeb/Rust/src/painting/mod.rsindex 5d1915751b7..22853141747 100644--- a/Libraries/LibWeb/Rust/src/painting/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/mod.rs@@ -6,7 +6,6 @@pub mod border_radii;pub(crate) mod border_shape;-pub(crate) mod caret;pub(crate) mod chrome_geometry;pub(crate) mod client_rects;pub(crate) mod content_visibility;diff --git a/Libraries/LibWeb/Rust/src/painting/scroll_chain.rs b/Libraries/LibWeb/Rust/src/painting/scroll_chain.rsindex ed8a7283114..f97541abf55 100644--- a/Libraries/LibWeb/Rust/src/painting/scroll_chain.rs+++ b/Libraries/LibWeb/Rust/src/painting/scroll_chain.rs@@ -7,9 +7,10 @@use crate::css::css_enums::writing_mode;use crate::css::css_pixels::{CssPixelPoint, CssPixelRect, CssPixels};use crate::layout::node_data::{NodeKind, NodeSlotId};+use crate::layout::query::inline_cursor::{CaretPosition, InlineCursor};use crate::painting::paintable_geometry::{absolute_padding_box_rect, has_scrollable_overflow};use crate::painting::paintable_rows::PaintableRowsRead;-use crate::painting::{caret, chrome_geometry, scroll_snap};+use crate::painting::{chrome_geometry, scroll_snap};/// The nearest box, `start` included, that keeps a scroll step by the delta to itself: neither it nor a box inside it/// passes the step on to a scroller around it. A step belongs to one scroller, and a touchpad rarely moves along one@@ -65,14 +66,11 @@ pub(crate) fn scroll_target_for_text_position(affinity_is_downstream: bool,scroll_block_axis: bool,) -> Option<(NodeSlotId, CssPixelPoint)> {- let fragments = arena.text_fragments(text);- let node_slots = fragments.as_slice();- let caret = match caret::caret_rect_for_position(arena, node_slots, offset, affinity_is_downstream) {- Some(caret) => caret,- // No fragment holds the position: the caret sits on an empty line of the block that lays the text out.- None => std::iter::successors(arena.node_parent_if_live(text), |&node| arena.node_parent_if_live(node))- .find_map(|block| caret::caret_rect_on_empty_line(arena, block, node_slots, offset))?,- };+ let caret = InlineCursor::new(arena).caret_rect(CaretPosition::Text {+ text,+ offset,+ downstream: affinity_is_downstream,+ })?;let style = arena.node_style_if_live(caret.style_source)?;let horizontal = style.writing_mode() == writing_mode::HORIZONTAL_TB;let one = CssPixels::from_integer(1);diff --git a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs b/Libraries/LibWeb/Rust/src/painting/visual_lines.rsindex 1153441a639..26bf2e9ac68 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_lines.rs@@ -9,75 +9,6 @@ use crate::layout::node_data::NodeSlotId;use crate::painting::paint_read::PaintRead;use crate::painting::text_fragment;-pub(crate) struct RecordVisualLine {- pub start_offset: usize,- pub end_offset: usize,- pub end_offset_with_trailing_whitespace: usize,- pub has_fragments: bool,- pub owner: NodeSlotId,- pub line_index: u32,-}--pub(crate) fn collect_visual_lines(layout_arena: &impl PaintRead, node_slots: &[NodeSlotId]) -> Vec<RecordVisualLine> {- let mut lines: Vec<RecordVisualLine> = Vec::new();- text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |block, _, fragment| {- let dom_start = fragment.dom_start_offset_in_node;- let dom_end = fragment.dom_end_offset_in_node;- let dom_end_with_trailing_whitespace = fragment.dom_end_offset_with_trailing_whitespace;- if let Some(line) = lines.last_mut()- && line.has_fragments- && line.owner == block- && line.line_index == fragment.line_index- {- line.start_offset = line.start_offset.min(dom_start);- line.end_offset = line.end_offset.max(dom_end);- line.end_offset_with_trailing_whitespace = line- .end_offset_with_trailing_whitespace- .max(dom_end_with_trailing_whitespace);- } else {- lines.push(RecordVisualLine {- start_offset: dom_start,- end_offset: dom_end,- end_offset_with_trailing_whitespace: dom_end_with_trailing_whitespace,- has_fragments: true,- owner: block,- line_index: fragment.line_index,- });- }- true- });- // A preserved newline that ends a line with nothing on it gives the line no fragment.- let mut blocks: Vec<NodeSlotId> = node_slots- .iter()- .filter_map(|&node| text_fragment::containing_block_paintable_of_node(layout_arena, node))- .collect();- blocks.dedup();- for block in blocks {- for (line_index, line) in layout_arena.committed_side_data(block).lines().iter().enumerate() {- if let Some(position) = line.forced_break- && line.fragment_count == 0- && node_slots.contains(&position.node)- {- let offset = layout_arena.dom_offset_for_rendered_text_offset(- position.node,- position.rendered_offset as usize,- crate::layout::RenderedTextBoundary::Start,- );- lines.push(RecordVisualLine {- start_offset: offset,- end_offset: offset,- end_offset_with_trailing_whitespace: offset,- has_fragments: false,- owner: block,- line_index: line_index as u32,- });- }- }- }- lines.sort_by_key(|line| line.start_offset);- lines-}-fn fragments_of_line(layout_arena: &impl PaintRead,owner_paintable: u32,