Skip to content

Truly independent web browser

LibWeb: Remove VisualLines and read caret lines from InlineCursor

Aliaksandr Kalenikef3fa94aa30e
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8bc3852c701..a1d56ce3880 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -920,7 +920,6 @@ set(SOURCES
UserTiming/PerformanceMark.cpp
UserTiming/PerformanceMeasure.cpp
ViewTransition/ViewTransition.cpp
- VisualLines.cpp
WebLocks/AbstractOperations.cpp
WebLocks/LockManager.cpp
WebLocks/NavigatorLocks.cpp
diff --git a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
index b1a5e63960f..f8b10399766 100644
--- a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
+++ b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
@@ -47,7 +47,6 @@
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/PaintableTypes.h>
#include <LibWeb/Selection/Selection.h>
-#include <LibWeb/VisualLines.h>
#include <LibWebCommon/WebView/AccessibilityNodeData.h>
namespace Web::DOM {
@@ -261,14 +260,19 @@ static bool fill_text_geometry(WebView::AccessibilityNodeData& node_data, DOM::T
return caret.rect;
};
+ Vector<Layout::RustFFI::FfiVisualLine> lines;
+ if (layout) {
+ Layout::RustFFI::render_state_text_visual_lines(layout->document_host(), Layout::Node::slot_id(layout), &lines,
+ [](void* context, Layout::RustFFI::FfiVisualLine line) {
+ static_cast<Vector<Layout::RustFFI::FfiVisualLine>*>(context)->append(line);
+ });
+ }
struct RenderedLine {
- VisualLine line;
+ Layout::RustFFI::FfiVisualLine line;
CSSPixelRect rect;
};
Vector<RenderedLine> rendered_lines;
- for (auto const& line : collect_visual_lines(read, text_node)) {
- if (!line.has_fragments)
- continue;
+ for (auto const& line : lines) {
if (auto rect = line_rect_at_offset(line.start_offset); rect.has_value())
rendered_lines.append({ line, *rect });
}
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 68f026c065e..da3ea684378 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -109,7 +109,6 @@
#include <LibWeb/Translation/DocumentTranslator.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
-#include <LibWeb/VisualLines.h>
#include <LibWeb/XLink/AttributeNames.h>
#include <LibWebCommon/Infra/CharacterTypes.h>
#include <LibWebCommon/Infra/Strings.h>
@@ -4404,8 +4403,8 @@ void Node::build_accessibility_tree(AccessibilityTreeNode& parent)
// render, the space between two inline siblings, stays: Gecko and Blink expose it, and it's what keeps the
// siblings' text apart in an AT's text view.
if (static_cast<Text const&>(*this).data().is_ascii_whitespace()) {
- auto lines = collect_visual_lines(read, static_cast<Text const&>(*this));
- if (!any_of(lines, [](auto const& line) { return line.has_fragments; }))
+ auto const* layout_node = unsafe_layout_node(read);
+ if (!layout_node || !Layout::RustFFI::render_state_text_has_rendered_text(layout_node->document_host(), Layout::Node::slot_id(layout_node)))
return;
}
parent.append_child(AccessibilityTreeNode::create(this).ptr());
diff --git a/Libraries/LibWeb/Editing/ClipboardSerializer.cpp b/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
index aaaebbd8b5b..99b80c6a340 100644
--- a/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
+++ b/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
@@ -30,7 +30,6 @@
#include <LibWeb/HTML/XMLSerializer.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Namespace.h>
-#include <LibWeb/VisualLines.h>
#include <LibWeb/Editing/StyledMarkupSerializer.h>
@@ -118,7 +117,7 @@ private:
return;
// Source formatting whitespace between blocks has a layout node but produces no painted text. TextIterator
// based engines omit it from the plain-text clipboard representation.
- if (collect_visual_lines(read, *text).is_empty())
+ if (!Layout::RustFFI::render_state_text_has_lines(layout_node->document_host(), Layout::Node::slot_id(layout_node)))
return;
Utf16String data;
diff --git a/Libraries/LibWeb/Editing/StyledMarkupSerializer.cpp b/Libraries/LibWeb/Editing/StyledMarkupSerializer.cpp
index 0787b1a62b9..79faafa0f72 100644
--- a/Libraries/LibWeb/Editing/StyledMarkupSerializer.cpp
+++ b/Libraries/LibWeb/Editing/StyledMarkupSerializer.cpp
@@ -34,7 +34,6 @@
#include <LibWeb/HTML/XMLSerializer.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Namespace.h>
-#include <LibWeb/VisualLines.h>
#include <LibWeb/Editing/StyledMarkupSerializer.h>
@@ -332,7 +331,7 @@ static void classify_cloned_text_for_interchange(Layout::BegunRead const& read,
auto white_space_collapse = resolved_keyword(*text.source, CSS::PropertyID::WhiteSpaceCollapse);
if (white_space_collapse.has_value() && white_space_collapse != CSS::Keyword::Collapse) {
text_with_preserved_breaks.append(*text.serialized);
- } else if (collect_visual_lines(read, *text.source).is_empty()) {
+ } else if (auto const* layout_node = text.source->unsafe_layout_node(read); !layout_node || !Layout::RustFFI::render_state_text_has_lines(layout_node->document_host(), Layout::Node::slot_id(layout_node))) {
unrendered_text.append(*text.serialized);
}
}
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
index 5aa25196fa4..915cdc6d05b 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
@@ -46,8 +46,8 @@
#include <LibWeb/Page/EventHandler.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/HitTestDisplayList.h>
+#include <LibWeb/Selection/CaretNavigation.h>
#include <LibWeb/UIEvents/InputTypes.h>
-#include <LibWeb/VisualLines.h>
#include <LibWebCommon/Infra/Strings.h>
namespace Web::HTML {
@@ -1716,7 +1716,7 @@ void FormAssociatedTextControlElement::increment_cursor_position_offset(Collapse
collapse_selection_to_offset(max(m_selection_start, m_selection_end));
}
// Otherwise, move forward if possible
- else if (auto new_position = compute_cursor_position_on_next_character(*text_node, m_selection_end, m_selection_end_affinity); new_position.has_value()) {
+ else if (auto new_position = Selection::location_after_character_step(*text_node, m_selection_end, m_selection_end_affinity, Selection::SelectionDirection::Forward); new_position.has_value()) {
move_selection_end_to(new_position->offset, new_position->affinity, collapse);
}
selection_was_changed(SelectionSource::UI);
@@ -1732,7 +1732,7 @@ void FormAssociatedTextControlElement::decrement_cursor_position_offset(Collapse
collapse_selection_to_offset(min(m_selection_start, m_selection_end));
}
// Otherwise, move backward if possible
- else if (auto new_position = compute_cursor_position_on_previous_character(*text_node, m_selection_end, m_selection_end_affinity); new_position.has_value()) {
+ else if (auto new_position = Selection::location_after_character_step(*text_node, m_selection_end, m_selection_end_affinity, Selection::SelectionDirection::Backward); new_position.has_value()) {
move_selection_end_to(new_position->offset, new_position->affinity, collapse);
}
selection_was_changed(SelectionSource::UI);
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index 432318d3dbc..b2a6406b40a 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -87,7 +87,6 @@
#include <LibWeb/UIEvents/TextEvent.h>
#include <LibWeb/UIEvents/TouchEvent.h>
#include <LibWeb/UIEvents/WheelEvent.h>
-#include <LibWeb/VisualLines.h>
#include <LibWebCommon/Clipboard/SystemClipboard.h>
#include <LibWebCommon/Infra/Strings.h>
#include <LibWebCommon/UIEvents/MouseButton.h>
@@ -4507,6 +4506,21 @@ bool EventHandler::initiate_word_selection(Layout::BegunRead const& read, DOM::D
return true;
}
+static size_t find_line_start(Utf16View const& view, size_t offset)
+{
+ while (offset != 0 && view.code_unit_at(offset - 1) != '\n')
+ --offset;
+ return offset;
+}
+
+static size_t find_line_end(Utf16View const& view, size_t offset)
+{
+ auto length = view.length_in_code_units();
+ while (offset < length && view.code_unit_at(offset) != '\n')
+ ++offset;
+ return offset;
+}
+
bool EventHandler::initiate_paragraph_selection(DOM::Document& document, Painting::CaretPosition const& caret_position, CSS::UserSelect user_select)
{
auto* boundary_node = as_if<DOM::Text>(caret_position.boundary_node().ptr());
diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
index ae2531a220a..affbbb48eda 100644
--- a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
@@ -918,6 +918,70 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
})
}
+ /// The caret position at the start of the first line of the DOM text whose layout node is `text`, or at the end of
+ /// its last line.
+ pub(crate) fn text_edge(&self, text: NodeSlotId, end: bool) -> Option<CaretPosition> {
+ let lines = self.lines_of_text(text);
+ let (offset, downstream) = if end {
+ (lines.last()?.end_offset, true)
+ } else {
+ let first = lines.first()?;
+ let second_line_starts_later = lines
+ .get(1)
+ .is_none_or(|second| second.start_offset > first.start_offset);
+ (first.start_offset, second_line_starts_later)
+ };
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ })
+ }
+
+ /// The first line of the DOM text whose layout node is `text`, or its last, where it holds rendered text of it.
+ pub(crate) fn rendered_text_edge_line(&self, text: NodeSlotId, end: bool) -> Option<InlineLine> {
+ let lines = self.lines_of_text(text);
+ let line = if end { lines.last() } else { lines.first() }?;
+ line.has_fragments.then_some(line.line)
+ }
+
+ /// The caret position one grapheme right of (`forward`) or left of `offset` in the DOM text whose layout node is
+ /// `text`, where the grapheme boundary that way is `grapheme_boundary`. Where one line ends and the next starts at
+ /// a soft wrap, the offset has a caret position on each line, and a step visits both.
+ pub(crate) fn position_after_character_step(
+ &self,
+ text: NodeSlotId,
+ offset: usize,
+ downstream: bool,
+ forward: bool,
+ grapheme_boundary: Option<usize>,
+ ) -> Option<CaretPosition> {
+ let lines = self.lines_of_text(text);
+ let ends_one_line_and_starts_the_next = |offset: usize| {
+ lines
+ .windows(2)
+ .any(|pair| pair[0].end_offset_with_trailing_whitespace == offset && pair[1].start_offset == offset)
+ };
+ if downstream != forward && ends_one_line_and_starts_the_next(offset) {
+ return Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream: forward,
+ });
+ }
+ let offset = grapheme_boundary?;
+ let is_in_whitespace_hanging_at_line_end = lines
+ .iter()
+ .any(|line| line.end_offset < offset && offset <= line.end_offset_with_trailing_whitespace);
+ let stays_on_earlier_line =
+ forward && (is_in_whitespace_hanging_at_line_end || ends_one_line_and_starts_the_next(offset));
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream: !stays_on_earlier_line,
+ })
+ }
+
/// 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/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rs
index 2917bc6d748..0605b888e15 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -827,16 +827,15 @@ pub extern "C" fn render_state_inline_paintable_first_piece_position(
};
}
+/// The DOM offsets a line renders of a DOM text.
#[repr(C)]
pub struct FfiVisualLine {
pub start_offset: usize,
pub end_offset: usize,
- pub end_offset_with_trailing_whitespace: usize,
- pub has_fragments: bool,
- pub owner_paintable: u32,
- pub line_index: u32,
}
+/// Pushes the lines that hold rendered text of the DOM text whose layout node is `primary`, in DOM order.
+///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
@@ -849,10 +848,10 @@ pub unsafe extern "C" fn render_state_text_visual_lines(
) {
let lines = {
read_arena(host, node_read(), primary, |arena, primary| {
- crate::layout::query::inline_cursor::InlineCursor::new(&arena.paintable_rows()).lines_of_text(primary)
+ InlineCursor::new(&arena.paintable_rows()).lines_of_text(primary)
})
};
- for line in lines {
+ for line in lines.into_iter().filter(|line| line.has_fragments) {
// SAFETY: The consumer copies the POD line synchronously.
unsafe {
push(
@@ -860,16 +859,92 @@ pub unsafe extern "C" fn render_state_text_visual_lines(
FfiVisualLine {
start_offset: line.start_offset,
end_offset: line.end_offset,
- end_offset_with_trailing_whitespace: line.end_offset_with_trailing_whitespace,
- has_fragments: line.has_fragments,
- owner_paintable: line.line.root.index,
- line_index: line.line.index,
},
);
}
}
}
+/// Whether a line holds rendered text of the DOM text whose layout node is `primary`.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_has_rendered_text(host: &DocumentHost, primary: NodeSlotId) -> bool {
+ read_arena(host, node_read(), primary, |arena, primary| {
+ InlineCursor::new(&arena.paintable_rows())
+ .lines_of_text(primary)
+ .iter()
+ .any(|line| line.has_fragments)
+ })
+}
+
+/// Whether the DOM text whose layout node is `primary` is on a line: one that holds rendered text of it, or one that a
+/// preserved newline in it ends with nothing on it.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_has_lines(host: &DocumentHost, primary: NodeSlotId) -> bool {
+ read_arena(host, node_read(), primary, |arena, primary| {
+ !InlineCursor::new(&arena.paintable_rows())
+ .lines_of_text(primary)
+ .is_empty()
+ })
+}
+
+/// The caret position at the start of the first line of the DOM text whose layout node is `primary`, or at the end of
+/// its last line.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_edge(
+ host: &DocumentHost,
+ primary: NodeSlotId,
+ end: bool,
+) -> FfiInlineCaretPosition {
+ read_arena(host, node_read(), (primary, end), |arena, (primary, end)| {
+ FfiInlineCaretPosition::of(InlineCursor::new(&arena.paintable_rows()).text_edge(primary, end))
+ })
+}
+
+/// The first line of the DOM text whose layout node is `primary`, or its last, where it holds rendered text of it.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_rendered_edge_line(
+ host: &DocumentHost,
+ primary: NodeSlotId,
+ end: bool,
+) -> FfiInlineLine {
+ read_arena(host, node_read(), (primary, end), |arena, (primary, end)| {
+ FfiInlineLine::of(InlineCursor::new(&arena.paintable_rows()).rendered_text_edge_line(primary, end))
+ })
+}
+
+/// The caret position one grapheme right of (`forward`) or left of `offset` in the DOM text whose layout node is
+/// `primary`, where the grapheme boundary of the DOM text that way is `grapheme_boundary`, if `has_grapheme_boundary`.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_character_step(
+ host: &DocumentHost,
+ primary: NodeSlotId,
+ offset: usize,
+ downstream: bool,
+ forward: bool,
+ has_grapheme_boundary: bool,
+ grapheme_boundary: usize,
+) -> FfiInlineCaretPosition {
+ let args = (
+ primary,
+ offset,
+ downstream,
+ forward,
+ has_grapheme_boundary.then_some(grapheme_boundary),
+ );
+ read_arena(host, node_read(), args, |arena, args| {
+ let (text, offset, downstream, forward, grapheme_boundary) = args;
+ FfiInlineCaretPosition::of(
+ InlineCursor::new(&arena.paintable_rows()).position_after_character_step(
+ text,
+ offset,
+ downstream,
+ forward,
+ grapheme_boundary,
+ ),
+ )
+ })
+}
+
fn has_rendered_text_matching(
arena: &impl PaintableRowsRead,
node_slots: &[NodeSlotId],
diff --git a/Libraries/LibWeb/Selection/CaretNavigation.cpp b/Libraries/LibWeb/Selection/CaretNavigation.cpp
index 4b16fb65cef..98cc8891107 100644
--- a/Libraries/LibWeb/Selection/CaretNavigation.cpp
+++ b/Libraries/LibWeb/Selection/CaretNavigation.cpp
@@ -21,7 +21,6 @@
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Selection/CaretNavigation.h>
-#include <LibWeb/VisualLines.h>
namespace Web::Selection {
@@ -45,11 +44,8 @@ static WordSegmentKind word_segment_kind(Utf16View const& segment)
static bool text_node_has_rendered_text(DOM::Text const& text)
{
Layout::ForcedReadScope read { text.document() };
- for (auto const& line : collect_visual_lines(read, text)) {
- if (line.has_fragments)
- return true;
- }
- return false;
+ auto const* layout_node = text.unsafe_layout_node(read);
+ return layout_node && Layout::RustFFI::render_state_text_has_rendered_text(layout_node->document_host(), Layout::Node::slot_id(layout_node));
}
// A <br> that renders an empty line hosts a caret position on its parent, at its child index. This covers a leading
@@ -107,27 +103,32 @@ static bool is_empty_inline_block(DOM::Node& node)
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)
+// The line the rendered text of `text` starts on, or ends on, where that line holds rendered text of it.
+static Optional<Layout::RustFFI::FfiInlineLine> rendered_text_edge_line(DOM::Text const& text, bool end)
{
- Layout::ForcedReadScope read { before.document() };
- auto before_lines = collect_visual_lines(read, before);
- auto after_lines = collect_visual_lines(read, after);
- if (before_lines.is_empty() || !before_lines.last().has_fragments || after_lines.is_empty() || !after_lines.first().has_fragments)
- return false;
+ Layout::ForcedReadScope read { text.document() };
+ auto const* layout_node = text.unsafe_layout_node(read);
+ if (!layout_node)
+ return {};
+ auto line = Layout::RustFFI::render_state_text_rendered_edge_line(layout_node->document_host(), Layout::Node::slot_id(layout_node), end);
+ if (line.root.index == Compositing::RustFFI::INVALID_NODE_SLOT_INDEX)
+ return {};
+ return line;
+}
- return before_lines.last().owner_paintable == after_lines.first().owner_paintable
- && before_lines.last().line_index == after_lines.first().line_index;
+static bool boundary_visual_lines_share_line(DOM::Text const& before, DOM::Text const& after)
+{
+ auto before_line = rendered_text_edge_line(before, true);
+ auto after_line = rendered_text_edge_line(after, false);
+ return before_line.has_value() && after_line.has_value()
+ && before_line->root.index == after_line->root.index && before_line->index == after_line->index;
}
static bool boundary_visual_lines_share_inline_context(DOM::Text const& before, DOM::Text const& after)
{
- Layout::ForcedReadScope read { before.document() };
- auto before_lines = collect_visual_lines(read, before);
- auto after_lines = collect_visual_lines(read, after);
- if (before_lines.is_empty() || !before_lines.last().has_fragments || after_lines.is_empty() || !after_lines.first().has_fragments)
- return false;
-
- return before_lines.last().owner_paintable == after_lines.first().owner_paintable;
+ auto before_line = rendered_text_edge_line(before, true);
+ auto after_line = rendered_text_edge_line(after, false);
+ return before_line.has_value() && after_line.has_value() && before_line->root.index == after_line->root.index;
}
// INTEROP: A forward vertical extension that ends at the start of text in another block ends at the equivalent boundary
@@ -205,6 +206,34 @@ static Optional<CaretLocation> caret_location_of(DOM::Document& document, Layout
VERIFY_NOT_REACHED();
}
+// The caret location at the start of the first line of `text`, or at the end of its last line.
+static Optional<CaretLocation> text_edge_location(DOM::Text& text, bool end)
+{
+ Layout::ForcedReadScope read { text.document() };
+ text.document().update_layout_if_needed_for_node(text, DOM::UpdateLayoutReason::CursorLineNavigation);
+ auto const* layout_node = text.unsafe_layout_node(read);
+ if (!layout_node)
+ return {};
+ return caret_location_of(text.document(), read, Layout::RustFFI::render_state_text_edge(layout_node->document_host(), Layout::Node::slot_id(layout_node), end));
+}
+
+Optional<CaretLocation> location_after_character_step(DOM::Text& text, size_t offset, TextAffinity affinity, SelectionDirection direction)
+{
+ Layout::ForcedReadScope read { text.document() };
+ text.document().update_layout_if_needed_for_node(text, DOM::UpdateLayoutReason::CursorLineNavigation);
+ auto forward = direction == SelectionDirection::Forward;
+ auto grapheme_boundary = forward ? text.grapheme_segmenter().next_boundary(offset) : text.grapheme_segmenter().previous_boundary(offset);
+ auto const* layout_node = text.unsafe_layout_node(read);
+ if (!layout_node) {
+ if (!grapheme_boundary.has_value())
+ return {};
+ return CaretLocation { text, *grapheme_boundary, TextAffinity::Downstream };
+ }
+ return caret_location_of(text.document(), read,
+ Layout::RustFFI::render_state_text_character_step(layout_node->document_host(), Layout::Node::slot_id(layout_node),
+ offset, affinity == TextAffinity::Downstream, forward, grapheme_boundary.has_value(), grapheme_boundary.value_or(0)));
+}
+
GC::Ptr<DOM::Node> CaretNavigator::adjacent_caret_host(DOM::Node& from, DOM::Node& editing_host, SelectionDirection direction)
{
auto* node = &from;
@@ -293,7 +322,6 @@ Optional<CaretLocation> CaretNavigator::move_to_adjacent_caret_host(CaretLocatio
return {};
size_t offset = 0;
- auto affinity = TextAffinity::Downstream;
if (is_atomic_inline_caret_host(*target) && target->parent()) {
auto target_is_in_origin_parent = target->parent() == origin.parent();
@@ -315,17 +343,10 @@ Optional<CaretLocation> CaretNavigator::move_to_adjacent_caret_host(CaretLocatio
target = target->parent();
}
- if (auto* text = as_if<DOM::Text>(*target)) {
- auto position = direction == SelectionDirection::Forward
- ? cursor_position_at_visual_start(*text)
- : cursor_position_at_visual_end(*text);
- if (!position.has_value())
- return {};
- offset = position->offset;
- affinity = position->affinity;
- }
+ if (auto* text = as_if<DOM::Text>(*target))
+ return text_edge_location(*text, direction == SelectionDirection::Backward);
- return CaretLocation { *target, offset, affinity };
+ return CaretLocation { *target, offset, TextAffinity::Downstream };
}
CaretLocation CaretNavigator::canonical_location_for_editing(CaretLocation const& location)
@@ -486,9 +507,8 @@ Optional<CaretLocation> CaretNavigator::location_before_atomic_inline(DOM::Node&
return {};
auto previous = adjacent_caret_host(atomic_inline, *editing_host, SelectionDirection::Backward);
if (auto* previous_text = as_if<DOM::Text>(previous.ptr())) {
- auto position = cursor_position_at_visual_end(*previous_text);
- if (position.has_value())
- return CaretLocation { *previous_text, position->offset, position->affinity };
+ if (auto position = text_edge_location(*previous_text, true); position.has_value())
+ return position;
}
return CaretLocation { *atomic_inline.parent(), atomic_inline.index(), TextAffinity::Downstream };
}
@@ -617,14 +637,8 @@ Optional<CaretLocation> CaretNavigator::move_to_editing_host_boundary(CaretLocat
target = next_target;
}
- if (auto* text = as_if<DOM::Text>(*target)) {
- auto position = direction == SelectionDirection::Forward
- ? cursor_position_at_visual_end(*text)
- : cursor_position_at_visual_start(*text);
- if (!position.has_value())
- return {};
- return CaretLocation { *text, position->offset, position->affinity };
- }
+ if (auto* text = as_if<DOM::Text>(*target))
+ return text_edge_location(*text, direction == SelectionDirection::Forward);
if (is_atomic_inline_caret_host(*target) && target->parent())
return CaretLocation { *target->parent(), target->index() + (direction == SelectionDirection::Forward ? 1 : 0), TextAffinity::Downstream };
@@ -639,9 +653,7 @@ Optional<CaretLocation> CaretNavigator::first_position_on_another_line(CaretLoca
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 };
+ candidate = text_edge_location(*text, direction == SelectionDirection::Backward);
} else if (is_empty_inline_block(*host)) {
candidate = CaretLocation { *host, 0 };
} else if (is_atomic_inline_caret_host(*host)) {
@@ -822,11 +834,8 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Sele
if (granularity == SelectionGranularity::Character) {
if (text) {
- auto position = direction == SelectionDirection::Forward
- ? compute_cursor_position_on_next_character(*text, location.offset, location.affinity)
- : compute_cursor_position_on_previous_character(*text, location.offset, location.affinity);
- if (position.has_value())
- return CaretLocation { *text, position->offset, position->affinity };
+ if (auto position = location_after_character_step(*text, location.offset, location.affinity, direction); position.has_value())
+ return position;
}
auto adjacent = move_to_adjacent_caret_host(location, direction);
if (!adjacent.has_value())
@@ -838,8 +847,8 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Sele
&& location.node->child_at_index(location.offset) == adjacent_text) {
auto* previous = location.node->child_at_index(location.offset - 1);
if (previous && is_atomic_inline_caret_host(*previous)) {
- if (auto position = compute_cursor_position_on_next_character(*adjacent_text, adjacent->offset, adjacent->affinity); position.has_value())
- return CaretLocation { *adjacent_text, position->offset, position->affinity };
+ if (auto position = location_after_character_step(*adjacent_text, adjacent->offset, adjacent->affinity, direction); position.has_value())
+ return position;
}
}
if (text && adjacent_text) {
@@ -847,11 +856,8 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Sele
? boundary_visual_lines_share_line(*text, *adjacent_text)
: boundary_visual_lines_share_line(*adjacent_text, *text);
if (shares_line) {
- auto position = direction == SelectionDirection::Forward
- ? compute_cursor_position_on_next_character(*adjacent_text, adjacent->offset, adjacent->affinity)
- : compute_cursor_position_on_previous_character(*adjacent_text, adjacent->offset, adjacent->affinity);
- if (position.has_value())
- return CaretLocation { *adjacent_text, position->offset, position->affinity };
+ if (auto position = location_after_character_step(*adjacent_text, adjacent->offset, adjacent->affinity, direction); position.has_value())
+ return position;
}
}
return adjacent;
diff --git a/Libraries/LibWeb/Selection/CaretNavigation.h b/Libraries/LibWeb/Selection/CaretNavigation.h
index b7e609399aa..d77a387c317 100644
--- a/Libraries/LibWeb/Selection/CaretNavigation.h
+++ b/Libraries/LibWeb/Selection/CaretNavigation.h
@@ -51,6 +51,10 @@ struct CaretLocation {
TextAffinity affinity { TextAffinity::Downstream };
};
+// One grapheme step in the text. At a soft wrap, the offset has a caret position at the end of the earlier line and at
+// the start of the next, and a step visits both.
+Optional<CaretLocation> location_after_character_step(DOM::Text&, size_t offset, TextAffinity, SelectionDirection);
+
// Resolves visible caret positions without mutating Selection. Editing operations use this service to share the same
// model of rendered text, atomic inline content, empty lines, and editing-host boundaries as keyboard navigation.
class CaretNavigator {
diff --git a/Libraries/LibWeb/VisualLines.cpp b/Libraries/LibWeb/VisualLines.cpp
deleted file mode 100644
index 325f38d3d85..00000000000
--- a/Libraries/LibWeb/VisualLines.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Utf16View.h>
-#include <LibUnicode/Segmenter.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Text.h>
-#include <LibWeb/Layout/TextNode.h>
-#include <LibWeb/VisualLines.h>
-
-namespace Web {
-
-Vector<VisualLine> collect_visual_lines(Layout::BegunRead const& read, DOM::Text const& dom_node)
-{
- Vector<VisualLine> lines;
-
- // NB: Unlike the callers below, this one is also reached from serialization and caret queries
- // that do not update layout first, so it has to read whatever layout it finds.
- auto const* layout_node = as_if<Layout::TextNode>(dom_node.unsafe_layout_node(read));
- if (!layout_node)
- return lines;
-
- Layout::RustFFI::render_state_text_visual_lines(layout_node->document_host(), Layout::Node::slot_id(layout_node), &lines,
- [](void* context, Layout::RustFFI::FfiVisualLine line) {
- static_cast<Vector<VisualLine>*>(context)->append({
- .start_offset = line.start_offset,
- .end_offset = line.end_offset,
- .end_offset_with_trailing_whitespace = line.end_offset_with_trailing_whitespace,
- .has_fragments = line.has_fragments,
- .owner_paintable = line.owner_paintable,
- .line_index = line.line_index,
- });
- });
- return lines;
-}
-
-static Vector<VisualLine> visual_lines_with_up_to_date_layout(DOM::Text const& dom_node)
-{
- Layout::ForcedReadScope read { dom_node.document() };
- const_cast<DOM::Document&>(dom_node.document()).update_layout_if_needed_for_node(dom_node, DOM::UpdateLayoutReason::CursorLineNavigation);
- return collect_visual_lines(read, dom_node);
-}
-
-// The affinity a cursor landing on `offset` within `lines[line_index]` needs in order to render on that line.
-static TextAffinity affinity_for_offset_on_line(Vector<VisualLine> const& lines, size_t line_index, size_t offset)
-{
- if (line_index + 1 < lines.size() && offset >= lines[line_index + 1].start_offset)
- return TextAffinity::Upstream;
- return TextAffinity::Downstream;
-}
-
-// Whether the offset sits at a soft wrap boundary with two visual caret positions (the end of one visual line and
-// the start of the next).
-static bool offset_is_soft_wrap_boundary(Vector<VisualLine> const& lines, size_t offset)
-{
- for (size_t i = 0; i + 1 < lines.size(); ++i) {
- if (lines[i].end_offset_with_trailing_whitespace == offset && lines[i + 1].start_offset == offset)
- return true;
- }
- return false;
-}
-
-// Moving right into whitespace hanging at a soft wrap point, or onto a soft wrap boundary, keeps the cursor on the
-// earlier line.
-static TextAffinity affinity_for_moving_right(Vector<VisualLine> const& lines, size_t new_offset)
-{
- for (size_t i = 0; i < lines.size(); ++i) {
- if (new_offset > lines[i].end_offset && new_offset <= lines[i].end_offset_with_trailing_whitespace)
- return TextAffinity::Upstream;
- if (new_offset == lines[i].end_offset_with_trailing_whitespace
- && i + 1 < lines.size() && lines[i + 1].start_offset == new_offset)
- return TextAffinity::Upstream;
- }
- return TextAffinity::Downstream;
-}
-
-Optional<CursorLinePosition> compute_cursor_position_on_next_character(DOM::Text const& dom_node, size_t current_offset, TextAffinity affinity)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
-
- // Step from the end of the earlier line to the start of the next line without advancing the offset.
- if (affinity == TextAffinity::Upstream && offset_is_soft_wrap_boundary(lines, current_offset))
- return CursorLinePosition { current_offset, TextAffinity::Downstream };
-
- auto next_offset = dom_node.grapheme_segmenter().next_boundary(current_offset);
- if (!next_offset.has_value())
- return {};
- return CursorLinePosition { *next_offset, affinity_for_moving_right(lines, *next_offset) };
-}
-
-Optional<CursorLinePosition> compute_cursor_position_on_previous_character(DOM::Text const& dom_node, size_t current_offset, TextAffinity affinity)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
-
- // Step from the start of the later line back to the end of the earlier line without moving the offset.
- if (affinity == TextAffinity::Downstream && offset_is_soft_wrap_boundary(lines, current_offset))
- return CursorLinePosition { current_offset, TextAffinity::Upstream };
-
- auto previous_offset = dom_node.grapheme_segmenter().previous_boundary(current_offset);
- if (!previous_offset.has_value())
- return {};
- return CursorLinePosition { *previous_offset, TextAffinity::Downstream };
-}
-
-Optional<CursorLinePosition> cursor_position_at_visual_start(DOM::Text const& dom_node)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (lines.is_empty())
- return {};
- auto offset = lines.first().start_offset;
- return CursorLinePosition { offset, affinity_for_offset_on_line(lines, 0, offset) };
-}
-
-Optional<CursorLinePosition> cursor_position_at_visual_end(DOM::Text const& dom_node)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (lines.is_empty())
- return {};
- auto offset = lines.last().end_offset;
- return CursorLinePosition { offset, affinity_for_offset_on_line(lines, lines.size() - 1, offset) };
-}
-
-size_t find_line_start(Utf16View const& view, size_t offset)
-{
- while (offset != 0 && view.code_unit_at(offset - 1) != '\n')
- --offset;
- return offset;
-}
-
-size_t find_line_end(Utf16View const& view, size_t offset)
-{
- auto length = view.length_in_code_units();
- while (offset < length && view.code_unit_at(offset) != '\n')
- ++offset;
- return offset;
-}
-
-}
diff --git a/Libraries/LibWeb/VisualLines.h b/Libraries/LibWeb/VisualLines.h
deleted file mode 100644
index 2b5084f2076..00000000000
--- a/Libraries/LibWeb/VisualLines.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Forward.h>
-#include <AK/Optional.h>
-#include <AK/Vector.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/TextAffinity.h>
-
-namespace Web {
-
-// A visual line of a text node: a run of text that is rendered on a single line box, delimited by soft wraps and/or
-// preserved newline characters. Lines with no rendered text (such as the line between two consecutive newlines) have
-// no fragments. Whitespace hanging at a soft wrap point is part of the line it trails, between end_offset and
-// end_offset_with_trailing_whitespace.
-struct VisualLine {
- size_t start_offset { 0 };
- size_t end_offset { 0 };
- size_t end_offset_with_trailing_whitespace { 0 };
- bool has_fragments { false };
- u32 owner_paintable { 0 };
- u32 line_index { 0 };
-};
-
-// NB: Layout must be up to date when calling this.
-Vector<VisualLine> collect_visual_lines(Layout::BegunRead const&, DOM::Text const&);
-
-// A cursor position produced by caret navigation: the affinity determines which line the offset renders on when the
-// offset sits exactly at a soft wrap boundary.
-struct CursorLinePosition {
- size_t offset { 0 };
- TextAffinity affinity { TextAffinity::Downstream };
-};
-
-// One cursor step right or left. At a soft wrap boundary, the same offset has two visual positions (the end of the
-// earlier line and the start of the next); stepping visits both before moving to the adjacent grapheme.
-Optional<CursorLinePosition> compute_cursor_position_on_next_character(DOM::Text const&, size_t current_offset, TextAffinity);
-Optional<CursorLinePosition> compute_cursor_position_on_previous_character(DOM::Text const&, size_t current_offset, TextAffinity);
-
-size_t find_line_start(Utf16View const&, size_t offset);
-size_t find_line_end(Utf16View const&, size_t offset);
-
-// 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
-// coordinate). All return nothing for text with no rendered lines.
-Optional<CursorLinePosition> cursor_position_at_visual_start(DOM::Text const&);
-Optional<CursorLinePosition> cursor_position_at_visual_end(DOM::Text const&);
-
-}