Skip to content

Truly independent web browser

LibWeb: Navigate contenteditable lines with InlineCursor

Aliaksandr Kalenik7963cc1f6e36
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index d5e34670c69..43cc32d1a99 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -12381,30 +12381,6 @@ Optional<Painting::CaretPosition> Document::caret_position_from_point_for_select
return query->list().caret_position_from_point(read, position, *query, Painting::CaretPositionMode::Selection, constraint_scope);
}
-Optional<Painting::CaretPosition> Document::caret_position_at_line_edge(Layout::BegunRead const& read, Node const& node, size_t offset, TextAffinity affinity, Painting::CaretLineEdge edge)
-{
- auto query = prepare_hit_test_query(read);
- if (!query.has_value())
- return {};
- return query->list().caret_position_at_line_edge(read, node, offset, affinity, edge);
-}
-
-Optional<Painting::CaretPosition> Document::caret_position_on_adjacent_line(Layout::BegunRead const& read, Node const& node, size_t offset, TextAffinity affinity, Painting::CaretLineDirection direction, CSSPixels inline_coordinate, Node const& scope)
-{
- auto query = prepare_hit_test_query(read);
- if (!query.has_value())
- return {};
- return query->list().caret_position_on_adjacent_line(read, node, offset, affinity, direction, inline_coordinate, scope);
-}
-
-Optional<CSSPixels> Document::caret_line_block_coordinate(Layout::BegunRead const& read, Node const& node, size_t offset, TextAffinity affinity)
-{
- auto query = prepare_hit_test_query(read);
- if (!query.has_value())
- return {};
- return query->list().caret_line_block_coordinate(read, node, offset, affinity);
-}
-
TraversalDecision Document::hit_test_all(Layout::BegunRead const& read, CSSPixelPoint position, Function<TraversalDecision(Painting::HitTestResult)> const& callback)
{
auto query = prepare_hit_test_query(read);
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index e29e47f9475..a1c72aa20f0 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -1701,9 +1701,6 @@ public:
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_at_line_edge(Layout::BegunRead const& read, Node const&, size_t offset, TextAffinity, Painting::CaretLineEdge);
- Optional<Painting::CaretPosition> caret_position_on_adjacent_line(Layout::BegunRead const& read, Node const&, size_t offset, TextAffinity, Painting::CaretLineDirection, CSSPixels inline_coordinate, Node const& scope);
- Optional<CSSPixels> caret_line_block_coordinate(Layout::BegunRead const& read, Node const&, size_t offset, TextAffinity);
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/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cpp
index 22a31819012..db86be10a86 100644
--- a/Libraries/LibWeb/Painting/BoxViews.cpp
+++ b/Libraries/LibWeb/Painting/BoxViews.cpp
@@ -371,28 +371,33 @@ CSSPixelPoint box_type_agnostic_position(Layout::Node const& node)
return absolute_position(node);
}
-Layout::RustFFI::FfiCaret caret_at_position(Layout::BegunRead const& read, DOM::Position const& position, Layout::RustFFI::FfiViewportMapping viewport_mapping)
+Optional<Layout::RustFFI::FfiCaretPosition> layout_caret_position(Layout::BegunRead const& read, DOM::Node const& node, size_t offset, TextAffinity affinity)
{
- Layout::RustFFI::FfiCaret caret {};
- auto const& node = *position.node();
auto const* layout_node = node.unsafe_layout_node(read);
if (!layout_node)
- return caret;
+ return {};
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 };
};
- auto offset = position.offset();
auto const* child_before = offset > 0 ? node.child_at_index(offset - 1) : nullptr;
- Layout::RustFFI::FfiCaretPosition ffi_position {
+ return Layout::RustFFI::FfiCaretPosition {
.node = Layout::Node::slot_id(layout_node),
.offset = offset,
- .downstream = position.affinity() == TextAffinity::Downstream,
+ .downstream = 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::layout_script_caret(layout_node->document_host(), ffi_position, viewport_mapping, &caret);
+}
+
+Layout::RustFFI::FfiCaret caret_at_position(Layout::BegunRead const& read, DOM::Position const& position, Layout::RustFFI::FfiViewportMapping viewport_mapping)
+{
+ Layout::RustFFI::FfiCaret caret {};
+ auto ffi_position = layout_caret_position(read, *position.node(), position.offset(), position.affinity());
+ if (!ffi_position.has_value())
+ return caret;
+ Layout::RustFFI::layout_script_caret(position.node()->unsafe_layout_node(read)->document_host(), *ffi_position, viewport_mapping, &caret);
return caret;
}
diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.h
index 891ab45b00c..f4c175e1b43 100644
--- a/Libraries/LibWeb/Painting/BoxViews.h
+++ b/Libraries/LibWeb/Painting/BoxViews.h
@@ -15,6 +15,7 @@
#include <LibWeb/Layout/NodeArena.h>
#include <LibWeb/Painting/BoxModelMetrics.h>
#include <LibWeb/Painting/PaintableTypes.h>
+#include <LibWeb/TextAffinity.h>
namespace Web::Painting {
@@ -89,6 +90,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&);
+// The position `offset` in `node` as layout names it, if `node` has a layout node.
+WEB_API Optional<Layout::RustFFI::FfiCaretPosition> layout_caret_position(Layout::BegunRead const&, DOM::Node const&, size_t offset, TextAffinity);
// 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);
diff --git a/Libraries/LibWeb/Painting/Forward.h b/Libraries/LibWeb/Painting/Forward.h
index d4942ebb069..c9738bb8128 100644
--- a/Libraries/LibWeb/Painting/Forward.h
+++ b/Libraries/LibWeb/Painting/Forward.h
@@ -14,8 +14,6 @@ namespace Web::Painting {
class DocumentPaintState;
class HitTestDisplayList;
class HitTestQuery;
-enum class CaretLineDirection : u8;
-enum class CaretLineEdge : u8;
enum class CaretPositionMode : u8;
enum class HitTestListAdoption : u8;
struct CaretPosition;
diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp
index 1335b35621c..574e9e606c7 100644
--- a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp
+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Noncopyable.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/Layout/LayoutRustFFI.h>
@@ -100,36 +99,6 @@ static Layout::RustFFI::FfiNodeIdentity ffi_identity_of(DOM::Node const* node)
return { .style_node = identity.style_node().value(), .is_document = identity == DOM::NodeIdentity::of_document() };
}
-// A caret boundary resolved to the node identities a hit test item is compared against. The query
-// asks five questions of every candidate item, and each one is answered by the node a child of the
-// boundary's node names, so they are all resolved here, once, before the query runs.
-// The query points into the descent this context owns, so the context stays where it was built.
-struct CaretPositionQueryContext {
- AK_MAKE_NONCOPYABLE(CaretPositionQueryContext);
- AK_MAKE_NONMOVABLE(CaretPositionQueryContext);
-
-public:
- Vector<u32, 8> boundary_descent;
- Layout::RustFFI::FfiCaretPositionQuery query {};
-
- CaretPositionQueryContext(DOM::Node const& node, size_t offset)
- {
- auto style_node_of = [](DOM::Node const* node) { return Layout::Node::style_node_of(node).value(); };
- query.node = style_node_of(&node);
- auto const* child_at_offset = node.child_at_index(offset);
- query.child_at_offset = style_node_of(child_at_offset);
- if (offset > 0) {
- auto const* child_before_offset = node.child_at_index(offset - 1);
- query.child_before_offset = style_node_of(child_before_offset);
- query.child_before_offset_length = child_before_offset ? child_before_offset->length() : 0;
- }
- for (auto const* descendant = child_at_offset; descendant; descendant = descendant->first_child())
- boundary_descent.append(style_node_of(descendant));
- query.boundary_descent = boundary_descent.data();
- query.boundary_descent_len = boundary_descent.size();
- }
-};
-
Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Layout::RustFFI::FfiTopmostItem const& item)
{
if (!item.has_item)
@@ -288,42 +257,6 @@ Optional<CaretPosition> HitTestDisplayList::caret_position_from(Layout::RustFFI:
};
}
-Optional<CaretPosition> HitTestDisplayList::caret_position_at_line_edge(Layout::BegunRead const& read, DOM::Node const& node, size_t offset, TextAffinity affinity, CaretLineEdge edge) const
-{
- if (!is_current())
- return {};
- CaretPositionQueryContext context { node, offset };
- auto type = first_is_one_of(edge, CaretLineEdge::Start, CaretLineEdge::Left) ? CaretPositionType::Before : CaretPositionType::After;
- auto physical = first_is_one_of(edge, CaretLineEdge::Left, CaretLineEdge::Right);
- QueryContext query_context { nullptr, m_arena->document() };
- auto scope = physical ? const_cast<DOM::Node&>(node).editing_host() : nullptr;
- Layout::RustFFI::FfiCaretAt caret_at;
- Layout::RustFFI::layout_hit_test_caret_at_line_edge(m_arena->host(), &read, query_context.callbacks(), context.query, offset, affinity == TextAffinity::Downstream, to_underlying(type), physical, ffi_identity_of(scope.ptr()), &caret_at);
- return caret_position_from(caret_at);
-}
-
-Optional<CaretPosition> HitTestDisplayList::caret_position_on_adjacent_line(Layout::BegunRead const& read, DOM::Node const& node, size_t offset, TextAffinity affinity, CaretLineDirection direction, CSSPixels inline_coordinate, DOM::Node const& scope) const
-{
- if (!is_current())
- return {};
- CaretPositionQueryContext position_context { node, offset };
- QueryContext context { nullptr, m_arena->document() };
- Layout::RustFFI::FfiCaretAt caret_at;
- Layout::RustFFI::layout_hit_test_caret_on_adjacent_line(m_arena->host(), &read, context.callbacks(), position_context.query, offset, affinity == TextAffinity::Downstream, direction == CaretLineDirection::Next ? 1 : 0, inline_coordinate.raw_value(), ffi_identity_of(&scope), &caret_at);
- return caret_position_from(caret_at);
-}
-
-Optional<CSSPixels> HitTestDisplayList::caret_line_block_coordinate(Layout::BegunRead const& read, DOM::Node const& node, size_t offset, TextAffinity affinity) const
-{
- if (!is_current())
- return {};
- CaretPositionQueryContext context { node, offset };
- i32 coordinate = 0;
- if (!Layout::RustFFI::layout_hit_test_caret_line_block_coordinate(m_arena->host(), &read, context.query, offset, affinity == TextAffinity::Downstream, &coordinate))
- return {};
- return CSSPixels::from_raw(coordinate);
-}
-
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
{
QueryContext context { &query, m_arena->document() };
diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.h b/Libraries/LibWeb/Painting/HitTestDisplayList.h
index fa14c15a016..a775fdb120e 100644
--- a/Libraries/LibWeb/Painting/HitTestDisplayList.h
+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.h
@@ -28,18 +28,6 @@ enum class CaretPositionMode : u8 {
Selection,
};
-enum class CaretLineEdge : u8 {
- Start,
- End,
- Left,
- Right,
-};
-
-enum class CaretLineDirection : u8 {
- Previous,
- Next,
-};
-
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
@@ -87,13 +75,6 @@ public:
// 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;
- // Resolve Home/End against the painted line containing the caret. A visual line can span several DOM nodes and
- // atomic inline boxes, so a text-node or block-element boundary is not necessarily a rendered line boundary.
- [[nodiscard]] Optional<CaretPosition> caret_position_at_line_edge(Layout::BegunRead const& read, DOM::Node const&, size_t offset, TextAffinity, CaretLineEdge) const;
- // Find the visually adjacent caret line within scope, preserving the requested inline-axis coordinate. This is a
- // rendered-content query: DOM adjacency alone cannot describe wrapping, writing modes, floats, or empty lines.
- [[nodiscard]] Optional<CaretPosition> caret_position_on_adjacent_line(Layout::BegunRead const& read, DOM::Node const&, size_t offset, TextAffinity, CaretLineDirection, CSSPixels inline_coordinate, DOM::Node const& scope) const;
- [[nodiscard]] Optional<CSSPixels> caret_line_block_coordinate(Layout::BegunRead const& read, DOM::Node const&, size_t offset, TextAffinity) const;
TraversalDecision hit_test_all(Layout::BegunRead const& read, CSSPixelPoint, HitTestQuery const&, Function<TraversalDecision(HitTestResult)> const&) const;
private:
@@ -110,12 +91,6 @@ private:
Compositing::ContextRef context() const { return facts.context; }
};
- enum class CaretPositionType : u8 {
- Closest,
- Before,
- After,
- };
-
struct TopmostItem {
size_t index { 0 };
CSSPixelPoint local_point;
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index f2038a63508..00ff91fa797 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -3135,6 +3135,7 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/render_state/clock.rs"),
manifest_dir.join("src/render_state/clock/hover.rs"),
manifest_dir.join("src/layout/script_entries.rs"),
+ manifest_dir.join("src/layout/query/inline_cursor.rs"),
manifest_dir.join("src/painting/paint_changes.rs"),
manifest_dir.join("src/painting/ffi/main_thread_entries.rs"),
manifest_dir.join("src/painting/paint_passes.rs"),
diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
index fa185c68df3..3df37e20a52 100644
--- a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
@@ -8,8 +8,8 @@
//! 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::css::css_enums::{white_space_collapse, writing_mode};
+use crate::css::css_pixels::{CssPixelPoint, CssPixelRect, CssPixels};
use crate::layout::RenderedTextBoundary;
use crate::layout::inline_content::LineRecord;
use crate::layout::node_data::{NodeKind, NodeSlotId};
@@ -70,7 +70,8 @@ pub(crate) struct CaretRect {
}
#[derive(Clone, Copy, PartialEq, Eq)]
-pub(crate) enum LineEdge {
+#[repr(u8)]
+pub enum LineEdge {
Start,
End,
Left,
@@ -87,6 +88,14 @@ pub(crate) struct TextLine {
pub(crate) has_fragments: bool,
}
+#[derive(Clone, Copy)]
+struct LineExtent {
+ inline_start: CssPixels,
+ inline_end: CssPixels,
+ block_start: CssPixels,
+ block_end: CssPixels,
+}
+
pub(crate) struct InlineCursor<'a, A: PaintRead> {
arena: &'a A,
}
@@ -149,6 +158,59 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
})
}
+ /// The line the caret at `position` is on. A position at the start of a box with no line content is on none.
+ pub(crate) fn line_of_position(&self, position: CaretPosition) -> Option<InlineLine> {
+ match position {
+ CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ } => Some(self.line_of(text, offset, downstream)?.line),
+ CaretPosition::BesideAtomicInline { node, .. } => {
+ let root = text_fragment::containing_block_paintable_of_node(self.arena, node)?;
+ let side = self.arena.committed_side_data(root);
+ let fragment = side
+ .fragments()
+ .iter()
+ .find(|fragment| fragment.layout_node == node && fragment.is_atomic_inline)?;
+ Some(InlineLine {
+ root,
+ index: fragment.line_index,
+ })
+ }
+ CaretPosition::BeforeForcedBreak { node } => self.line_ended_by_forced_break(node),
+ CaretPosition::StartOfBox { .. } => None,
+ }
+ }
+
+ /// The line that holds `line` outside the atomic inline boxes its line root is in.
+ pub(crate) fn line_outside_atomic_inlines(&self, mut line: InlineLine) -> InlineLine {
+ while self.arena.node(line.root).is_some_and(|row| row.is_atomic_inline()) {
+ let Some(outer_line) = self.line_of_position(CaretPosition::BesideAtomicInline {
+ node: line.root,
+ after: false,
+ }) else {
+ break;
+ };
+ line = outer_line;
+ }
+ line
+ }
+
+ /// The line the <br> `node` ends.
+ fn line_ended_by_forced_break(&self, node: NodeSlotId) -> Option<InlineLine> {
+ 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))?;
+ Some(InlineLine {
+ root,
+ index: index as u32,
+ })
+ }
+
pub(crate) fn caret_rect(&self, position: CaretPosition) -> Option<CaretRect> {
match position {
CaretPosition::Text {
@@ -298,24 +360,17 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
}
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];
+ let line = self.line_ended_by_forced_break(node)?;
+ let side = self.arena.committed_side_data(line.root);
+ let record = &side.lines()[line.index as usize];
if record.fragment_count == 0 {
- return self.caret_rect_on_empty_line(InlineLine {
- root,
- index: index as u32,
- });
+ return self.caret_rect_on_empty_line(line);
}
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))
+ Some(self.caret_rect_in_fragment(line.root, last, last.dom_end_offset_with_trailing_whitespace, false))
}
fn caret_rect_at_start_of_box(&self, node: NodeSlotId) -> Option<CaretRect> {
@@ -397,6 +452,19 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
Some((coordinate - root_coordinate).floor() + root_coordinate)
}
+ /// The inline coordinate of the caret at `position`, which a move to another line keeps.
+ pub(crate) fn inline_coordinate_of(&self, position: CaretPosition) -> Option<CssPixels> {
+ if let Some(line) = self.line_of_position(position) {
+ return self.caret_inline_coordinate(line, position);
+ }
+ let caret = self.caret_rect(position)?;
+ let horizontal = self
+ .arena
+ .node_style_if_live(caret.style_source)
+ .is_none_or(|style| style.writing_mode() == writing_mode::HORIZONTAL_TB);
+ Some(if horizontal { caret.rect.x } else { caret.rect.y })
+ }
+
/// The fragments of `line` that `accepts` takes, in line order.
fn fragments_on_line<'b>(
&self,
@@ -440,6 +508,120 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
}
}
+ /// The extents of the lines of `root` along the inline axis and along the block direction, with the block coordinate
+ /// growing in the block direction, and the map from a point to those coordinates.
+ fn line_extents(&self, root: NodeSlotId) -> (Vec<LineExtent>, impl Fn(CssPixelPoint) -> (CssPixels, CssPixels)) {
+ let side = self.arena.committed_side_data(root);
+ let (horizontal, block_axis_is_reverse) = match side.lines().first().map(|record| record.writing_mode) {
+ Some(writing_mode::VERTICAL_RL | writing_mode::SIDEWAYS_RL) => (false, true),
+ Some(writing_mode::HORIZONTAL_TB) | None => (true, false),
+ _ => (false, false),
+ };
+ let logical = move |point: CssPixelPoint| match (horizontal, block_axis_is_reverse) {
+ (true, _) => (point.x, point.y),
+ (false, false) => (point.y, point.x),
+ (false, true) => (point.y, -point.x),
+ };
+ let positions = LineRootPositions::new(self.arena, root);
+ let extents = side
+ .lines()
+ .iter()
+ .map(|record| {
+ let rect = CssPixelRect::from(record.rect).translated_by(positions.of_fragment(record.box_fragment));
+ let (inline_start, block_start) = logical(rect.location());
+ let (inline_end, block_end) = logical(CssPixelPoint::new(rect.right(), rect.bottom()));
+ LineExtent {
+ inline_start,
+ inline_end,
+ block_start: block_start.min(block_end),
+ block_end: block_start.max(block_end),
+ }
+ })
+ .collect();
+ (extents, logical)
+ }
+
+ /// The columns the lines of `extents` lie in, as the inline extent of their lines and the index of their first line.
+ /// A column is a run of lines that goes on in the block direction.
+ fn columns(extents: &[LineExtent]) -> Vec<(CssPixels, CssPixels, usize)> {
+ let mut columns: Vec<(CssPixels, CssPixels, usize)> = Vec::new();
+ for (index, extent) in extents.iter().enumerate() {
+ match columns.last_mut() {
+ Some(column) if index > 0 && extent.block_start >= extents[index - 1].block_start => {
+ column.0 = column.0.min(extent.inline_start);
+ column.1 = column.1.max(extent.inline_end);
+ }
+ _ => columns.push((extent.inline_start, extent.inline_end, index)),
+ }
+ }
+ columns
+ }
+
+ /// `x`, an inline coordinate a move between lines keeps, moved from the column of the line root it falls in to the
+ /// column of `line`, so that it keeps its place in the column.
+ fn inline_coordinate_in_column_of(&self, line: InlineLine, x: CssPixels) -> CssPixels {
+ let columns = Self::columns(&self.line_extents(line.root).0);
+ if columns.len() < 2 {
+ return x;
+ }
+ let Some(&(source_start, _, _)) = columns.iter().find(|&&(start, end, _)| start <= x && x < end) else {
+ return x;
+ };
+ let target = columns.partition_point(|&(_, _, first_line)| first_line <= line.index as usize) - 1;
+ x + columns[target].0 - source_start
+ }
+
+ /// The caret position for `point` among the lines of `root`: on the first line of the column nearest the point that
+ /// ends past it in the block direction, or at the start of the column's first line before it, or at the end of its
+ /// last line past it.
+ pub(crate) fn position_for_point(
+ &self,
+ root: NodeSlotId,
+ point: CssPixelPoint,
+ accepts: &dyn Fn(&FragmentRecord) -> bool,
+ ) -> Option<CaretPosition> {
+ let (extents, logical) = self.line_extents(root);
+ let (inline, block) = logical(point);
+ let side = self.arena.committed_side_data(root);
+ let holds_caret = |index: usize| {
+ let record = &side.lines()[index];
+ (record.fragment_count > 0 && !record.has_block_level_box) || record.forced_break.is_some()
+ };
+ let columns = Self::columns(&extents);
+ let distance_to_column = |&(start, end, _): &(CssPixels, CssPixels, usize)| {
+ if inline < start {
+ start - inline
+ } else if inline > end {
+ inline - end
+ } else {
+ CssPixels::default()
+ }
+ };
+ let column = columns
+ .iter()
+ .enumerate()
+ .min_by_key(|(_, column)| distance_to_column(column))
+ .map(|(index, _)| index)?;
+ let column_end = columns.get(column + 1).map_or(extents.len(), |next| next.2);
+ let mut lines = (columns[column].2..column_end).filter(|&index| holds_caret(index));
+ let first = lines.next()?;
+ let line = |index: usize| InlineLine {
+ root,
+ index: index as u32,
+ };
+ if block < extents[first].block_start {
+ return self.line_edge(line(first), LineEdge::Start, accepts);
+ }
+ 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);
+ }
+ 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.
pub(crate) fn position_at_inline_coordinate(
@@ -451,9 +633,10 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
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 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));
@@ -462,6 +645,33 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
let Some((fragment, 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)
+ };
+ if let Some(position) = self.position_for_point(fragment.layout_node, point, &accepts) {
+ return Some(position);
+ }
+ }
+ 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,
+ });
+ }
let mut point = rect.center();
if horizontal {
point.x = rect.x.max(x);
@@ -472,8 +682,13 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
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 at `edge` of `line`, among the fragments `accepts` takes, or in front of the line's forced
- /// break where it takes none.
+ /// break where it takes none. The logical edges are those of the first and last fragment in line order.
pub(crate) fn line_edge(
&self,
line: InlineLine,
@@ -482,29 +697,42 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
) -> Option<CaretPosition> {
let arena = self.arena;
let side = arena.committed_side_data(line.root);
- let fragments = self.fragments_on_line(&side, line, accepts);
+ let mut fragments = self.fragments_on_line(&side, line, accepts);
+ let horizontal = self.line_is_horizontal(line);
let rect = |fragment: &&FragmentRecord| text_fragment::absolute_rect(arena, fragment);
let fragment = match edge {
- LineEdge::Start => fragments.min_by_key(|fragment| fragment.dom_start_offset_in_node),
- LineEdge::End => fragments.max_by_key(|fragment| fragment.dom_end_offset_with_trailing_whitespace),
+ LineEdge::Start => fragments.next(),
+ LineEdge::End => fragments.last(),
LineEdge::Left => fragments.min_by_key(|fragment| {
let rect = rect(fragment);
- if self.line_is_horizontal(line) { rect.x } else { rect.y }
+ if horizontal { rect.x } else { rect.y }
}),
LineEdge::Right => fragments.max_by_key(|fragment| {
let rect = rect(fragment);
- if self.line_is_horizontal(line) {
- rect.right()
- } else {
- rect.bottom()
- }
+ if horizontal { rect.right() } else { rect.bottom() }
}),
};
let Some(fragment) = fragment else {
return self.position_before_forced_break(line);
};
- let physical_edge = text_fragment::physical_edge_offset(arena, fragment, edge == LineEdge::Left);
- let offset = match (edge, physical_edge) {
+ if fragment.is_atomic_inline {
+ 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: match edge {
+ LineEdge::Start => false,
+ LineEdge::End => true,
+ LineEdge::Left => reverse,
+ LineEdge::Right => !reverse,
+ },
+ });
+ }
+ let offset = match (
+ edge,
+ text_fragment::physical_edge_offset(arena, fragment, edge == LineEdge::Left),
+ ) {
(LineEdge::Left | LineEdge::Right, Some((offset, at_cluster_end))) => {
return Some(CaretPosition::Text {
text: fragment.layout_node,
@@ -512,12 +740,49 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
downstream: !at_cluster_end,
});
}
+ (LineEdge::End, _) if self.only_collapsible_whitespace_follows(fragment) => fragment.dom_end_offset_in_node,
(LineEdge::End, _) => fragment.dom_end_offset_with_trailing_whitespace,
_ => fragment.dom_start_offset_in_node,
};
Some(self.text_position_in_fragment(fragment, offset))
}
+ // INTEROP: Collapsed whitespace at the end of the text of a block is not a caret stop, unlike whitespace that hangs
+ // at a soft wrap.
+ fn only_collapsible_whitespace_follows(&self, fragment: &FragmentRecord) -> bool {
+ if !matches!(
+ fragment.white_space_collapse,
+ white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS
+ ) {
+ return false;
+ }
+ 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');
+ self.arena.rendered_text(fragment.layout_node).is_some_and(|rendered| {
+ rendered
+ .text
+ .get(end..)
+ .is_none_or(|rest| rest.iter().all(is_space_or_tab))
+ })
+ }
+
+ /// The position nearest `offset` in the DOM text whose layout node is `text` that a line holds: the end of the
+ /// rendered text before it, as for a position in collapsed whitespace after it, or else the start of the first line.
+ pub(crate) fn nearest_text_position_on_a_line(&self, text: NodeSlotId, offset: usize) -> Option<CaretPosition> {
+ let lines = self.lines_of_text(text);
+ let (offset, downstream) = lines
+ .iter()
+ .rev()
+ .find(|line| line.end_offset_with_trailing_whitespace <= offset)
+ .map(|line| (line.end_offset_with_trailing_whitespace, false))
+ .or_else(|| lines.first().map(|line| (line.start_offset, true)))?;
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ })
+ }
+
/// 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;
diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
index 664e6082197..00a9a9f5d6a 100644
--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
@@ -312,6 +312,7 @@ pub unsafe extern "C" fn layout_script_text_character_x_positions(
/// 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)]
+#[derive(Clone, Copy)]
pub struct FfiCaretPosition {
pub node: NodeSlotId,
pub offset: usize,
@@ -321,6 +322,33 @@ pub struct FfiCaretPosition {
pub child_after: NodeSlotId,
}
+impl FfiCaretPosition {
+ /// The caret positions the position can take, in the order to try them.
+ pub(crate) fn candidates(&self, arena: &impl PaintRead) -> impl Iterator<Item = CaretPosition> {
+ let is_text = arena
+ .node_kind_if_live(self.node)
+ .is_some_and(super::node_facts::kind_is_text);
+ let text = is_text.then_some(CaretPosition::Text {
+ text: self.node,
+ offset: self.offset,
+ downstream: self.downstream,
+ });
+ let between_children = (!is_text)
+ .then(|| {
+ inline_cursor::caret_positions_between_children(
+ arena,
+ self.node,
+ self.child_before,
+ self.child_before_length,
+ self.child_after,
+ )
+ })
+ .into_iter()
+ .flatten();
+ text.into_iter().chain(between_children)
+ }
+}
+
/// The caret layout gives a position, as the recorder paints it and in the layout viewport.
#[repr(C)]
pub struct FfiCaret {
@@ -342,26 +370,10 @@ pub extern "C" fn layout_script_caret(
) {
*out = read_rows(host, |arena| {
let cursor = InlineCursor::new(arena);
- let caret = if arena
- .node_kind_if_live(position.node)
- .is_some_and(super::node_facts::kind_is_text)
- {
- 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,
- )
+ let Some(caret) = position
+ .candidates(arena)
.find_map(|candidate| cursor.caret_rect(candidate))
- };
- let Some(caret) = caret else {
+ else {
return FfiCaret {
found: false,
paint: FfiCaretPaintKind::None,
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rs
index b9fe4abbbb8..2917bc6d748 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -7,8 +7,9 @@
use crate::css::css_pixels::{CssPixelRect, CssPixels};
use crate::css::ffi_support::{FfiUtf16View, OwnedBox};
use crate::layout::LayoutNodeArena;
-use crate::layout::node_data::NodeSlotId;
-use crate::layout::query::inline_cursor::{CaretPosition, InlineCursor, LineEdge};
+use crate::layout::node_data::{DomPaintFact, NodeSlotId};
+use crate::layout::query::inline_cursor::{CaretPosition, InlineCursor, InlineLine, LineEdge};
+use crate::layout::script_entries::FfiCaretPosition;
use crate::layout::svg_formatting_context;
use crate::layout::used_values::FfiCssPixelPoint;
use crate::layout::used_values::FfiCssPixelRect;
@@ -931,34 +932,229 @@ impl FfiOptionalCssPixels {
}
}
-/// The inline coordinate of the caret at `offset` in the DOM text whose layout node is `primary`, where a fragment holds
-/// it, which a move to another line keeps.
+/// A line of the line root `root`, or none where `root` is invalid.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiInlineLine {
+ pub root: NodeSlotId,
+ pub index: u32,
+}
+
+impl FfiInlineLine {
+ fn of(line: Option<InlineLine>) -> Self {
+ line.map_or(
+ Self {
+ root: NodeSlotId::INVALID,
+ index: 0,
+ },
+ |line| Self {
+ root: line.root,
+ index: line.index,
+ },
+ )
+ }
+
+ fn line(self, arena: &impl PaintRead) -> Option<InlineLine> {
+ let line = InlineLine {
+ root: self.root,
+ index: self.index,
+ };
+ (!self.root.is_invalid()
+ && arena.paintable_row_is_populated(self.root)
+ && (line.index as usize) < arena.committed_side_data(self.root).lines().len())
+ .then_some(line)
+ }
+}
+
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum FfiInlineCaretPositionKind {
+ None,
+ Text,
+ BesideAtomicInline,
+ BeforeForcedBreak,
+ StartOfBox,
+}
+
+/// A caret position as InlineCursor names it: `offset` in the DOM text whose layout node is `node` (leaning to the next
+/// line where `downstream`), beside the atomic inline `node` (`after` it or before it), before the <br> `node`, or at the
+/// start of the box `node`.
+#[repr(C)]
+pub struct FfiInlineCaretPosition {
+ pub kind: FfiInlineCaretPositionKind,
+ pub node: NodeSlotId,
+ pub offset: usize,
+ pub downstream: bool,
+ pub after: bool,
+}
+
+impl FfiInlineCaretPosition {
+ fn of(position: Option<CaretPosition>) -> Self {
+ let (kind, node, offset, downstream, after) = match position {
+ None => (FfiInlineCaretPositionKind::None, NodeSlotId::INVALID, 0, true, false),
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ }) => (FfiInlineCaretPositionKind::Text, text, offset, downstream, false),
+ Some(CaretPosition::BesideAtomicInline { node, after }) => {
+ (FfiInlineCaretPositionKind::BesideAtomicInline, node, 0, true, after)
+ }
+ Some(CaretPosition::BeforeForcedBreak { node }) => {
+ (FfiInlineCaretPositionKind::BeforeForcedBreak, node, 0, true, false)
+ }
+ Some(CaretPosition::StartOfBox { node }) => (FfiInlineCaretPositionKind::StartOfBox, node, 0, true, false),
+ };
+ Self {
+ kind,
+ node,
+ offset,
+ downstream,
+ after,
+ }
+ }
+}
+
+/// The caret positions that produce a caret: those in DOM text and beside DOM elements, not in generated content.
+fn produces_caret(arena: &impl PaintRead, fragment: &FragmentRecord) -> bool {
+ arena.node_is_dom_backed(fragment.layout_node)
+}
+
+/// The caret positions a move between lines can start from at `position`: those it can take, and in DOM text that no line
+/// holds there, such as collapsed whitespace, the nearest position that one does.
+fn navigation_candidates<'a, A: PaintRead>(
+ cursor: &'a InlineCursor<'a, A>,
+ rows: &'a A,
+ position: &'a FfiCaretPosition,
+) -> impl Iterator<Item = CaretPosition> + 'a {
+ position.candidates(rows).chain(
+ std::iter::once_with(move || {
+ rows.node_kind_if_live(position.node)
+ .is_some_and(crate::layout::node_facts::kind_is_text)
+ .then(|| cursor.nearest_text_position_on_a_line(position.node, position.offset))
+ .flatten()
+ })
+ .flatten(),
+ )
+}
+
+/// The line the caret at `position` is on, if any.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_caret_line(host: &DocumentHost, position: FfiCaretPosition) -> FfiInlineLine {
+ read_arena(host, node_read(), position, |arena, position| {
+ let rows = arena.paintable_rows();
+ let cursor = InlineCursor::new(&rows);
+ FfiInlineLine::of(
+ navigation_candidates(&cursor, &rows, &position).find_map(|candidate| cursor.line_of_position(candidate)),
+ )
+ })
+}
+
+/// The line that holds `line` outside the atomic inline boxes its line root is in.
#[unsafe(no_mangle)]
-pub extern "C" fn render_state_text_caret_inline_coordinate(
+pub extern "C" fn render_state_caret_line_outside_atomic_inlines(
host: &DocumentHost,
- primary: NodeSlotId,
- offset: usize,
- downstream: bool,
- out: &mut FfiOptionalCssPixels,
-) {
- *out = read_arena(
+ line: FfiInlineLine,
+) -> FfiInlineLine {
+ read_arena(host, node_read(), line, |arena, line| {
+ let rows = arena.paintable_rows();
+ FfiInlineLine::of(
+ line.line(&rows)
+ .map(|line| InlineCursor::new(&rows).line_outside_atomic_inlines(line)),
+ )
+ })
+}
+
+/// The next line after `line` (or the previous one) in its line root that holds a caret position, if any.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_adjacent_caret_line(
+ host: &DocumentHost,
+ line: FfiInlineLine,
+ forward: bool,
+) -> FfiInlineLine {
+ read_arena(host, node_read(), (line, forward), |arena, (line, forward)| {
+ let rows = arena.paintable_rows();
+ FfiInlineLine::of(
+ line.line(&rows)
+ .and_then(|line| InlineCursor::new(&rows).adjacent_line(line, forward)),
+ )
+ })
+}
+
+/// The caret position on `line` nearest the inline coordinate `x`, which a move between lines kept.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_caret_position_at_inline_coordinate(
+ host: &DocumentHost,
+ line: FfiInlineLine,
+ x: CssPixels,
+) -> FfiInlineCaretPosition {
+ read_arena(host, node_read(), (line, x), |arena, (line, x)| {
+ let rows = arena.paintable_rows();
+ FfiInlineCaretPosition::of(line.line(&rows).and_then(|line| {
+ InlineCursor::new(&rows).position_at_inline_coordinate(line, x, |fragment| produces_caret(&rows, fragment))
+ }))
+ })
+}
+
+/// The caret position at `edge` of `line`, among its editable line content where `editable_only`.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_caret_position_at_line_edge(
+ host: &DocumentHost,
+ line: FfiInlineLine,
+ edge: LineEdge,
+ editable_only: bool,
+) -> FfiInlineCaretPosition {
+ read_arena(
host,
node_read(),
- (primary, offset, downstream),
- |arena, (text, offset, downstream)| {
+ (line, edge, editable_only),
+ |arena, (line, edge, editable_only)| {
let rows = arena.paintable_rows();
- let cursor = InlineCursor::new(&rows);
- let position = CaretPosition::Text {
- text,
- offset,
- downstream,
+ let is_editable = |node: NodeSlotId| {
+ [Some(node), rows.node_parent_if_live(node)]
+ .into_iter()
+ .flatten()
+ .any(|node| rows.node_has_dom_paint_fact(node, DomPaintFact::EditableOrEditingHost))
};
- let line = cursor
- .line_of(text, offset, downstream)
- .filter(|line| line.fragment.is_some());
- FfiOptionalCssPixels::of(line.and_then(|line| cursor.caret_inline_coordinate(line.line, position)))
+ FfiInlineCaretPosition::of(line.line(&rows).and_then(|line| {
+ InlineCursor::new(&rows).line_edge(line, edge, |fragment| {
+ produces_caret(&rows, fragment) && (!editable_only || is_editable(fragment.layout_node))
+ })
+ }))
},
- );
+ )
+}
+
+/// The middle of `line` along the block axis.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_caret_line_block_coordinate(
+ host: &DocumentHost,
+ line: FfiInlineLine,
+ out: &mut CssPixels,
+) {
+ *out = read_arena(host, node_read(), line, |arena, line| {
+ let rows = arena.paintable_rows();
+ line.line(&rows)
+ .map(|line| InlineCursor::new(&rows).line_block_coordinate(line))
+ .unwrap_or_default()
+ });
+}
+
+/// The inline coordinate of the caret at `position`, which a move to another line keeps.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_caret_inline_coordinate(
+ host: &DocumentHost,
+ position: FfiCaretPosition,
+ out: &mut FfiOptionalCssPixels,
+) {
+ *out = read_arena(host, node_read(), position, |arena, position| {
+ let rows = arena.paintable_rows();
+ let cursor = InlineCursor::new(&rows);
+ FfiOptionalCssPixels::of(
+ navigation_candidates(&cursor, &rows, &position)
+ .find_map(|candidate| cursor.inline_coordinate_of(candidate)),
+ )
+ });
}
#[repr(u8)]
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
index 4d78ec000ab..3f68b435a3c 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
@@ -821,21 +821,6 @@ fn with_hit_test_list_items_only<R>(
with_hit_test_list(host, read, default, |_, _| {}, |list, _, source| query(list, source))
}
-fn with_hit_test_list_and_caret_lines<R>(
- host: &crate::render_state::DocumentHost,
- read: &crate::render_state::BegunRead,
- default: R,
- query: impl FnOnce(&crate::painting::hit_test::HitTestList, &crate::painting::paint_read::PaintSource<'_>) -> R,
-) -> R {
- with_hit_test_list(
- host,
- read,
- default,
- |list, source| list.build_caret_lines_if_needed(source),
- |list, _, source| query(list, source),
- )
-}
-
fn with_hit_test_list_spatial_indexes_and_visual_context_tree<R>(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
@@ -1064,116 +1049,6 @@ pub unsafe extern "C" fn layout_hit_test_caret_position_from_point(
.unwrap_or_else(FfiCaretAt::none);
}
-/// The caret position at the start (`edge` 1) or end (`edge` 2) of the painted line holding the position `query`
-/// describes.
-///
-/// # Safety
-///
-/// `host` must be a live document host, on its document's thread; the query must stay valid for this synchronous call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn layout_hit_test_caret_at_line_edge(
- host: &crate::render_state::DocumentHost,
- read: &crate::render_state::BegunRead,
- callbacks: crate::painting::host::FfiHitTestQueryCallbacks,
- query: crate::painting::host::FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- edge: u8,
- physical: bool,
- scope: crate::painting::host::FfiNodeIdentity,
- out: &mut FfiCaretAt,
-) {
- let edge = crate::painting::hit_test::caret::CaretPositionType::from_u8(edge);
- // SAFETY: Guaranteed by the entry point's contract.
- let main_thread = unsafe { main_thread(host) };
- *out = with_hit_test_list_and_caret_lines(host, read, None, |list, arena| {
- list.caret_at_line_edge(
- &HostNodeScopes {
- main_thread: &main_thread,
- callbacks: &callbacks,
- },
- arena,
- &query,
- offset,
- affinity_is_downstream,
- edge,
- physical,
- scope,
- )
- })
- .unwrap_or_else(FfiCaretAt::none);
-}
-
-/// The caret position on the line visually after (`direction` 1) or before (`direction` 0) the line holding the
-/// position `query` describes, among the lines inside `scope`.
-///
-/// # Safety
-///
-/// `host` must be a live document host, on its document's thread; the query and callbacks must stay valid for this
-/// synchronous call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn layout_hit_test_caret_on_adjacent_line(
- host: &crate::render_state::DocumentHost,
- read: &crate::render_state::BegunRead,
- callbacks: crate::painting::host::FfiHitTestQueryCallbacks,
- query: crate::painting::host::FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- direction: u8,
- inline_coordinate: i32,
- scope: crate::painting::host::FfiNodeIdentity,
- out: &mut FfiCaretAt,
-) {
- let direction = if direction == 1 {
- crate::painting::hit_test::caret::CaretLineDirection::Next
- } else {
- crate::painting::hit_test::caret::CaretLineDirection::Previous
- };
- // SAFETY: Guaranteed by the entry point's contract.
- let main_thread = unsafe { main_thread(host) };
- *out = with_hit_test_list_and_caret_lines(host, read, None, |list, arena| {
- list.caret_on_adjacent_line(
- &HostNodeScopes {
- main_thread: &main_thread,
- callbacks: &callbacks,
- },
- arena,
- &query,
- offset,
- affinity_is_downstream,
- direction,
- CssPixels::from_raw(inline_coordinate),
- scope,
- )
- })
- .unwrap_or_else(FfiCaretAt::none);
-}
-
-/// The block-axis middle of the painted line holding the position `query` describes, if a line holds it.
-///
-/// # Safety
-///
-/// `host` must be a live document host, on its document's thread; the query must stay valid for this synchronous call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn layout_hit_test_caret_line_block_coordinate(
- host: &crate::render_state::DocumentHost,
- read: &crate::render_state::BegunRead,
- query: crate::painting::host::FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- out_coordinate: &mut i32,
-) -> bool {
- let coordinate = with_hit_test_list_and_caret_lines(host, read, None, |list, arena| {
- let line_index = list.caret_line_for_position(arena, &query, offset, affinity_is_downstream)?;
- Some(list.line_block_coordinate(line_index))
- });
- let Some(coordinate) = coordinate else {
- return false;
- };
- *out_coordinate = coordinate.raw_value();
- true
-}
-
/// The style-tree identity of the first `<area>` of the image's map, in tree order, whose shape
/// covers the point. Zero when the image has no map, or when no shape covers the point.
#[unsafe(no_mangle)]
diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs
index 7ef27fe3256..a79cbbb91c3 100644
--- a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs
+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs
@@ -4,14 +4,11 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use super::resolve::with_item_fragment;
use super::*;
use crate::painting::host::{
- FfiCaretAt, FfiCaretBoundaryKind, FfiCaretPositionQuery, FfiHitTestQueryCallbacks, FfiNodeIdentity,
- FfiResolvedCaret,
+ FfiCaretAt, FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiNodeIdentity, FfiResolvedCaret,
};
use crate::painting::paint_read::PaintRead;
-use crate::painting::text_fragment::CaretMatch;
use crate::painting::viewport_mapping::ViewportSpace;
use crate::painting::visual_context::{ClipBehavior, SpatialNodeIndex};
@@ -34,21 +31,10 @@ impl NodeScopes for HostNodeScopes<'_> {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
pub enum CaretPositionType {
- Closest = 0,
- Before = 1,
- After = 2,
-}
-
-impl CaretPositionType {
- pub fn from_u8(value: u8) -> Self {
- match value {
- value if value == Self::Before as u8 => Self::Before,
- value if value == Self::After as u8 => Self::After,
- _ => Self::Closest,
- }
- }
+ Closest,
+ Before,
+ After,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -69,12 +55,6 @@ impl CaretPositionMode {
}
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum CaretLineDirection {
- Previous = 0,
- Next = 1,
-}
// 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.
@@ -131,10 +111,6 @@ fn caret_line_is_better_candidate(
block_distance < closest_block_distance
}
-fn line_block_middle(rect: CssPixelRect, writing_mode: u8) -> CssPixels {
- block_axis_start(rect, writing_mode)
- + (block_axis_end(rect, writing_mode) - block_axis_start(rect, writing_mode)).scaled(0.5)
-}
#[derive(Clone, Copy, Debug)]
pub struct ClosestLine {
pub index: Option<usize>,
@@ -167,85 +143,6 @@ impl Default for ClosestLine {
}
impl HitTestList {
- pub(crate) fn caret_line_for_position(
- &self,
- arena: &impl PaintRead,
- query: &FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- ) -> Option<usize> {
- // At a soft wrap, prefer the fragment whose line directly owns the position. Only use the preceding
- // fragment's fallback match when no direct match exists.
- for allow_soft_wrap_fallback in [false, true] {
- for (line_index, line) in self.caret_lines.iter().enumerate() {
- 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 position_match =
- self.item_position_match(arena, query, item_index, offset, affinity_is_downstream);
- match position_match {
- CaretMatch::None => continue,
- CaretMatch::SoftWrapFallback if !allow_soft_wrap_fallback => continue,
- CaretMatch::Direct | CaretMatch::SoftWrapFallback => return Some(line_index),
- }
- }
- }
- }
- None
- }
-
- fn item_position_match(
- &self,
- arena: &impl PaintRead,
- query: &FfiCaretPositionQuery,
- item_index: usize,
- offset: usize,
- affinity_is_downstream: bool,
- ) -> CaretMatch {
- let item = &self.items[item_index];
- match item.kind {
- HitTestItemKind::TextFragment => resolve::with_item_fragment(arena, item, |fragment| {
- let node = resolve::row_dom_style_node(arena, fragment.layout_node);
- if query.is_query_node(node) {
- return crate::painting::text_fragment::caret_match(fragment, offset, affinity_is_downstream);
- }
- if fragment.dom_start_offset_in_node == 0 && query.boundary_descends_to(node) {
- return CaretMatch::Direct;
- }
- if query.boundary_follows_end(node, fragment.dom_end_offset_with_trailing_whitespace) {
- return CaretMatch::Direct;
- }
- CaretMatch::None
- })
- .unwrap_or(CaretMatch::None),
- HitTestItemKind::EmptyLine => {
- let node = resolve::row_dom_style_node(arena, item.caret_node);
- let matches = if super::resolve::empty_line_is_anchored_to_its_forced_break(arena, item) {
- query.boundary_precedes(node)
- } else {
- item.caret_offset == offset && query.is_query_node(node)
- };
- if matches { CaretMatch::Direct } else { CaretMatch::None }
- }
- HitTestItemKind::EmptyEditable => {
- let node = resolve::row_dom_style_node(arena, item.paintable);
- if offset == 0 && query.is_query_node(node) {
- CaretMatch::Direct
- } else {
- CaretMatch::None
- }
- }
- HitTestItemKind::Box => {
- let node = resolve::row_dom_style_node(arena, item.paintable);
- if query.is_adjacent_to(node) {
- CaretMatch::Direct
- } else {
- CaretMatch::None
- }
- }
- HitTestItemKind::SvgPath | HitTestItemKind::ChromeWidget => CaretMatch::None,
- }
- }
-
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);
@@ -274,16 +171,6 @@ impl HitTestList {
}
pub fn item_at_line_edge(&self, line_index: usize, position_type: CaretPositionType) -> usize {
- self.item_at_line_edge_matching(line_index, position_type, |_| true)
- .expect("a caret line has at least one item")
- }
-
- fn item_at_line_edge_matching(
- &self,
- line_index: usize,
- position_type: CaretPositionType,
- accepts_item: impl Fn(usize) -> bool,
- ) -> Option<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);
@@ -320,7 +207,7 @@ impl HitTestList {
}
};
let first_index = self.caret_item_indices[line.first_caret_item_index];
- let mut best_item_index = accepts_item(first_index).then_some(first_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() {
@@ -338,12 +225,12 @@ impl HitTestList {
// 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) || !accepts_item(*item_index) {
+ if !item_is_on_line(item) {
continue;
}
let coordinate = coordinate_for_item(item);
- if best_item_index.is_none() || coordinate_is_closer_to_line_edge(coordinate, best_coordinate) {
- best_item_index = Some(*item_index);
+ if coordinate_is_closer_to_line_edge(coordinate, best_coordinate) {
+ best_item_index = *item_index;
best_coordinate = coordinate;
}
}
@@ -444,13 +331,6 @@ impl HitTestList {
closest_item_index.map(|index| (index, CaretPositionType::Closest))
}
- pub fn line_block_coordinate(&self, line_index: usize) -> CssPixels {
- debug_assert!(self.caret_lines_built);
- let line = &self.caret_lines[line_index];
- let writing_mode = self.first_item_of_line(line).writing_mode;
- line_block_middle(line.rect, writing_mode)
- }
-
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];
@@ -681,155 +561,6 @@ impl HitTestList {
}
closest_line
}
-
- #[allow(clippy::too_many_arguments)]
- pub(crate) fn adjacent_line(
- &self,
- scopes: &impl NodeScopes,
- arena: &impl PaintRead,
- current_line_index: usize,
- direction: CaretLineDirection,
- inline_coordinate: CssPixels,
- scope: FfiNodeIdentity,
- ) -> Option<(usize, CssPixelPoint)> {
- // INTEROP: Vertical caret movement in Chromium, WebKit, and Gecko follows rendered line geometry rather than
- // DOM tree order. Rank candidates in the requested logical block direction, prefer the current line-producing
- // context, then minimize block distance and finally distance from the remembered inline coordinate.
-
- // Keep these coordinates fractional. Rounding line geometry before comparison can reorder candidates when
- // layout positions or device scaling produce subpixel line centers.
- debug_assert!(self.caret_lines_built);
- let current_line = self.caret_lines[current_line_index].clone();
- let current_first_item = self.first_item_of_line(&current_line);
- let writing_mode = current_first_item.writing_mode;
- let block_axis_is_reverse = current_first_item.block_axis_is_reverse;
- let physically_after = (direction == CaretLineDirection::Next) != block_axis_is_reverse;
- let current_line_context = current_first_item.paintable;
- let current_block_coordinate = line_block_middle(current_line.rect, writing_mode);
-
- let fragment_rects: smallvec::SmallVec<[CssPixelRect; 2]> = if current_line.block_container.is_invalid()
- || !arena.paintable_row_is_populated(current_line.block_container)
- {
- smallvec::SmallVec::new()
- } else {
- (0..crate::painting::paintable_geometry::fragment_count(arena, current_line.block_container))
- .map(|index| {
- crate::painting::paintable_geometry::absolute_fragment_rect(
- arena,
- current_line.block_container,
- index,
- )
- })
- .collect()
- };
- let fragment_inline_start = |box_fragment: u32| {
- fragment_rects
- .get(box_fragment as usize)
- .map(|rect| inline_axis_start(*rect, writing_mode))
- };
- let mut inline_coordinate = inline_coordinate;
- if fragment_rects.len() > 1
- && let Some(source_fragment) = fragment_rects.iter().position(|rect| {
- inline_coordinate >= inline_axis_start(*rect, writing_mode)
- && inline_coordinate < inline_axis_end(*rect, writing_mode)
- })
- && let (Some(current_start), Some(source_start)) = (
- fragment_inline_start(current_line.box_fragment),
- fragment_inline_start(source_fragment as u32),
- )
- {
- inline_coordinate += current_start - source_start;
- }
- let mut closest_line_index: Option<usize> = None;
- let mut closest_line_shares_context = false;
- let mut closest_block_distance = CssPixels::from_raw(i32::MAX);
- let mut closest_inline_distance = CssPixels::from_raw(i32::MAX);
- let is_in_other_fragment_of_current_block_container = |line: &CaretLine| {
- !current_line.block_container.is_invalid()
- && line.block_container == current_line.block_container
- && line.box_fragment != current_line.box_fragment
- };
- for line_index in 0..self.caret_lines.len() {
- let line = &self.caret_lines[line_index];
- // INTEROP: Keyboard navigation follows layout geometry across clips, effects, and transforms.
- // Separate paint contexts inside one editing host must not isolate its editable lines.
- if line_index == current_line_index
- || is_in_other_fragment_of_current_block_container(line)
- || !self.line_in_scope(scopes, arena, line_index, scope)
- {
- continue;
- }
- let candidate_block_coordinate = line_block_middle(line.rect, writing_mode);
- if (physically_after && candidate_block_coordinate <= current_block_coordinate)
- || (!physically_after && candidate_block_coordinate >= current_block_coordinate)
- {
- continue;
- }
- let block_distance = absolute_difference(candidate_block_coordinate, current_block_coordinate);
- let inline_distance = distance_to_range(
- inline_coordinate,
- inline_axis_start(line.rect, writing_mode),
- inline_axis_end(line.rect, writing_mode),
- );
- let candidate_first_item = self.first_item_of_line(line);
- // Prefer lines produced by the same line paintable. Independently painted content, such as a floated first
- // letter, may occupy the same block-axis neighborhood without being the next line of the current content.
- let shares_line_context = candidate_first_item.paintable == current_line_context;
- if closest_line_index.is_none()
- || (shares_line_context && !closest_line_shares_context)
- || (shares_line_context == closest_line_shares_context
- && (block_distance < closest_block_distance
- || (block_distance == closest_block_distance && inline_distance < closest_inline_distance)))
- {
- closest_line_index = Some(line_index);
- closest_line_shares_context = shares_line_context;
- closest_block_distance = block_distance;
- closest_inline_distance = inline_distance;
- }
- }
- let adjacent_fragment = if direction == CaretLineDirection::Next {
- current_line.box_fragment.checked_add(1)
- } else {
- current_line.box_fragment.checked_sub(1)
- };
- let continues_in_adjacent_fragment = closest_line_index
- .is_none_or(|index| self.caret_lines[index].block_container != current_line.block_container);
- if continues_in_adjacent_fragment
- && let Some(adjacent_fragment) = adjacent_fragment
- && let Some(line_index) = (0..self.caret_lines.len())
- .filter(|&line_index| {
- let line = &self.caret_lines[line_index];
- is_in_other_fragment_of_current_block_container(line)
- && line.box_fragment == adjacent_fragment
- && self.line_in_scope(scopes, arena, line_index, scope)
- })
- .min_by_key(|&line_index| {
- let block_coordinate = line_block_middle(self.caret_lines[line_index].rect, writing_mode);
- if physically_after {
- block_coordinate
- } else {
- -block_coordinate
- }
- })
- {
- if let (Some(target_start), Some(current_start)) = (
- fragment_inline_start(self.caret_lines[line_index].box_fragment),
- fragment_inline_start(current_line.box_fragment),
- ) {
- inline_coordinate += target_start - current_start;
- }
- closest_line_index = Some(line_index);
- }
- let closest_line_index = closest_line_index?;
- let closest_line = &self.caret_lines[closest_line_index];
- let block_coordinate = line_block_middle(closest_line.rect, writing_mode);
- let point = if writing_mode_is_horizontal(writing_mode) {
- CssPixelPoint::new(inline_coordinate, block_coordinate)
- } else {
- CssPixelPoint::new(block_coordinate, inline_coordinate)
- };
- Some((closest_line_index, point))
- }
}
impl FfiCaretAt {
@@ -1074,76 +805,4 @@ impl HitTestList {
}
Some(caret)
}
-
- /// The caret position at the start or end of the painted line holding the position. A visual line can span several
- /// DOM nodes and atomic inline boxes, so a text-node or block-element boundary is not necessarily a line boundary.
- #[allow(clippy::too_many_arguments)]
- pub(crate) fn caret_at_line_edge(
- &self,
- scopes: &impl NodeScopes,
- arena: &impl PaintRead,
- query: &FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- edge: CaretPositionType,
- physical: bool,
- scope: FfiNodeIdentity,
- ) -> Option<FfiCaretAt> {
- let line_index = self.caret_line_for_position(arena, query, offset, affinity_is_downstream)?;
- let mut logical_edge = edge;
- if physical
- && self
- .first_item_of_line(&self.caret_lines[line_index])
- .inline_axis_is_reverse
- {
- logical_edge = if edge == CaretPositionType::Before {
- CaretPositionType::After
- } else {
- CaretPositionType::Before
- };
- }
- let item_index = self.item_at_line_edge_matching(line_index, logical_edge, |index| {
- scope.is_none() || scopes.contains(scope, self.item_target(arena, index))
- })?;
- let mut caret = self.caret_at_item(arena, item_index, CssPixelPoint::default(), logical_edge)?;
- if physical {
- let item = &self.items[item_index];
- if item.kind == HitTestItemKind::TextFragment
- && let Some((offset, upstream)) = with_item_fragment(arena, item, |fragment| {
- crate::painting::text_fragment::physical_edge_offset(
- arena,
- fragment,
- edge == CaretPositionType::Before,
- )
- })
- .flatten()
- {
- caret.caret.offset = offset;
- caret.caret.affinity_is_upstream = upstream;
- caret.caret.has_debug_rect = false;
- }
- }
- Some(caret)
- }
-
- /// The caret position on the visually adjacent line within `scope`, preserving the requested inline coordinate.
- #[allow(clippy::too_many_arguments)]
- pub(crate) fn caret_on_adjacent_line(
- &self,
- scopes: &impl NodeScopes,
- arena: &impl PaintRead,
- query: &FfiCaretPositionQuery,
- offset: usize,
- affinity_is_downstream: bool,
- direction: CaretLineDirection,
- inline_coordinate: CssPixels,
- scope: FfiNodeIdentity,
- ) -> Option<FfiCaretAt> {
- let line_index = self.caret_line_for_position(arena, query, offset, affinity_is_downstream)?;
- let (adjacent_line_index, point) =
- self.adjacent_line(scopes, arena, line_index, direction, inline_coordinate, scope)?;
- // Reuse point-to-caret resolution after choosing the line so text, atomic boxes, and empty lines share one rule
- // for selecting the position closest to the preferred inline coordinate.
- self.caret_at_line(arena, adjacent_line_index, point, CaretPositionMode::Normal)
- }
}
diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs
index 7288b6182bf..b04ad8b12a4 100644
--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs
+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs
@@ -112,66 +112,6 @@ impl FfiHitTestQueryCallbacks {
}
}
-/// A caret boundary, as the node identities a hit test item can be compared against.
-///
-/// The five questions a caret position query asks of a candidate item all reduce to "which node
-/// is it", so the host resolves the boundary's neighbourhood once before the query runs and the
-/// query compares StyleNodeIDs. A node without one is named by 0, which matches nothing: an item
-/// that stands for no DOM node is named by 0 as well.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiCaretPositionQuery {
- /// The node the boundary is inside.
- pub node: u32,
- /// The child at the boundary's offset, or 0 when the node has no child there.
- pub child_at_offset: u32,
- /// The child before the boundary's offset, or 0 at offset 0.
- pub child_before_offset: u32,
- /// The length of the node `child_before_offset` names.
- pub child_before_offset_length: usize,
- /// `child_at_offset` and the chain of first children descending from it, in order.
- pub boundary_descent: *const u32,
- pub boundary_descent_len: usize,
-}
-
-impl FfiCaretPositionQuery {
- fn names(named: u32, node: u32) -> bool {
- named != 0 && named == node
- }
-
- fn boundary_descent(&self) -> &[u32] {
- if self.boundary_descent.is_null() {
- return &[];
- }
- // SAFETY: The host keeps the descent alive for the synchronous query.
- unsafe { ak::slice_from_raw_parts(self.boundary_descent, self.boundary_descent_len) }
- }
-
- pub(crate) fn is_query_node(&self, node: u32) -> bool {
- Self::names(self.node, node)
- }
-
- /// Whether the boundary sits immediately before `node` among its parent's children.
- pub(crate) fn boundary_precedes(&self, node: u32) -> bool {
- Self::names(self.child_at_offset, node)
- }
-
- /// Whether the boundary sits at the end of `node`, which ends at `end_offset`.
- pub(crate) fn boundary_follows_end(&self, node: u32, end_offset: usize) -> bool {
- Self::names(self.child_before_offset, node) && end_offset == self.child_before_offset_length
- }
-
- /// Whether the boundary sits on either side of `node`.
- pub(crate) fn is_adjacent_to(&self, node: u32) -> bool {
- Self::names(self.child_at_offset, node) || Self::names(self.child_before_offset, node)
- }
-
- /// Whether descending through first children from the boundary reaches `node`.
- pub(crate) fn boundary_descends_to(&self, node: u32) -> bool {
- node != 0 && self.boundary_descent().contains(&node)
- }
-}
-
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct FfiTopmostItem {
diff --git a/Libraries/LibWeb/Selection/CaretNavigation.cpp b/Libraries/LibWeb/Selection/CaretNavigation.cpp
index a722944ba35..4b16fb65cef 100644
--- a/Libraries/LibWeb/Selection/CaretNavigation.cpp
+++ b/Libraries/LibWeb/Selection/CaretNavigation.cpp
@@ -20,7 +20,6 @@
#include <LibWeb/Layout/Box.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Painting/BoxViews.h>
-#include <LibWeb/Painting/HitTestDisplayList.h>
#include <LibWeb/Selection/CaretNavigation.h>
#include <LibWeb/VisualLines.h>
@@ -100,6 +99,14 @@ static bool is_atomic_inline_caret_host(DOM::Node& node)
return node.is_editable() && node.parent() && layout_node && layout_node->is_atomic_inline();
}
+// An atomic inline box with no content, such as an empty inline-block, holds a caret position inside it, on no line.
+static bool is_empty_inline_block(DOM::Node& node)
+{
+ Layout::ForcedReadScope read { node.document() };
+ auto const* layout_node = node.layout_node(read);
+ return is_atomic_inline_caret_host(node) && !node.has_children() && !layout_node->is_replaced_box();
+}
+
static bool boundary_visual_lines_share_line(DOM::Text const& before, DOM::Text const& after)
{
Layout::ForcedReadScope read { before.document() };
@@ -123,18 +130,79 @@ static bool boundary_visual_lines_share_inline_context(DOM::Text const& before,
return before_lines.last().owner_paintable == after_lines.first().owner_paintable;
}
-// Convert a text-edge destination to the equivalent boundary in its block. Chromium exposes this form when a vertical
-// extension crosses a block boundary, which keeps the selected DOM range aligned with the rendered block contents.
-static CaretLocation canonical_location_at_outer_edge_of_inline_content(DOM::Text& text, DOM::Node& block, SelectionDirection direction)
+// INTEROP: A forward vertical extension that ends at the start of text in another block ends at the equivalent boundary
+// at the start of that block, which keeps the selected DOM range aligned with the rendered block contents.
+static CaretLocation canonical_location_at_start_of_inline_content(DOM::Text& text, DOM::Node& block)
{
DOM::Node* node = &text;
while (auto* parent = node->parent()) {
- auto offset = direction == SelectionDirection::Forward ? node->index() : node->index() + 1;
if (parent == &block)
- return { *parent, offset, TextAffinity::Downstream };
+ return { *parent, node->index(), TextAffinity::Downstream };
node = parent;
}
- return { text, direction == SelectionDirection::Forward ? 0u : text.length(), TextAffinity::Downstream };
+ return { text, 0, TextAffinity::Downstream };
+}
+
+using InlineLine = Layout::RustFFI::FfiInlineLine;
+
+// Lines inside an atomic inline box are on the line that holds the box, as a move between lines in tree order sees them.
+static bool is_same_line(DOM::Document& document, InlineLine const& a, InlineLine const& b)
+{
+ auto* host = document.layout_node_arena().host();
+ auto outer_a = Layout::RustFFI::render_state_caret_line_outside_atomic_inlines(host, a);
+ auto outer_b = Layout::RustFFI::render_state_caret_line_outside_atomic_inlines(host, b);
+ return outer_a.root.index == outer_b.root.index && outer_a.index == outer_b.index;
+}
+
+// A boundary before an element with content is at the start of that content, which is what layout has a caret for.
+static Optional<Layout::RustFFI::FfiCaretPosition> layout_caret_position_of(Layout::BegunRead const& read, CaretLocation const& location)
+{
+ GC::Ref<DOM::Node> node = location.node;
+ auto offset = location.offset;
+ while (!is<DOM::Text>(*node)) {
+ auto* child = node->child_at_index(offset);
+ if (!child || !child->has_children() || is_atomic_inline_caret_host(*child))
+ break;
+ node = *child;
+ offset = 0;
+ }
+ return Painting::layout_caret_position(read, node, offset, location.affinity);
+}
+
+static Optional<InlineLine> caret_line(DOM::Document& document, Layout::BegunRead const& read, CaretLocation const& location)
+{
+ auto position = layout_caret_position_of(read, location);
+ if (!position.has_value())
+ return {};
+ auto line = Layout::RustFFI::render_state_caret_line(document.layout_node_arena().host(), *position);
+ if (line.root.index == Compositing::RustFFI::INVALID_NODE_SLOT_INDEX)
+ return {};
+ return line;
+}
+
+static Optional<CaretLocation> caret_location_of(DOM::Document& document, Layout::BegunRead const& read, Layout::RustFFI::FfiInlineCaretPosition const& position)
+{
+ using Kind = Layout::RustFFI::FfiInlineCaretPositionKind;
+ if (position.kind == Kind::None)
+ return {};
+ auto* layout_node = document.layout_node_arena().node_if_live(read, position.node);
+ auto* dom_node = layout_node ? layout_node->dom_node() : nullptr;
+ if (!dom_node)
+ return {};
+ switch (position.kind) {
+ case Kind::Text:
+ return CaretLocation { *dom_node, position.offset, position.downstream ? TextAffinity::Downstream : TextAffinity::Upstream };
+ case Kind::StartOfBox:
+ return CaretLocation { *dom_node, 0, TextAffinity::Downstream };
+ case Kind::BesideAtomicInline:
+ case Kind::BeforeForcedBreak:
+ if (!dom_node->parent())
+ return {};
+ return CaretLocation { *dom_node->parent(), dom_node->index() + (position.after ? 1 : 0), TextAffinity::Downstream };
+ case Kind::None:
+ break;
+ }
+ VERIFY_NOT_REACHED();
}
GC::Ptr<DOM::Node> CaretNavigator::adjacent_caret_host(DOM::Node& from, DOM::Node& editing_host, SelectionDirection direction)
@@ -174,27 +242,23 @@ Optional<CSSPixels> CaretNavigator::inline_coordinate(CaretLocation const& locat
{
Layout::ForcedReadScope read { *m_document };
m_document->update_layout_if_needed_for_node(location.node, DOM::UpdateLayoutReason::CursorLineNavigation);
- if (auto* text = as_if<DOM::Text>(*location.node))
- return cursor_inline_coordinate(read, *text, location.offset, location.affinity);
-
- if (location.offset > 0) {
- auto* child_before = location.node->child_at_index(location.offset - 1);
- if (child_before && is_atomic_inline_caret_host(*child_before)) {
- // A parent boundary after an atomic inline can paint at the same position as the end of the preceding text.
- // Use that text position when available so a vertical round trip preserves the visually chosen column.
- auto editing_host = location.node->editing_host();
- auto previous = editing_host ? adjacent_caret_host(*child_before, *editing_host, SelectionDirection::Backward) : nullptr;
- if (auto* previous_text = as_if<DOM::Text>(previous.ptr()))
- return cursor_inline_coordinate(read, *previous_text, previous_text->length(), TextAffinity::Downstream);
- }
+ // A parent boundary after an atomic inline keeps the coordinate of the end of the text before the atomic inline, so
+ // that a vertical round trip comes back in front of it.
+ auto origin = location;
+ if (auto* child_before = location.offset > 0 ? location.node->child_at_index(location.offset - 1) : nullptr; child_before && is_atomic_inline_caret_host(*child_before)) {
+ auto editing_host = location.node->editing_host();
+ auto previous = editing_host ? adjacent_caret_host(*child_before, *editing_host, SelectionDirection::Backward) : nullptr;
+ if (auto* previous_text = as_if<DOM::Text>(previous.ptr()))
+ origin = { *previous_text, previous_text->length(), TextAffinity::Downstream };
}
-
- auto const* layout_node = location.node->layout_node(read);
- return m_document->current_caret_rect().map([&](auto const& rect) {
- if (layout_node && Painting::has_committed_box(*layout_node) && as<Layout::NodeWithStyle>(*layout_node).writing_mode() != CSS::WritingMode::HorizontalTb)
- return rect.y();
- return rect.x();
- });
+ auto position = layout_caret_position_of(read, origin);
+ if (!position.has_value())
+ return {};
+ Layout::RustFFI::FfiOptionalCssPixels coordinate;
+ Layout::RustFFI::render_state_caret_inline_coordinate(m_document->layout_node_arena().host(), *position, &coordinate);
+ if (!coordinate.has_value)
+ return {};
+ return coordinate.value;
}
Optional<CaretLocation> CaretNavigator::move_to_adjacent_caret_host(CaretLocation const& location, SelectionDirection direction)
@@ -569,6 +633,67 @@ Optional<CaretLocation> CaretNavigator::move_to_editing_host_boundary(CaretLocat
return CaretLocation { *target, 0, TextAffinity::Downstream };
}
+Optional<CaretLocation> CaretNavigator::first_position_on_another_line(CaretLocation const& location, DOM::Node& editing_host, SelectionDirection direction, InlineLine const* line)
+{
+ Layout::ForcedReadScope read { *m_document };
+ for (auto host = adjacent_caret_host(navigation_origin(location, direction), editing_host, direction); host; host = adjacent_caret_host(*host, editing_host, direction)) {
+ Optional<CaretLocation> candidate;
+ if (auto* text = as_if<DOM::Text>(*host)) {
+ auto position = direction == SelectionDirection::Forward ? cursor_position_at_visual_start(*text) : cursor_position_at_visual_end(*text);
+ if (position.has_value())
+ candidate = CaretLocation { *text, position->offset, position->affinity };
+ } else if (is_empty_inline_block(*host)) {
+ candidate = CaretLocation { *host, 0 };
+ } else if (is_atomic_inline_caret_host(*host)) {
+ candidate = CaretLocation { *host->parent(), host->index() + (direction == SelectionDirection::Backward ? 1 : 0) };
+ } else if (is<HTML::HTMLBRElement>(*host) && host->parent()) {
+ candidate = CaretLocation { *host->parent(), host->index() };
+ } else {
+ candidate = CaretLocation { *host, 0 };
+ }
+ if (!candidate.has_value())
+ continue;
+ if (line) {
+ if (auto candidate_line = caret_line(*m_document, read, *candidate); candidate_line.has_value() && is_same_line(*m_document, *candidate_line, *line))
+ continue;
+ }
+ return candidate;
+ }
+ return {};
+}
+
+Optional<CaretLocation> CaretNavigator::position_on_adjacent_line(CaretLocation const& location, SelectionDirection direction, CSSPixels inline_coordinate)
+{
+ auto editing_host = location.node->editing_host();
+ if (!editing_host)
+ return {};
+ Layout::ForcedReadScope read { *m_document };
+ m_document->update_layout_if_needed_for_node(*editing_host, DOM::UpdateLayoutReason::CursorLineNavigation);
+ auto* host = m_document->layout_node_arena().host();
+
+ // The next line in the line root of the caret's line, which runs on through the fragmentainers the root spans, or
+ // else the line of the next caret position in tree order, as editing navigates lines.
+ auto line = caret_line(*m_document, read, location);
+ Optional<InlineLine> target_line;
+ if (line.has_value()) {
+ auto adjacent_line = Layout::RustFFI::render_state_adjacent_caret_line(host, *line, direction == SelectionDirection::Forward);
+ if (adjacent_line.root.index != Compositing::RustFFI::INVALID_NODE_SLOT_INDEX)
+ target_line = adjacent_line;
+ }
+ if (!target_line.has_value()) {
+ auto candidate = first_position_on_another_line(location, *editing_host, direction, line.has_value() ? &*line : nullptr);
+ if (!candidate.has_value())
+ return {};
+ target_line = caret_line(*m_document, read, *candidate);
+ if (!target_line.has_value())
+ return candidate;
+ }
+ auto position = caret_location_of(*m_document, read, Layout::RustFFI::render_state_caret_position_at_inline_coordinate(host, *target_line, inline_coordinate));
+ if (!position.has_value() || !editing_host->is_inclusive_ancestor_of(position->node))
+ return {};
+ return position;
+}
+
Optional<CaretLocation> CaretNavigator::move_by_page(CaretLocation const& location, SelectionDirection direction, CSSPixels inline_coordinate)
{
auto editing_host = location.node->editing_host();
@@ -584,9 +709,8 @@ Optional<CaretLocation> CaretNavigator::move_by_page(CaretLocation const& locati
if (!window)
return {};
- // INTEROP: Chromium defines a page as the smaller of the editing host and viewport heights, then leaves either
- // 12.5% or (on macOS) at least 40 CSS pixels of overlap. It walks visual lines until the next line would exceed
- // that distance, rather than mapping the target coordinate directly back into the DOM.
+ // INTEROP: A page is the smaller of the editing host and viewport heights, less 12.5% (or on macOS, at least 40 CSS
+ // pixels) of overlap. A page move walks lines until the next one would be farther away than that.
auto page_height = min(Painting::absolute_padding_box_rect(*editing_host_layout_node).height().to_int(), window->inner_height());
if (page_height <= 0)
return {};
@@ -596,32 +720,29 @@ Optional<CaretLocation> CaretNavigator::move_by_page(CaretLocation const& locati
#endif
page_distance = max(page_distance, 1);
- auto start_block_coordinate = m_document->caret_line_block_coordinate(read, location.node, location.offset, location.affinity);
- if (!start_block_coordinate.has_value())
+ auto* host = m_document->layout_node_arena().host();
+ auto start_line = caret_line(*m_document, read, location);
+ if (!start_line.has_value())
return {};
+ CSSPixels start_block_coordinate;
+ Layout::RustFFI::render_state_caret_line_block_coordinate(host, *start_line, &start_block_coordinate);
auto current = location;
Optional<CaretLocation> result;
- auto line_direction = direction == SelectionDirection::Forward ? Painting::CaretLineDirection::Next : Painting::CaretLineDirection::Previous;
for (u32 iteration = 0; iteration < 1024; ++iteration) {
- auto position = m_document->caret_position_on_adjacent_line(read, current.node, current.offset, current.affinity, line_direction, inline_coordinate, *editing_host);
- Optional<CaretLocation> next;
- auto boundary = position.has_value() ? position->boundary_point() : Optional<DOM::BoundaryPoint> {};
- if (boundary.has_value()) {
- next = CaretLocation { boundary->node, boundary->offset, position->affinity };
- } else {
- // PreviousLinePosition and NextLinePosition in Chromium expose the editing-host boundary as a final stop
- // on the first or last visual line. Preserve that stop when it still fits within this page movement.
+ auto next = position_on_adjacent_line(current, direction, inline_coordinate);
+ if (!next.has_value())
next = move_to_editing_host_boundary(current, direction);
- if (!next.has_value() || (next->node == current.node && next->offset == current.offset))
- break;
- }
- auto next_block_coordinate = m_document->caret_line_block_coordinate(read, next->node, next->offset, next->affinity);
- if (!next_block_coordinate.has_value())
+ if (!next.has_value() || (next->node == current.node && next->offset == current.offset))
+ break;
+ auto next_line = caret_line(*m_document, read, *next);
+ if (!next_line.has_value())
break;
- auto block_distance = *next_block_coordinate > *start_block_coordinate
- ? *next_block_coordinate - *start_block_coordinate
- : *start_block_coordinate - *next_block_coordinate;
+ CSSPixels next_block_coordinate;
+ Layout::RustFFI::render_state_caret_line_block_coordinate(host, *next_line, &next_block_coordinate);
+ auto block_distance = next_block_coordinate > start_block_coordinate
+ ? next_block_coordinate - start_block_coordinate
+ : start_block_coordinate - next_block_coordinate;
if (block_distance > CSSPixels(page_distance))
break;
current = *next;
@@ -743,54 +864,27 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Sele
if (granularity == SelectionGranularity::LineBoundary || granularity == SelectionGranularity::PhysicalLineBoundary) {
Layout::ForcedReadScope read { *m_document };
m_document->update_layout_if_needed_for_node(location.node, DOM::UpdateLayoutReason::CursorLineNavigation);
- auto edge = direction == SelectionDirection::Forward ? Painting::CaretLineEdge::End : Painting::CaretLineEdge::Start;
- if (granularity == SelectionGranularity::PhysicalLineBoundary)
- edge = direction == SelectionDirection::Forward ? Painting::CaretLineEdge::Right : Painting::CaretLineEdge::Left;
- auto position = m_document->caret_position_at_line_edge(read, location.node, location.offset, location.affinity, edge);
- if (!position.has_value())
+ auto line = caret_line(*m_document, read, location);
+ if (!line.has_value())
return {};
- auto boundary = position->boundary_point();
- if (!boundary.has_value())
- return {};
- return CaretLocation { boundary->node, boundary->offset, position->affinity };
+ auto edge = direction == SelectionDirection::Forward ? Layout::RustFFI::LineEdge::End : Layout::RustFFI::LineEdge::Start;
+ if (granularity == SelectionGranularity::PhysicalLineBoundary)
+ edge = direction == SelectionDirection::Forward ? Layout::RustFFI::LineEdge::Right : Layout::RustFFI::LineEdge::Left;
+ return caret_location_of(*m_document, read, Layout::RustFFI::render_state_caret_position_at_line_edge(m_document->layout_node_arena().host(), *line, edge, location.node->is_editable_or_editing_host()));
}
VERIFY(granularity == SelectionGranularity::Line);
- auto line_origin = location;
- // Resolve the parent boundary after an atomic inline to its visually equivalent text edge before asking painting
- // which line contains the caret. This avoids selecting the atomic inline's other side as the current line.
- if (!text && location.offset > 0) {
- auto* child_before = location.node->child_at_index(location.offset - 1);
- if (child_before && is_atomic_inline_caret_host(*child_before)) {
- auto editing_host = location.node->editing_host();
- auto previous = editing_host ? adjacent_caret_host(*child_before, *editing_host, SelectionDirection::Backward) : nullptr;
- if (auto* previous_text = as_if<DOM::Text>(previous.ptr())) {
- line_origin = { *previous_text, previous_text->length(), TextAffinity::Downstream };
- text = previous_text;
- }
- }
- }
-
- auto editing_host = line_origin.node->editing_host();
+ auto editing_host = location.node->editing_host();
if (!editing_host || !preferred_inline_coordinate.has_value())
return {};
- Layout::ForcedReadScope read { *m_document };
- m_document->update_layout_if_needed_for_node(line_origin.node, DOM::UpdateLayoutReason::CursorLineNavigation);
- auto line_direction = direction == SelectionDirection::Forward ? Painting::CaretLineDirection::Next : Painting::CaretLineDirection::Previous;
- auto position = m_document->caret_position_on_adjacent_line(read, line_origin.node, line_origin.offset, line_origin.affinity, line_direction, *preferred_inline_coordinate, *editing_host);
- if (!position.has_value()) {
- // INTEROP: Chromium and WebKit move to the current line's directional edge when there is no visual line in the
- // requested direction. This makes Up and Down useful at the first and final lines instead of becoming no-ops.
- auto edge = direction == SelectionDirection::Forward ? Painting::CaretLineEdge::End : Painting::CaretLineEdge::Start;
- position = m_document->caret_position_at_line_edge(read, line_origin.node, line_origin.offset, line_origin.affinity, edge);
- if (!position.has_value())
- return {};
- }
-
- auto boundary = position->boundary_point();
- if (!boundary.has_value())
+ // INTEROP: With no line in the requested direction, the caret moves to the start or end of the editing host.
+ auto position = position_on_adjacent_line(location, direction, *preferred_inline_coordinate);
+ if (!position.has_value())
+ position = move_to_editing_host_boundary(location, direction);
+ if (!position.has_value())
return {};
- CaretLocation destination { boundary->node, boundary->offset, position->affinity };
+
+ auto destination = *position;
// Point-to-caret resolution naturally returns the parent boundary before an atomic inline. For a collapsed caret,
// prefer the visually equivalent preceding text edge so horizontal movement does not revisit the same position.
if (alteration == SelectionAlteration::Move && !is<DOM::Text>(*destination.node)) {
@@ -802,13 +896,11 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Sele
}
}
auto* destination_text = as_if<DOM::Text>(*destination.node);
- if (alteration == SelectionAlteration::Extend && destination_text
- && ((direction == SelectionDirection::Forward && destination.offset == 0)
- || (direction == SelectionDirection::Backward && destination.offset == destination_text->length()))) {
- auto origin_block = Editing::block_node_of_node(line_origin.node);
+ if (alteration == SelectionAlteration::Extend && destination_text && direction == SelectionDirection::Forward && destination.offset == 0) {
+ auto origin_block = Editing::block_node_of_node(location.node);
auto destination_block = Editing::block_node_of_node(*destination_text);
if (origin_block && destination_block && origin_block != destination_block)
- destination = canonical_location_at_outer_edge_of_inline_content(*destination_text, *destination_block, direction);
+ destination = canonical_location_at_start_of_inline_content(*destination_text, *destination_block);
}
return destination;
}
diff --git a/Libraries/LibWeb/Selection/CaretNavigation.h b/Libraries/LibWeb/Selection/CaretNavigation.h
index ccb692d3f0d..b7e609399aa 100644
--- a/Libraries/LibWeb/Selection/CaretNavigation.h
+++ b/Libraries/LibWeb/Selection/CaretNavigation.h
@@ -13,6 +13,12 @@
#include <LibWeb/TextAffinity.h>
#include <LibWebCommon/PixelUnits.h>
+namespace Web::Layout::RustFFI {
+
+struct FfiInlineLine;
+
+}
+
namespace Web::Selection {
enum class SelectionAlteration : u8 {
@@ -65,6 +71,8 @@ private:
Optional<CaretLocation> move_to_editing_host_boundary(CaretLocation const&, SelectionDirection);
Optional<CaretLocation> move_to_paragraph_boundary(CaretLocation const&, SelectionDirection);
Optional<CaretLocation> move_by_page(CaretLocation const&, SelectionDirection, CSSPixels inline_coordinate);
+ Optional<CaretLocation> position_on_adjacent_line(CaretLocation const&, SelectionDirection, CSSPixels inline_coordinate);
+ Optional<CaretLocation> first_position_on_another_line(CaretLocation const&, DOM::Node& editing_host, SelectionDirection, Layout::RustFFI::FfiInlineLine const* line);
Optional<CaretLocation> move_by_word(CaretLocation const&, SelectionAlteration, SelectionDirection);
GC::Ptr<DOM::Node> adjacent_caret_host(DOM::Node&, DOM::Node& editing_host, SelectionDirection);
Optional<CaretLocation> location_before_atomic_inline(DOM::Node&, SelectionAlteration);
diff --git a/Libraries/LibWeb/Selection/SelectionModifier.cpp b/Libraries/LibWeb/Selection/SelectionModifier.cpp
index cf0ecade98f..20b8ba17008 100644
--- a/Libraries/LibWeb/Selection/SelectionModifier.cpp
+++ b/Libraries/LibWeb/Selection/SelectionModifier.cpp
@@ -24,13 +24,12 @@ void SelectionModifier::modify(SelectionAlteration alteration, SelectionDirectio
auto origin = Editing::VisiblePosition::create(*m_selection->document(), { *focus, static_cast<WebIDL::UnsignedLong>(m_selection->focus_offset()) }, m_selection->focus_affinity());
// INTEROP: Major engines remember a preferred inline-axis position across consecutive Up/Down operations. Without
- // this state, traversing a short line permanently shifts the caret column for every subsequent line.
+ // this state, traversing a short line permanently shifts the caret column for every subsequent line. Any other
+ // change of the selection forgets it, but a move that leaves the caret where it was keeps it.
auto preferred_inline_coordinate = m_selection->m_preferred_inline_coordinate;
auto is_vertical_movement = granularity == SelectionGranularity::Line || granularity == SelectionGranularity::Page;
if (is_vertical_movement && !preferred_inline_coordinate.has_value())
preferred_inline_coordinate = origin.inline_coordinate();
- else if (!is_vertical_movement)
- m_selection->m_preferred_inline_coordinate.clear();
Optional<Editing::VisiblePosition> destination;
Optional<DOM::BoundaryPoint> canonical_anchor;
@@ -47,6 +46,9 @@ void SelectionModifier::modify(SelectionAlteration alteration, SelectionDirectio
return;
auto destination_boundary = destination->boundary();
+ if (alteration == SelectionAlteration::Move && m_selection->is_collapsed() && destination_boundary.node.ptr() == focus.ptr()
+ && destination_boundary.offset == m_selection->focus_offset() && destination->affinity() == m_selection->focus_affinity())
+ return;
// Apply exactly one selection mutation after navigation has produced a complete destination. In particular, do
// not use Selection itself as scratch state while walking across DOM nodes or painted lines.
if (alteration == SelectionAlteration::Move) {
diff --git a/Libraries/LibWeb/VisualLines.cpp b/Libraries/LibWeb/VisualLines.cpp
index d0287dd6654..325f38d3d85 100644
--- a/Libraries/LibWeb/VisualLines.cpp
+++ b/Libraries/LibWeb/VisualLines.cpp
@@ -105,19 +105,6 @@ Optional<CursorLinePosition> compute_cursor_position_on_previous_character(DOM::
return CursorLinePosition { *previous_offset, TextAffinity::Downstream };
}
-Optional<CSSPixels> cursor_inline_coordinate(Layout::BegunRead const& read, DOM::Text const& dom_node, size_t offset, TextAffinity affinity)
-{
- const_cast<DOM::Document&>(dom_node.document()).update_layout_if_needed_for_node(dom_node, DOM::UpdateLayoutReason::CursorLineNavigation);
- auto const* layout_node = dom_node.layout_node(read);
- if (!layout_node)
- return {};
- Layout::RustFFI::FfiOptionalCssPixels result;
- Layout::RustFFI::render_state_text_caret_inline_coordinate(layout_node->document_host(), Layout::Node::slot_id(layout_node), offset, affinity == TextAffinity::Downstream, &result);
- if (!result.has_value)
- return {};
- return result.value;
-}
-
Optional<CursorLinePosition> cursor_position_at_visual_start(DOM::Text const& dom_node)
{
auto lines = visual_lines_with_up_to_date_layout(dom_node);
diff --git a/Libraries/LibWeb/VisualLines.h b/Libraries/LibWeb/VisualLines.h
index a617f1bfae4..2b5084f2076 100644
--- a/Libraries/LibWeb/VisualLines.h
+++ b/Libraries/LibWeb/VisualLines.h
@@ -11,7 +11,6 @@
#include <AK/Vector.h>
#include <LibWeb/Forward.h>
#include <LibWeb/TextAffinity.h>
-#include <LibWebCommon/PixelUnits.h>
namespace Web {
@@ -46,11 +45,6 @@ Optional<CursorLinePosition> compute_cursor_position_on_previous_character(DOM::
size_t find_line_start(Utf16View const&, size_t offset);
size_t find_line_end(Utf16View const&, size_t offset);
-// Helpers for caret navigation across node boundaries.
-// The absolute inline-axis coordinate of the caret at the given offset, used to keep the caret column when moving
-// between lines. Returns nothing for positions on lines without rendered text.
-Optional<CSSPixels> cursor_inline_coordinate(Layout::BegunRead const&, DOM::Text const&, size_t offset, TextAffinity);
-
// Cursor positions for entering a text node from an adjacent node. The "visual start" and "visual end" positions are
// the rendered start of the first line and the rendered end of the last line; the "closest to" variants pick the
// position on the first/last visual line closest to the given inline coordinate (or the line start when there is no
diff --git a/Tests/LibWeb/Text/expected/Editing/caret-walk-through-inline-bidi-and-shadow-content.txt b/Tests/LibWeb/Text/expected/Editing/caret-walk-through-inline-bidi-and-shadow-content.txt
index 0121667783f..bb94a5b4a4b 100644
--- a/Tests/LibWeb/Text/expected/Editing/caret-walk-through-inline-bidi-and-shadow-content.txt
+++ b/Tests/LibWeb/Text/expected/Editing/caret-walk-through-inline-bidi-and-shadow-content.txt
@@ -82,30 +82,30 @@ bidi Left #text[0]:3
bidi Left #text[0]:2
bidi Left #text[0]:1
bidi Left #text[0]:0
-bidi Down #text[0]:4
-bidi Down #text[0]:4
-bidi Down #text[0]:4
-bidi Down #text[0]:4
-bidi Down #text[0]:4
-bidi Down #text[0]:4
-bidi Up #text[2]:0
-bidi Up #text[2]:0
-bidi Up #text[2]:0
-bidi Up #text[2]:0
-bidi Up #text[2]:0
-bidi Up #text[2]:0
-bidi Home #text[2]:0
-bidi Home #text[2]:0
-bidi Home #text[2]:0
-bidi Home #text[2]:0
-bidi Home #text[2]:0
-bidi Home #text[2]:0
-bidi End #text[0]:4
-bidi End #text[0]:4
-bidi End #text[0]:4
-bidi End #text[0]:4
-bidi End #text[0]:4
-bidi End #text[0]:4
+bidi Down #text[2]:4
+bidi Down #text[2]:4
+bidi Down #text[2]:4
+bidi Down #text[2]:4
+bidi Down #text[2]:4
+bidi Down #text[2]:4
+bidi Up #text[0]:0
+bidi Up #text[0]:0
+bidi Up #text[0]:0
+bidi Up #text[0]:0
+bidi Up #text[0]:0
+bidi Up #text[0]:0
+bidi Home #text[0]:0
+bidi Home #text[0]:0
+bidi Home #text[0]:0
+bidi Home #text[0]:0
+bidi Home #text[0]:0
+bidi Home #text[0]:0
+bidi End #text[2]:4
+bidi End #text[2]:4
+bidi End #text[2]:4
+bidi End #text[2]:4
+bidi End #text[2]:4
+bidi End #text[2]:4
host Right #text[0/0]:0
host Right #text[0/0]:1
host Right #text[0/0]:2
@@ -118,30 +118,30 @@ host Left #text[0/0]:2
host Left #text[0/0]:1
host Left #text[0/0]:0
host Left #text[0/0]:0
-host Down #text[shadow/0/2]:6
-host Down #text[shadow/0/2]:6
-host Down #text[shadow/0/2]:6
-host Down #text[shadow/0/2]:6
-host Down #text[shadow/0/2]:6
-host Down #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Up #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host Home #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
-host End #text[shadow/0/2]:6
+host Down #text[1/0]:11
+host Down #text[1/0]:11
+host Down #text[1/0]:11
+host Down #text[1/0]:11
+host Down #text[1/0]:11
+host Down #text[1/0]:11
+host Up #text[0/0]:0
+host Up #text[0/0]:0
+host Up #text[0/0]:0
+host Up #text[0/0]:0
+host Up #text[0/0]:0
+host Up #text[0/0]:0
+host Home #text[0/0]:0
+host Home #text[0/0]:0
+host Home #text[0/0]:0
+host Home #text[0/0]:0
+host Home #text[0/0]:0
+host Home #text[0/0]:0
+host End #text[1/0]:11
+host End #text[1/0]:11
+host End #text[1/0]:11
+host End #text[1/0]:11
+host End #text[1/0]:11
+host End #text[1/0]:11
empty Right DIV[]:0
empty Right DIV[]:0
empty Right DIV[]:0
@@ -226,12 +226,12 @@ atomic Left #text[0]:3
atomic Left #text[0]:2
atomic Left #text[0]:1
atomic Left #text[0]:0
-atomic Down #text[2/0]:0
-atomic Down #text[2/0]:1
-atomic Down #text[2/0]:1
-atomic Down #text[2/0]:1
-atomic Down #text[2/0]:1
-atomic Down #text[2/0]:1
+atomic Down #text[3]:5
+atomic Down #text[3]:5
+atomic Down #text[3]:5
+atomic Down #text[3]:5
+atomic Down #text[3]:5
+atomic Down #text[3]:5
atomic Up #text[0]:0
atomic Up #text[0]:0
atomic Up #text[0]:0
@@ -330,32 +330,32 @@ plain@6 Home #text[0]:0
plain@6 End #text[3]:6
atomic@0 Right #text[0]:0
atomic@0 Left #text[0]:0
-atomic@0 Down #text[2/0]:0
+atomic@0 Down #text[3]:5
atomic@0 Up #text[0]:0
atomic@0 Home #text[0]:0
atomic@0 End #text[3]:5
atomic@1 Right DIV[]:2
atomic@1 Left #text[0]:6
-atomic@1 Down #text[2/0]:0
-atomic@1 Up #text[0]:6
+atomic@1 Down #text[3]:5
+atomic@1 Up #text[0]:0
atomic@1 Home #text[0]:0
atomic@1 End #text[3]:5
atomic@2 Right DIV[]:3
atomic@2 Left DIV[]:2
-atomic@2 Down #text[2/0]:0
-atomic@2 Up #text[0]:6
+atomic@2 Down #text[3]:5
+atomic@2 Up #text[0]:0
atomic@2 Home #text[0]:0
atomic@2 End #text[3]:5
atomic@3 Right #text[3]:1
atomic@3 Left #text[3]:0
-atomic@3 Down #text[2/0]:1
-atomic@3 Up DIV[]:3
+atomic@3 Down #text[3]:5
+atomic@3 Up #text[0]:0
atomic@3 Home #text[0]:0
atomic@3 End #text[3]:5
atomic@4 Right DIV[]:4
atomic@4 Left #text[3]:5
-atomic@4 Down #text[2/0]:1
-atomic@4 Up #text[3]:5
+atomic@4 Down #text[3]:5
+atomic@4 Up #text[0]:0
atomic@4 Home #text[0]:0
atomic@4 End #text[3]:5
nested@0 Right #text[0/0/0/0]:0
@@ -378,22 +378,22 @@ nested@2 Home #text[0/0/0/0]:0
nested@2 End #text[0/0/0/0]:4
host@0 Right #text[0/0]:0
host@0 Left #text[0/0]:0
-host@0 Down #text[shadow/0/2]:6
-host@0 Up #text[shadow/0/2]:6
-host@0 Home #text[shadow/0/2]:6
-host@0 End #text[shadow/0/2]:6
+host@0 Down #text[1/0]:11
+host@0 Up #text[0/0]:0
+host@0 Home #text[0/0]:0
+host@0 End #text[1/0]:11
host@1 Right #text[0/0]:0
host@1 Left #text[0/0]:0
-host@1 Down #text[shadow/0/2]:6
-host@1 Up #text[shadow/0/2]:6
-host@1 Home #text[shadow/0/2]:6
-host@1 End #text[shadow/0/2]:6
+host@1 Down #text[1/0]:11
+host@1 Up #text[0/0]:0
+host@1 Home #text[0/0]:0
+host@1 End #text[1/0]:11
host@2 Right #text[1/0]:0
host@2 Left #text[0/0]:10
-host@2 Down #text[shadow/0/2]:6
-host@2 Up #text[shadow/0/2]:6
-host@2 Home #text[shadow/0/2]:6
-host@2 End #text[shadow/0/2]:6
+host@2 Down #text[1/0]:11
+host@2 Up #text[0/0]:0
+host@2 Home #text[0/0]:0
+host@2 End #text[1/0]:11
breaks@0 Right #text[0]:0
breaks@0 Left #text[0]:0
breaks@0 Down DIV[]:2
@@ -426,10 +426,10 @@ breaks@4 Home DIV[]:2
breaks@4 End DIV[]:2
breaks@5 Right DIV[]:5
breaks@5 Left DIV[]:5
-breaks@5 Down DIV[]:5
-breaks@5 Up DIV[]:5
-breaks@5 Home DIV[]:5
-breaks@5 End DIV[]:5
+breaks@5 Down #text[3]:5
+breaks@5 Up DIV[]:2
+breaks@5 Home DIV[]:2
+breaks@5 End DIV[]:2
point 0 #text[0]:0
point 10 #text[0]:1
point 20 #text[0]:3
diff --git a/Tests/LibWeb/Text/expected/contenteditable-wrap-space-caret.txt b/Tests/LibWeb/Text/expected/contenteditable-wrap-space-caret.txt
index 77bbba10d68..77d49508582 100644
--- a/Tests/LibWeb/Text/expected/contenteditable-wrap-space-caret.txt
+++ b/Tests/LibWeb/Text/expected/contenteditable-wrap-space-caret.txt
@@ -1,9 +1,9 @@
Right over the wrap space: focus=18 anchor=18
-Down from end of first visual line: focus=36 anchor=36
+Down from end of first visual line: focus=35 anchor=35
Right twice from before the wrap space: focus=18 anchor=18
Down from start of second visual line: focus=36 anchor=36
Right three times from before the wrap space: focus=19 anchor=19
Left from start of second visual line: focus=18 anchor=18
-Down after stepping back to end of first visual line: focus=36 anchor=36
-Left again over the wrap space: focus=35 anchor=35
+Down after stepping back to end of first visual line: focus=35 anchor=35
+Left again over the wrap space: focus=34 anchor=34
Shift+Right selects the wrap space: focus=18 anchor=17