Skip to content

Truly independent web browser

LibWeb: Navigate text controls by InlineCursor lines

Aliaksandr Kalenik8f21a421fb4e
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 0979a145e5a..db32cb8aa1d 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -921,6 +921,7 @@ class IntersectionObserverEntry;
namespace Web::Layout::RustFFI {
struct BegunRead;
+enum class FfiTextCaretMovement : u8;
}
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
index e7d72ba83d3..5aa25196fa4 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
@@ -841,6 +841,7 @@ void FormAssociatedTextControlElement::relevant_value_was_changed()
if (static_cast<DOM::Element&>(element).dir() == DOM::Element::Dir::Auto)
CSS::Invalidation::invalidate_style_after_directionality_change(element);
+ m_line_move_inline_coordinate = {};
auto the_relevant_value = relevant_value();
auto relevant_value_length = the_relevant_value.length_in_code_units();
@@ -1270,6 +1271,7 @@ void FormAssociatedTextControlElement::set_the_selection_range(Optional<WebIDL::
m_selection_start = new_selection_start;
m_selection_end = new_selection_end;
m_selection_end_affinity = TextAffinity::Downstream;
+ m_line_move_inline_coordinate = {};
// 4. If direction is not identical to either "backward" or "forward", or if the direction
// argument was not given, set direction to "none".
@@ -1477,6 +1479,8 @@ void FormAssociatedTextControlElement::collapse_selection_to_offset(size_t posit
void FormAssociatedTextControlElement::move_selection_end_to(size_t offset, TextAffinity affinity, CollapseSelection collapse)
{
+ if (m_selection_end != offset || m_selection_end_affinity != affinity || (collapse == CollapseSelection::Yes && m_selection_start != offset))
+ m_line_move_inline_coordinate = {};
if (collapse == CollapseSelection::Yes)
m_selection_start = offset;
m_selection_end = offset;
@@ -1618,24 +1622,38 @@ void FormAssociatedTextControlElement::move_cursor_to_end(CollapseSelection coll
selection_was_changed(SelectionSource::UI);
}
-void FormAssociatedTextControlElement::move_cursor_to_start_of_current_line(CollapseSelection collapse)
+void FormAssociatedTextControlElement::move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement movement, CollapseSelection collapse, CSSPixels page_distance)
{
- auto text_node = form_associated_element_to_text_node();
- if (!text_node)
+ auto text = form_associated_element_to_text_node();
+ if (!text)
+ return;
+ auto& document = text_control_to_html_element().document();
+ Layout::ForcedReadScope read { document };
+ document.update_layout_if_needed_for_node(*text, DOM::UpdateLayoutReason::CursorLineNavigation);
+ auto const* layout_node = text->layout_node(read);
+ if (!layout_node)
return;
- auto new_offset = find_visual_line_start(*text_node, m_selection_end, m_selection_end_affinity);
- move_selection_end_to(new_offset, TextAffinity::Downstream, collapse);
+ Layout::RustFFI::FfiTextCaretMove move;
+ Layout::RustFFI::render_state_text_caret_move(layout_node->document_host(), Layout::Node::slot_id(layout_node),
+ m_selection_end, m_selection_end_affinity == TextAffinity::Downstream, text->length(), movement,
+ { .has_value = m_line_move_inline_coordinate.has_value(), .value = m_line_move_inline_coordinate.value_or(0) },
+ page_distance, &move);
+ if (!move.found)
+ return;
+ move_selection_end_to(move.offset, move.downstream ? TextAffinity::Downstream : TextAffinity::Upstream, collapse);
+ if (move.inline_coordinate.has_value)
+ m_line_move_inline_coordinate = move.inline_coordinate.value;
selection_was_changed(SelectionSource::UI);
}
+void FormAssociatedTextControlElement::move_cursor_to_start_of_current_line(CollapseSelection collapse)
+{
+ move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement::LineStart, collapse);
+}
+
void FormAssociatedTextControlElement::move_cursor_to_end_of_current_line(CollapseSelection collapse)
{
- auto text_node = form_associated_element_to_text_node();
- if (!text_node)
- return;
- auto new_position = find_visual_line_end(*text_node, m_selection_end, m_selection_end_affinity);
- move_selection_end_to(new_position.offset, new_position.affinity, collapse);
- selection_was_changed(SelectionSource::UI);
+ move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement::LineEnd, collapse);
}
void FormAssociatedTextControlElement::move_cursor_to_start_of_paragraph(CollapseSelection collapse)
@@ -1666,10 +1684,7 @@ void FormAssociatedTextControlElement::move_cursor_to_end_of_paragraph(CollapseS
void FormAssociatedTextControlElement::move_cursor_by_page(bool forward, CollapseSelection collapse)
{
- auto text = form_associated_element_to_text_node();
auto& element = text_control_to_html_element();
- if (!text)
- return;
Layout::ForcedReadScope read { element.document() };
element.document().update_layout_if_needed_for_node(element, DOM::UpdateLayoutReason::CursorLineNavigation);
auto* layout = element.layout_node(read);
@@ -1683,30 +1698,12 @@ void FormAssociatedTextControlElement::move_cursor_by_page(bool forward, Collaps
#ifdef AK_OS_MACOS
distance = max(distance, page_height - 40);
#endif
- auto position = compute_cursor_position_by_page(*text, m_selection_end, m_selection_end_affinity, forward, max(distance, 1));
- if (!position.has_value())
- return;
- move_selection_end_to(position->offset, position->affinity, collapse);
- selection_was_changed(SelectionSource::UI);
+ move_cursor_on_lines(forward ? Layout::RustFFI::FfiTextCaretMovement::NextPage : Layout::RustFFI::FfiTextCaretMovement::PreviousPage, collapse, max(distance, 1));
}
void FormAssociatedTextControlElement::move_cursor_to_physical_line_boundary(bool left, CollapseSelection collapse)
{
- auto text = form_associated_element_to_text_node();
- if (!text)
- return;
- auto& document = text_control_to_html_element().document();
- Layout::ForcedReadScope read { document };
- document.update_layout_if_needed_for_node(*text, DOM::UpdateLayoutReason::CursorLineNavigation);
- auto position = document.caret_position_at_line_edge(read, *text, m_selection_end, m_selection_end_affinity,
- left ? Painting::CaretLineEdge::Left : Painting::CaretLineEdge::Right);
- if (!position.has_value())
- return;
- auto boundary = position->boundary_point();
- if (!boundary.has_value() || boundary->node != text)
- return;
- move_selection_end_to(boundary->offset, position->affinity, collapse);
- selection_was_changed(SelectionSource::UI);
+ move_cursor_on_lines(left ? Layout::RustFFI::FfiTextCaretMovement::LineLeft : Layout::RustFFI::FfiTextCaretMovement::LineRight, collapse);
}
void FormAssociatedTextControlElement::increment_cursor_position_offset(CollapseSelection collapse)
@@ -1781,30 +1778,12 @@ void FormAssociatedTextControlElement::decrement_cursor_position_to_previous_wor
void FormAssociatedTextControlElement::increment_cursor_position_to_next_line(CollapseSelection collapse)
{
- auto text_node = form_associated_element_to_text_node();
- if (!text_node)
- return;
-
- auto new_position = compute_cursor_position_on_next_line(*text_node, m_selection_end, m_selection_end_affinity);
- if (!new_position.has_value())
- return;
-
- move_selection_end_to(new_position->offset, new_position->affinity, collapse);
- selection_was_changed(SelectionSource::UI);
+ move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement::NextLine, collapse);
}
void FormAssociatedTextControlElement::decrement_cursor_position_to_previous_line(CollapseSelection collapse)
{
- auto text_node = form_associated_element_to_text_node();
- if (!text_node)
- return;
-
- auto new_position = compute_cursor_position_on_previous_line(*text_node, m_selection_end, m_selection_end_affinity);
- if (!new_position.has_value())
- return;
-
- move_selection_end_to(new_position->offset, new_position->affinity, collapse);
- selection_was_changed(SelectionSource::UI);
+ move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement::PreviousLine, collapse);
}
GC::Ptr<DOM::Position> FormAssociatedTextControlElement::cursor_position() const
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.h b/Libraries/LibWeb/HTML/FormAssociatedElement.h
index 5f99431682a..41a0739565d 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.h
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.h
@@ -20,6 +20,7 @@
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/XHR/FormDataEntry.h>
+#include <LibWebCommon/PixelUnits.h>
#include <LibWebCommon/WebIDL/Types.h>
namespace Web::HTML {
@@ -334,6 +335,7 @@ private:
void collapse_selection_to_offset(size_t, TextAffinity = TextAffinity::Downstream);
void move_selection_end_to(size_t offset, TextAffinity, CollapseSelection);
void move_cursor_by_page(bool forward, CollapseSelection);
+ void move_cursor_on_lines(Layout::RustFFI::FfiTextCaretMovement, CollapseSelection, CSSPixels page_distance = 0);
void scroll_cursor_into_view();
void reveal_cursor_after_edit();
void selection_was_changed(SelectionSource);
@@ -346,6 +348,10 @@ private:
// Disambiguates which visual line the selection end renders on when it sits at a soft wrap boundary.
TextAffinity m_selection_end_affinity { TextAffinity::Downstream };
+ // The inline coordinate that consecutive moves of the selection end to other lines keep, until the selection changes
+ // another way.
+ Optional<CSSPixels> m_line_move_inline_coordinate;
+
// https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event
bool m_has_scheduled_selectionchange_event { false };
diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
index 0b15d422792..fa185c68df3 100644
--- a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
@@ -69,6 +69,14 @@ pub(crate) struct CaretRect {
pub(crate) node: NodeSlotId,
}
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum LineEdge {
+ Start,
+ End,
+ Left,
+ Right,
+}
+
/// A line of a text node: the DOM offsets it renders, with the whitespace hanging at its soft wrap between `end_offset`
/// and `end_offset_with_trailing_whitespace`. A line that a preserved newline ends with nothing on it has no fragments.
pub(crate) struct TextLine {
@@ -337,6 +345,179 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
})
}
+ /// The next line after `line` in its line root, or the previous one, that holds a caret position.
+ pub(crate) fn adjacent_line(&self, line: InlineLine, forward: bool) -> Option<InlineLine> {
+ let side = self.arena.committed_side_data(line.root);
+ let mut index = line.index as usize;
+ loop {
+ index = if forward { index + 1 } else { index.checked_sub(1)? };
+ let record = side.lines().get(index)?;
+ if (record.fragment_count > 0 && !record.has_block_level_box) || record.forced_break.is_some() {
+ return Some(InlineLine {
+ root: line.root,
+ index: index as u32,
+ });
+ }
+ }
+ }
+
+ fn line_is_horizontal(&self, line: InlineLine) -> bool {
+ let side = self.arena.committed_side_data(line.root);
+ side.lines()
+ .get(line.index as usize)
+ .is_none_or(|record| record.writing_mode == writing_mode::HORIZONTAL_TB)
+ }
+
+ /// The middle of `line` along the block axis.
+ pub(crate) fn line_block_coordinate(&self, line: InlineLine) -> CssPixels {
+ let side = self.arena.committed_side_data(line.root);
+ let Some(record) = side.lines().get(line.index as usize) else {
+ return CssPixels::default();
+ };
+ let rect = self.line_rect(line, record);
+ let center = rect.center();
+ if record.writing_mode == writing_mode::HORIZONTAL_TB {
+ center.y
+ } else {
+ center.x
+ }
+ }
+
+ /// The inline coordinate of the caret at `position` on `line`, which a move to another line keeps.
+ pub(crate) fn caret_inline_coordinate(&self, line: InlineLine, position: CaretPosition) -> Option<CssPixels> {
+ let caret = self.caret_rect(position)?;
+ let root = paintable_geometry::absolute_line_root_position(self.arena, line.root, line.index as usize);
+ let (coordinate, root_coordinate) = if self.line_is_horizontal(line) {
+ (caret.rect.x, root.x)
+ } else {
+ (caret.rect.y, root.y)
+ };
+ // INTEROP: Vertical navigation takes the pixel-rounded leading edge of a one-pixel caret centered on the text
+ // boundary, which floors the coordinate in the line root.
+ Some((coordinate - root_coordinate).floor() + root_coordinate)
+ }
+
+ /// The fragments of `line` that `accepts` takes, in line order.
+ fn fragments_on_line<'b>(
+ &self,
+ side: &'b crate::painting::paintable_data::CommittedSideData,
+ line: InlineLine,
+ accepts: impl Fn(&FragmentRecord) -> bool,
+ ) -> impl Iterator<Item = &'b FragmentRecord> {
+ let range = side.lines().get(line.index as usize).map_or(0..0, |record| {
+ record.first_fragment as usize..(record.first_fragment + record.fragment_count) as usize
+ });
+ side.fragments()[range].iter().filter(move |fragment| accepts(fragment))
+ }
+
+ /// The position in front of the <br> or preserved newline that ends `line`.
+ fn position_before_forced_break(&self, line: InlineLine) -> Option<CaretPosition> {
+ let side = self.arena.committed_side_data(line.root);
+ let position = side.lines().get(line.index as usize)?.forced_break?;
+ if self.arena.node_kind_if_live(position.node) == Some(NodeKind::BreakNode) {
+ return Some(CaretPosition::BeforeForcedBreak { node: position.node });
+ }
+ Some(CaretPosition::Text {
+ text: position.node,
+ offset: self.arena.dom_offset_for_rendered_text_offset(
+ position.node,
+ position.rendered_offset as usize,
+ RenderedTextBoundary::Start,
+ ),
+ downstream: true,
+ })
+ }
+
+ /// The text position at `offset` in `fragment`, leaning to the line of the fragment.
+ fn text_position_in_fragment(&self, fragment: &FragmentRecord, offset: usize) -> CaretPosition {
+ let downstream = self
+ .line_of(fragment.layout_node, offset, true)
+ .is_none_or(|position| position.line.index == fragment.line_index);
+ CaretPosition::Text {
+ text: fragment.layout_node,
+ offset,
+ downstream,
+ }
+ }
+
+ /// 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(
+ &self,
+ line: InlineLine,
+ x: CssPixels,
+ accepts: impl Fn(&FragmentRecord) -> bool,
+ ) -> Option<CaretPosition> {
+ let arena = self.arena;
+ let side = arena.committed_side_data(line.root);
+ let horizontal = self.line_is_horizontal(line);
+ let 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) {
+ let rect = text_fragment::absolute_rect(arena, fragment);
+ if chosen.is_none() || inline_start(rect) <= x {
+ chosen = Some((fragment, rect));
+ }
+ }
+ let Some((fragment, rect)) = chosen else {
+ return self.position_before_forced_break(line);
+ };
+ let mut point = rect.center();
+ if horizontal {
+ point.x = rect.x.max(x);
+ } else {
+ point.y = rect.y.max(x);
+ }
+ let offset = text_fragment::index_in_node_for_point(arena, fragment, point);
+ Some(self.text_position_in_fragment(fragment, offset))
+ }
+
+ /// 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.
+ pub(crate) fn line_edge(
+ &self,
+ line: InlineLine,
+ edge: LineEdge,
+ accepts: impl Fn(&FragmentRecord) -> bool,
+ ) -> Option<CaretPosition> {
+ let arena = self.arena;
+ let side = arena.committed_side_data(line.root);
+ let fragments = self.fragments_on_line(&side, line, accepts);
+ 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::Left => fragments.min_by_key(|fragment| {
+ let rect = rect(fragment);
+ if self.line_is_horizontal(line) { 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()
+ }
+ }),
+ };
+ 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) {
+ (LineEdge::Left | LineEdge::Right, Some((offset, at_cluster_end))) => {
+ return Some(CaretPosition::Text {
+ text: fragment.layout_node,
+ offset,
+ downstream: !at_cluster_end,
+ });
+ }
+ (LineEdge::End, _) => fragment.dom_end_offset_with_trailing_whitespace,
+ _ => fragment.dom_start_offset_in_node,
+ };
+ Some(self.text_position_in_fragment(fragment, offset))
+ }
+
/// 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 8bae0eec764..b9fe4abbbb8 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -8,6 +8,7 @@ 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::svg_formatting_context;
use crate::layout::used_values::FfiCssPixelPoint;
use crate::layout::used_values::FfiCssPixelRect;
@@ -915,75 +916,173 @@ pub extern "C" fn render_state_text_has_rendered_text_after(
}
#[repr(C)]
+#[derive(Default)]
pub struct FfiOptionalCssPixels {
pub has_value: bool,
pub value: CssPixels,
}
+impl FfiOptionalCssPixels {
+ fn of(value: Option<CssPixels>) -> Self {
+ Self {
+ has_value: value.is_some(),
+ value: value.unwrap_or_default(),
+ }
+ }
+}
+
+/// 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.
#[unsafe(no_mangle)]
-pub extern "C" fn render_state_visual_line_caret_inline_coordinate(
+pub extern "C" fn render_state_text_caret_inline_coordinate(
host: &DocumentHost,
- owner_paintable: u32,
- line_index: u32,
primary: NodeSlotId,
offset: usize,
+ downstream: bool,
out: &mut FfiOptionalCssPixels,
) {
- *out = {
- read_arena(
- host,
- node_read(),
- (owner_paintable, line_index, primary, offset),
- |arena, (owner_paintable, line_index, primary, offset)| {
- let paintable_rows = arena.paintable_rows();
- let fragments = arena.text_fragments(primary);
- let node_slots = fragments.as_slice();
- let coordinate = crate::painting::visual_lines::caret_inline_coordinate(
- &paintable_rows,
- owner_paintable,
- line_index,
- node_slots,
- offset,
- );
- match coordinate {
- Some(value) => FfiOptionalCssPixels { has_value: true, value },
- None => FfiOptionalCssPixels {
- has_value: false,
- value: CssPixels::from_raw(0),
- },
- }
- },
- )
- };
+ *out = read_arena(
+ host,
+ node_read(),
+ (primary, offset, downstream),
+ |arena, (text, offset, downstream)| {
+ let rows = arena.paintable_rows();
+ let cursor = InlineCursor::new(&rows);
+ let position = CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ };
+ 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)))
+ },
+ );
+}
+
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[expect(dead_code, reason = "C++ constructs the variants")]
+pub enum FfiTextCaretMovement {
+ NextLine,
+ PreviousLine,
+ NextPage,
+ PreviousPage,
+ LineStart,
+ LineEnd,
+ LineLeft,
+ LineRight,
}
+#[repr(C)]
+#[derive(Default)]
+pub struct FfiTextCaretMove {
+ pub found: bool,
+ pub offset: usize,
+ pub downstream: bool,
+ /// For a move to another line, the inline coordinate it kept, for the next such move to keep.
+ pub inline_coordinate: FfiOptionalCssPixels,
+}
+
+/// Moves the caret at `offset` in the DOM text (`text_length` long) whose layout node is `primary`: to an edge of its
+/// line, or to the position nearest `inline_coordinate` (or else the caret's own) on the next or previous line, or on
+/// the farthest line no more than `page_distance` away. A move past the last or first line goes to the end or start of
+/// the text.
#[unsafe(no_mangle)]
-pub extern "C" fn render_state_visual_line_offset_closest_to_inline_coordinate(
+#[allow(clippy::too_many_arguments)]
+pub extern "C" fn render_state_text_caret_move(
host: &DocumentHost,
- owner_paintable: u32,
- line_index: u32,
primary: NodeSlotId,
- inline_coordinate: CssPixels,
- fallback_offset: usize,
-) -> usize {
- read_arena(
- host,
- node_read(),
- (owner_paintable, line_index, primary, inline_coordinate, fallback_offset),
- |arena, (owner_paintable, line_index, primary, inline_coordinate, fallback_offset)| {
- let paintable_rows = arena.paintable_rows();
- let fragments = arena.text_fragments(primary);
- let node_slots = fragments.as_slice();
- crate::painting::visual_lines::offset_closest_to_inline_coordinate(
- &paintable_rows,
- owner_paintable,
- line_index,
- node_slots,
- inline_coordinate,
- )
- .unwrap_or(fallback_offset)
- },
- )
+ offset: usize,
+ downstream: bool,
+ text_length: usize,
+ movement: FfiTextCaretMovement,
+ inline_coordinate: FfiOptionalCssPixels,
+ page_distance: CssPixels,
+ out: &mut FfiTextCaretMove,
+) {
+ let args = (
+ primary,
+ offset,
+ downstream,
+ text_length,
+ movement,
+ inline_coordinate,
+ page_distance,
+ );
+ *out = read_arena(host, node_read(), args, |arena, args| {
+ use FfiTextCaretMovement::*;
+ let (text, offset, downstream, text_length, movement, inline_coordinate, page_distance) = args;
+ let rows = arena.paintable_rows();
+ let cursor = InlineCursor::new(&rows);
+ let fragments = arena.text_fragments(text);
+ let in_text = |node: &NodeSlotId| fragments.as_slice().contains(node);
+ let moved = |position, inline_coordinate| match position {
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ }) if in_text(&text) => FfiTextCaretMove {
+ found: true,
+ offset,
+ downstream,
+ inline_coordinate: FfiOptionalCssPixels::of(inline_coordinate),
+ },
+ _ => FfiTextCaretMove::default(),
+ };
+ let mut position = CaretPosition::Text {
+ text,
+ offset,
+ downstream,
+ };
+ let Some(start) = cursor.line_of(text, offset, downstream) else {
+ return FfiTextCaretMove::default();
+ };
+ let accepts = |fragment: &FragmentRecord| in_text(&fragment.layout_node);
+ let edge = |edge| moved(cursor.line_edge(start.line, edge, accepts), None);
+ let forward = match movement {
+ LineStart => return edge(LineEdge::Start),
+ LineEnd => return edge(LineEdge::End),
+ LineLeft => return edge(LineEdge::Left),
+ LineRight => return edge(LineEdge::Right),
+ NextLine | NextPage => true,
+ PreviousLine | PreviousPage => false,
+ };
+ let page_distance = matches!(movement, NextPage | PreviousPage).then_some(page_distance);
+ let goal = if inline_coordinate.has_value {
+ inline_coordinate.value
+ } else if let Some(coordinate) = cursor.caret_inline_coordinate(start.line, position) {
+ coordinate
+ } else {
+ return FfiTextCaretMove::default();
+ };
+ let start_coordinate = cursor.line_block_coordinate(start.line);
+ let mut line = start.line;
+ while let Some(next) = cursor.adjacent_line(line, forward) {
+ let distance = cursor.line_block_coordinate(next) - start_coordinate;
+ if page_distance.is_some_and(|page_distance| distance.max(-distance) > page_distance) {
+ return moved(Some(position), Some(goal));
+ }
+ let Some(position_on_next) = cursor.position_at_inline_coordinate(next, goal, accepts) else {
+ return moved(Some(position), Some(goal));
+ };
+ position = position_on_next;
+ line = next;
+ if page_distance.is_none() {
+ return moved(Some(position), Some(goal));
+ }
+ }
+ let offset = if forward { text_length } else { 0 };
+ moved(
+ Some(CaretPosition::Text {
+ text,
+ offset,
+ downstream: true,
+ }),
+ Some(goal),
+ )
+ });
}
/// # Safety
diff --git a/Libraries/LibWeb/Rust/src/painting/mod.rs b/Libraries/LibWeb/Rust/src/painting/mod.rs
index 22853141747..3fec1324955 100644
--- a/Libraries/LibWeb/Rust/src/painting/mod.rs
+++ b/Libraries/LibWeb/Rust/src/painting/mod.rs
@@ -53,6 +53,5 @@ pub mod text_fragment;
pub mod viewport_mapping;
pub mod visual_animation_builder;
pub mod visual_context;
-pub(crate) mod visual_lines;
pub use libcompositing_rust::{filter_bytes, force_dark, visual_animation};
diff --git a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
index 2b02ed6ee83..6677a3ef0fe 100644
--- a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
+++ b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
@@ -80,10 +80,6 @@ pub(crate) fn is_horizontal(fragment: &FragmentRecord) -> bool {
fragment.writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB
}
-pub(crate) fn fragment_is_horizontal(fragment: &FragmentRecord) -> bool {
- is_horizontal(fragment)
-}
-
fn primary_size(rect: CssPixelRect, horizontal: bool) -> CssPixels {
if horizontal { rect.width } else { rect.height }
}
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs b/Libraries/LibWeb/Rust/src/painting/visual_lines.rs
deleted file mode 100644
index 26bf2e9ac68..00000000000
--- a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use crate::css::css_pixels::CssPixels;
-use crate::layout::node_data::NodeSlotId;
-use crate::painting::paint_read::PaintRead;
-use crate::painting::text_fragment;
-
-fn fragments_of_line(
- layout_arena: &impl PaintRead,
- owner_paintable: u32,
- line_index: u32,
- node_slots: &[NodeSlotId],
-) -> Vec<(NodeSlotId, u32)> {
- let Some(block) = node_slots
- .iter()
- .filter_map(|&node| text_fragment::containing_block_paintable_of_node(layout_arena, node))
- .find(|block| block.index == owner_paintable)
- else {
- return Vec::new();
- };
- let side = layout_arena.committed_side_data(block);
- let Some(line) = side.lines().get(line_index as usize) else {
- return Vec::new();
- };
- (line.first_fragment..line.first_fragment + line.fragment_count)
- .filter(|&index| node_slots.contains(&side.fragments()[index as usize].layout_node))
- .map(|index| (block, index))
- .collect()
-}
-
-pub(crate) fn caret_inline_coordinate(
- layout_arena: &impl PaintRead,
- owner_paintable: u32,
- line_index: u32,
- node_slots: &[NodeSlotId],
- offset: usize,
-) -> Option<CssPixels> {
- let fragments = fragments_of_line(layout_arena, owner_paintable, line_index, node_slots);
- let mut chosen = *fragments.first()?;
- for &(block, index) in &fragments {
- let side = layout_arena.committed_side_data(block);
- let fragment = &side.fragments()[index as usize];
- let dom_start = fragment.dom_start_offset_in_node;
- let dom_end_with_trailing_whitespace = fragment.dom_end_offset_with_trailing_whitespace;
- if offset >= dom_start && offset <= dom_end_with_trailing_whitespace {
- chosen = (block, index);
- break;
- }
- if dom_start <= offset {
- chosen = (block, index);
- }
- }
- let (block, index) = chosen;
- let side = layout_arena.committed_side_data(block);
- let fragment = &side.fragments()[index as usize];
- let dom_start = fragment.dom_start_offset_in_node;
- let dom_end_with_trailing_whitespace = fragment.dom_end_offset_with_trailing_whitespace;
- let clamped_offset = offset.clamp(dom_start, dom_end_with_trailing_whitespace);
- let rect = text_fragment::range_rect(
- layout_arena,
- fragment,
- crate::painting::paintable_data::SELECTION_STATE_START_AND_END,
- clamped_offset,
- clamped_offset,
- );
- let block_position = crate::painting::paintable_geometry::absolute_line_root_position(
- layout_arena,
- block,
- fragment.line_index as usize,
- );
- let (coordinate, block_coordinate) = if text_fragment::fragment_is_horizontal(fragment) {
- (rect.x, block_position.x)
- } else {
- (rect.y, block_position.y)
- };
- // INTEROP: Chromium uses the pixel-rounded leading edge of a one-pixel caret centered on the text boundary
- // for vertical navigation. Rounding after subtracting half a pixel floors the local text coordinate.
- Some((coordinate - block_coordinate).floor() + block_coordinate)
-}
-
-pub(crate) fn offset_closest_to_inline_coordinate(
- layout_arena: &impl PaintRead,
- owner_paintable: u32,
- line_index: u32,
- node_slots: &[NodeSlotId],
- inline_coordinate: CssPixels,
-) -> Option<usize> {
- let fragments = fragments_of_line(layout_arena, owner_paintable, line_index, node_slots);
- let mut chosen = *fragments.first()?;
- for &(block, index) in &fragments {
- let side = layout_arena.committed_side_data(block);
- let fragment = &side.fragments()[index as usize];
- let rect = text_fragment::absolute_rect(layout_arena, fragment);
- let inline_start = if text_fragment::fragment_is_horizontal(fragment) {
- rect.x
- } else {
- rect.y
- };
- if inline_start <= inline_coordinate {
- chosen = (block, index);
- }
- }
- let (block, index) = chosen;
- let side = layout_arena.committed_side_data(block);
- let fragment = &side.fragments()[index as usize];
- let rect = text_fragment::absolute_rect(layout_arena, fragment);
- let mut point = crate::css::css_pixels::CssPixelPoint {
- x: rect.x + CssPixels::from_raw(rect.width.raw_value() / 2),
- y: rect.y + CssPixels::from_raw(rect.height.raw_value() / 2),
- };
- if text_fragment::fragment_is_horizontal(fragment) {
- point.x = rect.x.max(inline_coordinate);
- } else {
- point.y = rect.y.max(inline_coordinate);
- }
- Some(text_fragment::index_in_node_for_point(layout_arena, fragment, point))
-}
diff --git a/Libraries/LibWeb/VisualLines.cpp b/Libraries/LibWeb/VisualLines.cpp
index 1e5da83f6f5..d0287dd6654 100644
--- a/Libraries/LibWeb/VisualLines.cpp
+++ b/Libraries/LibWeb/VisualLines.cpp
@@ -44,38 +44,6 @@ static Vector<VisualLine> visual_lines_with_up_to_date_layout(DOM::Text const& d
return collect_visual_lines(read, dom_node);
}
-static Optional<size_t> visual_line_index_for_offset(Vector<VisualLine> const& lines, size_t offset, TextAffinity affinity)
-{
- // An offset exactly at a soft wrap boundary belongs to the earlier line with Upstream affinity and to the later
- // line with Downstream affinity. This matches how the caret is painted (see
- // the painted-line fragment lookup).
- Optional<size_t> boundary_match;
- for (size_t i = 0; i < lines.size(); ++i) {
- if (offset < lines[i].start_offset || offset > lines[i].end_offset_with_trailing_whitespace)
- continue;
- if (affinity == TextAffinity::Downstream && offset == lines[i].end_offset_with_trailing_whitespace) {
- // A later line starting exactly at this offset takes precedence.
- if (!boundary_match.has_value())
- boundary_match = i;
- continue;
- }
- return i;
- }
- if (boundary_match.has_value())
- return boundary_match;
-
- if (lines.is_empty())
- return {};
-
- // Offsets that no line covers belong to the closest line that starts before them.
- Optional<size_t> result;
- for (size_t i = 0; i < lines.size(); ++i) {
- if (lines[i].start_offset <= offset)
- result = i;
- }
- return result.value_or(0);
-}
-
// 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)
{
@@ -109,106 +77,6 @@ static TextAffinity affinity_for_moving_right(Vector<VisualLine> const& lines, s
return TextAffinity::Downstream;
}
-// Returns the absolute inline-axis coordinate of the caret at the given offset, which must be on the given line.
-// Returns nothing for lines without rendered text, whose caret sits at the line's inline start.
-static Optional<CSSPixels> caret_inline_coordinate(Layout::BegunRead const& read, DOM::Text const& dom_node, VisualLine const& line, size_t offset)
-{
- if (!line.has_fragments)
- return {};
- auto const* layout_node = dom_node.layout_node(read);
- if (!layout_node)
- return {};
- Layout::RustFFI::FfiOptionalCssPixels result;
- Layout::RustFFI::render_state_visual_line_caret_inline_coordinate(
- layout_node->document_host(), line.owner_paintable, line.line_index, Layout::Node::slot_id(layout_node), offset, &result);
- if (!result.has_value)
- return {};
- return result.value;
-}
-
-static size_t offset_in_visual_line_closest_to_inline_coordinate(Layout::BegunRead const& read, DOM::Text const& dom_node, VisualLine const& line, Optional<CSSPixels> inline_coordinate)
-{
- if (!line.has_fragments || !inline_coordinate.has_value())
- return line.start_offset;
- auto const* layout_node = dom_node.layout_node(read);
- if (!layout_node)
- return line.start_offset;
- return Layout::RustFFI::render_state_visual_line_offset_closest_to_inline_coordinate(
- layout_node->document_host(), line.owner_paintable, line.line_index, Layout::Node::slot_id(layout_node),
- *inline_coordinate, line.start_offset);
-}
-
-Optional<CursorLinePosition> compute_cursor_position_by_page(DOM::Text& text, size_t offset, TextAffinity affinity, bool forward, CSSPixels page_distance)
-{
- Layout::ForcedReadScope read { text.document() };
- auto lines = visual_lines_with_up_to_date_layout(text);
- auto origin_index = visual_line_index_for_offset(lines, offset, affinity);
- if (!origin_index.has_value())
- return {};
- auto inline_coordinate = caret_inline_coordinate(read, text, lines[*origin_index], offset);
- auto origin_coordinate = text.document().caret_line_block_coordinate(read, text, offset, affinity);
- if (!origin_coordinate.has_value())
- return {};
- CursorLinePosition result { offset, affinity };
- auto index = *origin_index;
- for (;;) {
- if ((forward && index + 1 == lines.size()) || (!forward && index == 0)) {
- result = { forward ? text.length() : 0, TextAffinity::Downstream };
- break;
- }
- auto next_index = forward ? index + 1 : index - 1;
- auto next_offset = offset_in_visual_line_closest_to_inline_coordinate(read, text, lines[next_index], inline_coordinate);
- auto next_affinity = affinity_for_offset_on_line(lines, next_index, next_offset);
- auto coordinate = text.document().caret_line_block_coordinate(read, text, next_offset, next_affinity);
- if (!coordinate.has_value())
- break;
- auto distance = *coordinate > *origin_coordinate ? *coordinate - *origin_coordinate : *origin_coordinate - *coordinate;
- if (distance > page_distance)
- break;
- result = { next_offset, next_affinity };
- index = next_index;
- }
- return result;
-}
-
-Optional<CursorLinePosition> compute_cursor_position_on_next_line(DOM::Text const& dom_node, size_t current_offset, TextAffinity affinity)
-{
- Layout::ForcedReadScope read { dom_node.document() };
- // NB: The layout update is best-effort; a detached document may still have no layout node.
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (!as_if<Layout::TextNode>(dom_node.layout_node(read)))
- return {};
-
- auto line_index = visual_line_index_for_offset(lines, current_offset, affinity);
-
- // On the last line (or with no line information at all), move to the end of the text.
- if (!line_index.has_value() || *line_index + 1 >= lines.size())
- return CursorLinePosition { dom_node.data().length_in_code_units(), TextAffinity::Downstream };
-
- auto inline_coordinate = caret_inline_coordinate(read, dom_node, lines[*line_index], current_offset);
- auto new_offset = offset_in_visual_line_closest_to_inline_coordinate(read, dom_node, lines[*line_index + 1], inline_coordinate);
- return CursorLinePosition { new_offset, affinity_for_offset_on_line(lines, *line_index + 1, new_offset) };
-}
-
-Optional<CursorLinePosition> compute_cursor_position_on_previous_line(DOM::Text const& dom_node, size_t current_offset, TextAffinity affinity)
-{
- Layout::ForcedReadScope read { dom_node.document() };
- // NB: The layout update is best-effort; a detached document may still have no layout node.
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (!as_if<Layout::TextNode>(dom_node.layout_node(read)))
- return {};
-
- auto line_index = visual_line_index_for_offset(lines, current_offset, affinity);
-
- // On the first line (or with no line information at all), move to the start of the text.
- if (!line_index.has_value() || *line_index == 0)
- return CursorLinePosition { 0, TextAffinity::Downstream };
-
- auto inline_coordinate = caret_inline_coordinate(read, dom_node, lines[*line_index], current_offset);
- auto new_offset = offset_in_visual_line_closest_to_inline_coordinate(read, dom_node, lines[*line_index - 1], inline_coordinate);
- return CursorLinePosition { new_offset, affinity_for_offset_on_line(lines, *line_index - 1, new_offset) };
-}
-
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);
@@ -239,11 +107,15 @@ Optional<CursorLinePosition> compute_cursor_position_on_previous_character(DOM::
Optional<CSSPixels> cursor_inline_coordinate(Layout::BegunRead const& read, DOM::Text const& dom_node, size_t offset, TextAffinity affinity)
{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- auto line_index = visual_line_index_for_offset(lines, offset, affinity);
- if (!line_index.has_value())
+ 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 caret_inline_coordinate(read, dom_node, lines[*line_index], offset);
+ return result.value;
}
Optional<CursorLinePosition> cursor_position_at_visual_start(DOM::Text const& dom_node)
@@ -279,25 +151,4 @@ size_t find_line_end(Utf16View const& view, size_t offset)
return offset;
}
-size_t find_visual_line_start(DOM::Text const& dom_node, size_t offset, TextAffinity affinity)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (auto line_index = visual_line_index_for_offset(lines, offset, affinity); line_index.has_value())
- return lines[*line_index].start_offset;
-
- return find_line_start(dom_node.data().utf16_view(), offset);
-}
-
-CursorLinePosition find_visual_line_end(DOM::Text const& dom_node, size_t offset, TextAffinity affinity)
-{
- auto lines = visual_lines_with_up_to_date_layout(dom_node);
- if (auto line_index = visual_line_index_for_offset(lines, offset, affinity); line_index.has_value()) {
- // The end of a visual line includes whitespace hanging at a soft wrap point.
- auto end_offset = lines[*line_index].end_offset_with_trailing_whitespace;
- return CursorLinePosition { end_offset, affinity_for_offset_on_line(lines, *line_index, end_offset) };
- }
-
- return CursorLinePosition { find_line_end(dom_node.data().utf16_view(), offset), TextAffinity::Downstream };
-}
-
}
diff --git a/Libraries/LibWeb/VisualLines.h b/Libraries/LibWeb/VisualLines.h
index 72df046e2f3..a617f1bfae4 100644
--- a/Libraries/LibWeb/VisualLines.h
+++ b/Libraries/LibWeb/VisualLines.h
@@ -38,18 +38,11 @@ struct CursorLinePosition {
TextAffinity affinity { TextAffinity::Downstream };
};
-Optional<CursorLinePosition> compute_cursor_position_on_next_line(DOM::Text const&, size_t current_offset, TextAffinity);
-Optional<CursorLinePosition> compute_cursor_position_on_previous_line(DOM::Text const&, size_t current_offset, TextAffinity);
-Optional<CursorLinePosition> compute_cursor_position_by_page(DOM::Text&, size_t current_offset, TextAffinity, bool forward, CSSPixels page_distance);
-
// 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_visual_line_start(DOM::Text const&, size_t offset, TextAffinity);
-CursorLinePosition find_visual_line_end(DOM::Text const&, size_t offset, TextAffinity);
-
size_t find_line_start(Utf16View const&, size_t offset);
size_t find_line_end(Utf16View const&, size_t offset);
diff --git a/Tests/LibWeb/Text/expected/textarea-line-moves-keep-column.txt b/Tests/LibWeb/Text/expected/textarea-line-moves-keep-column.txt
new file mode 100644
index 00000000000..336fdf6ab74
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/textarea-line-moves-keep-column.txt
@@ -0,0 +1,3 @@
+Down, Down, Up, Up: 10 -> 20 -> 31 -> 20 -> 10
+Down, Left, Down, Up: 10 -> 20 -> 19 -> 22 -> 19
+Down, End, Down: 4 -> 20 -> 20 -> 25
diff --git a/Tests/LibWeb/Text/input/textarea-line-moves-keep-column.html b/Tests/LibWeb/Text/input/textarea-line-moves-keep-column.html
new file mode 100644
index 00000000000..97f174a4924
--- /dev/null
+++ b/Tests/LibWeb/Text/input/textarea-line-moves-keep-column.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<style>
+textarea { font: 16px/20px "Liberation Mono", monospace; width: 300px; height: 100px; }
+</style>
+<textarea id="textarea">a long first line
+ab
+a long third line</textarea>
+<script>
+test(() => {
+ // Consecutive moves to other lines keep the column they started from, across the short middle line. Moving the
+ // caret another way starts from its new column, but a move that leaves the caret where it is does not.
+ textarea.focus();
+ for (const [start, keys] of [[10, ["Down", "Down", "Up", "Up"]], [10, ["Down", "Left", "Down", "Up"]], [4, ["Down", "End", "Down"]]]) {
+ textarea.setSelectionRange(start, start);
+ const offsets = [start];
+ for (const key of keys) {
+ textarea.getBoundingClientRect();
+ internals.sendKey(textarea, key);
+ offsets.push(textarea.selectionStart);
+ }
+ println(`${keys.join(", ")}: ${offsets.join(" -> ")}`);
+ }
+});
+</script>