Skip to content

Truly independent web browser

LibWeb: Record forced break offsets and lay out real empty lines

Aliaksandr Kalenik4565ecdf2b00
diff --git a/Libraries/LibWeb/HTML/HTMLBRElement.cpp b/Libraries/LibWeb/HTML/HTMLBRElement.cpp
index 7e225338f12..f0c9cab26be 100644
--- a/Libraries/LibWeb/HTML/HTMLBRElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLBRElement.cpp
@@ -10,10 +10,9 @@
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/HTMLBRElement.h>
#include <LibWeb/Layout/Box.h>
-#include <LibWeb/VisualLines.h>
+#include <LibWeb/Layout/LayoutRustBridge.h>
namespace Web::HTML {
@@ -55,51 +54,14 @@ void HTMLBRElement::apply_presentational_hints(Vector<CSS::StyleProperty>& prope
});
}
-// Rendered inline content that would appear before a <br> on its line.
-static bool is_rendered_inline_content(Layout::BegunRead const& read, DOM::Node const& node)
-{
- if (auto const* text = as_if<DOM::Text>(node)) {
- for (auto const& line : collect_visual_lines(read, *text)) {
- if (line.has_fragments)
- return true;
- }
- return false;
- }
- if (auto const* element = as_if<DOM::Element>(node)) {
- auto const* layout_node = element->layout_node(read);
- if (!layout_node)
- return false;
- if (layout_node->is_replaced_box())
- return true;
- if (layout_node->display().is_inline_outside() && !layout_node->display().is_flow_inside())
- return true;
- }
- return false;
-}
-
-// NB: Layout produces no fragments for <br>, so this walks the DOM back to the start of the containing block or a
-// previous <br>, whichever comes first.
bool HTMLBRElement::represents_empty_line(Layout::BegunRead const& read) const
{
- if (!layout_node(read))
+ auto const* layout_node = this->layout_node(read);
+ if (!layout_node || !layout_node->containing_block())
return false;
-
- auto const* containing_block = layout_node(read)->containing_block();
- if (!containing_block)
- return false;
- auto const* containing_block_dom_node = containing_block->dom_node();
- if (!containing_block_dom_node)
- return false;
-
- for (auto const* previous = previous_in_pre_order(); previous && previous != containing_block_dom_node; previous = previous->previous_in_pre_order()) {
- if (!containing_block_dom_node->is_inclusive_ancestor_of(*previous))
- break;
- if (is<HTMLBRElement>(*previous))
- return true;
- if (is_rendered_inline_content(read, *previous))
- return false;
- }
- return true;
+ CSSPixelPoint line_position;
+ return Layout::RustFFI::layout_script_empty_line_ended_by_forced_break_position(layout_node->document_host(),
+ Layout::Node::slot_id(layout_node->containing_block()), Layout::Node::slot_id(layout_node), &line_position);
}
}
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_content.rs b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
index ab27c60f540..44c35c590c0 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_content.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
@@ -135,9 +135,17 @@ impl PartialEq for GlyphRunRecord {
}
}
+/// The <br> that ends a line, or the preserved newline at `rendered_offset` in the text of `node`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ForcedBreakPosition {
+ pub node: NodeSlotId,
+ pub rendered_offset: u32,
+}
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LineRecord {
pub rect: used_values::FfiCssPixelRect,
+ pub first_fragment: u32,
pub fragment_count: u32,
pub(crate) is_empty: bool,
pub(crate) horizontal_extent: CssPixels,
@@ -158,7 +166,7 @@ pub struct LineRecord {
pub original_available_inline_size: AvailableSize,
pub has_break: bool,
pub has_forced_break: bool,
- pub forced_break_node: NodeSlotId,
+ pub forced_break: Option<ForcedBreakPosition>,
pub has_block_level_box: bool,
pub box_fragment: u32,
}
@@ -435,6 +443,7 @@ impl InlineContent {
.expect("fragment count overflowed");
lines.push(LineRecord {
rect: inline_formatting_context::line_rect(line, content_inline_size),
+ first_fragment: (fragment_count - visible_fragment_count) as u32,
fragment_count: visible_fragment_count as u32,
reusable_atomic_prefix: !line.fragments.is_empty()
&& !line.has_block_level_box
@@ -611,7 +620,11 @@ impl InlineContent {
let fragment_offset = self.fragments.len() as u32;
let piece_offset = self.inline_box_pieces.len() as u32;
self.lines.extend(content.lines.iter().map(|line| {
- let mut line = LineRecord { box_fragment, ..*line };
+ let mut line = LineRecord {
+ box_fragment,
+ first_fragment: line.first_fragment + fragment_offset,
+ ..*line
+ };
line.rect.x += offset.x;
line.rect.y += offset.y;
line.block_start += offset.y;
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
index 026d9735d02..2e8ddc59b56 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
@@ -1759,7 +1759,7 @@ impl<'context> InlineFormattingContext<'context> {
let line_is_empty = self.line_data().line_boxes.last().is_some_and(|line| line.is_empty());
self.set_current_line_start_offset(item_index, item.offset_in_node);
if line_is_empty && line_builder.current_line_has_no_space_left_by_floats() {
- line_builder.break_line(line_builder::ForcedBreak::No, NodeSlotId::INVALID, None);
+ line_builder.break_line(line_builder::ForcedBreak::No, None, None);
continue;
}
let split_item = self.pass.with_grapheme_segmenter(item.node, |grapheme_segmenter| {
@@ -1777,16 +1777,12 @@ impl<'context> InlineFormattingContext<'context> {
if line_is_empty {
return false;
}
- line_builder.break_line(
- line_builder::ForcedBreak::No,
- NodeSlotId::INVALID,
- Some(item.border_box_inline_size()),
- );
+ line_builder.break_line(line_builder::ForcedBreak::No, None, Some(item.border_box_inline_size()));
continue;
};
line_builder.append_text_item(&mut prefix, prepared, style);
self.set_current_line_start_offset(item_index, item.offset_in_node);
- line_builder.break_line(line_builder::ForcedBreak::No, NodeSlotId::INVALID, None);
+ line_builder.break_line(line_builder::ForcedBreak::No, None, None);
}
}
@@ -2147,7 +2143,8 @@ impl<'context> InlineFormattingContext<'context> {
offset_in_node: 0,
});
let continuation = iterator.next_unbreakable_run_inline_size(self);
- line_builder.break_line(line_builder::ForcedBreak::Yes, item.node, continuation);
+ let position = iterator.forced_break_position(&item);
+ line_builder.break_line(line_builder::ForcedBreak::Yes, Some(position), continuation);
if !item.node.is_invalid() && self.clear_floating_boxes(item.node) {
line_builder.did_introduce_clearance(self.block_axis_float_clearance.get());
self.reset_parent_margin_state();
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
index 0ff0c67d8bd..135e9c8fec2 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
@@ -1094,7 +1094,7 @@ impl<'pass> InlineContentPreparer<'pass> {
}
if text_context.should_respect_linebreaks && chunk.has_breaking_newline {
self.text_node_context = Some(text_context);
- return Some(PreparedItem::new(ItemType::ForcedBreak, text_node, 0));
+ return Some(PreparedItem::newline(text_node, chunk.start));
}
let full_text = text_context.text;
@@ -1965,6 +1965,17 @@ impl InlineLevelIterator {
&self.prepared
}
+ /// The <br> or the preserved newline that the forced break `item` stands for.
+ pub(crate) fn forced_break_position(&self, item: &Item) -> inline_content::ForcedBreakPosition {
+ // NB: The item of a preserved newline has no node, so its prepared item cannot be checked against it.
+ let prepared = &self.prepared.items[item.prepared_item_index as usize];
+ debug_assert_eq!(prepared.type_(), ItemType::ForcedBreak);
+ inline_content::ForcedBreakPosition {
+ node: prepared.node(),
+ rendered_offset: prepared.offset_in_node() as u32,
+ }
+ }
+
pub(crate) fn shares_items(&self) -> bool {
matches!(self.items, ItemQueue::Shared { .. })
}
diff --git a/Libraries/LibWeb/Rust/src/layout/line_builder.rs b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
index 23c1e8722ef..d86dd9f6fc7 100644
--- a/Libraries/LibWeb/Rust/src/layout/line_builder.rs
+++ b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
@@ -294,7 +294,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
pub(crate) fn break_line(
&mut self,
forced: ForcedBreak,
- forced_break_node: NodeSlotId,
+ forced_break: Option<inline_content::ForcedBreakPosition>,
next_size: Option<CssPixels>,
) {
// FIXME: Respect inline direction.
@@ -305,7 +305,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
let mut line = self.line_mut(line_index);
line.has_break = true;
line.has_forced_break = forced == ForcedBreak::Yes;
- line.forced_break_node = forced_break_node;
+ line.forced_break = forced_break;
}
self.last_line_needs_update = true;
self.update_last_line(forced == ForcedBreak::No || next_size.is_some());
@@ -387,7 +387,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
if !self.should_break(next_item_inline_size) {
return false;
}
- self.break_line(ForcedBreak::No, NodeSlotId::INVALID, Some(next_item_inline_size));
+ self.break_line(ForcedBreak::No, None, Some(next_item_inline_size));
true
}
@@ -398,7 +398,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
if !self.should_break(next_item_inline_size) {
return false;
}
- self.break_line(ForcedBreak::No, NodeSlotId::INVALID, None);
+ self.break_line(ForcedBreak::No, None, None);
true
}
diff --git a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
index 1bd450c3098..9d24738c05d 100644
--- a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
+++ b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
@@ -77,6 +77,14 @@ impl PreparedItem {
}
}
+ /// The forced break of a preserved newline at `offset_in_node` in the text of `node`.
+ pub(super) fn newline(node: Node, offset_in_node: usize) -> Self {
+ Self {
+ offset_in_node: u32::try_from(offset_in_node).expect("text offsets fit in 32 bits"),
+ ..Self::new(ItemType::ForcedBreak, node, 0)
+ }
+ }
+
pub(super) fn text(
node: Node,
text_range: std::ops::Range<usize>,
diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
index f482d29f3af..0ebd5ef2f49 100644
--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
@@ -523,10 +523,9 @@ pub extern "C" fn layout_script_empty_line_ended_by_forced_break_position(
return None;
}
let side = arena.committed_side_data(block);
- let line = side
- .lines()
- .iter()
- .find(|line| line.forced_break_node == forced_break && line.fragment_count == 0)?;
+ let line = side.lines().iter().find(|line| {
+ line.forced_break.is_some_and(|position| position.node == forced_break) && line.fragment_count == 0
+ })?;
let root_position =
crate::painting::paintable_geometry::LineRootPositions::new(arena, block).of_fragment(line.box_fragment);
Some(CssPixelRect::from(line.rect).translated_by(root_position).location())
diff --git a/Libraries/LibWeb/Rust/src/painting/caret.rs b/Libraries/LibWeb/Rust/src/painting/caret.rs
index a2e64f7a782..2c68e925202 100644
--- a/Libraries/LibWeb/Rust/src/painting/caret.rs
+++ b/Libraries/LibWeb/Rust/src/painting/caret.rs
@@ -8,8 +8,8 @@ use crate::css::css_pixels::{CssPixelRect, CssPixels};
use crate::layout::node_data::NodeSlotId;
use crate::painting::paint_read::PaintRead;
use crate::painting::paintable_data::{FragmentRecord, SELECTION_STATE_START_AND_END};
+use crate::painting::paintable_geometry;
use crate::painting::text_fragment::{self, CaretMatch};
-use crate::painting::visual_lines;
pub(crate) struct CaretRectResult {
pub rect: CssPixelRect,
@@ -92,8 +92,8 @@ pub(crate) fn caret_rect_for_position(
))
}
-/// The caret on an empty line of `block`, such as the line after a trailing newline, at `offset` in the text laid out
-/// in the fragments of `node_slots`. No fragment holds such a position.
+/// The caret on an empty line of `block` that a preserved newline at `offset` in the text laid out in the fragments of
+/// `node_slots` ends. No fragment holds such a position.
pub(crate) fn caret_rect_on_empty_line(
layout_arena: &impl PaintRead,
block: NodeSlotId,
@@ -104,18 +104,23 @@ pub(crate) fn caret_rect_on_empty_line(
return None;
}
let side = layout_arena.committed_side_data(block);
- let first_fragment = side.fragments().first()?;
- if !node_slots.contains(&first_fragment.layout_node) {
- return None;
- }
- let target = visual_lines::empty_line_caret_targets(layout_arena, block)
- .into_iter()
- .find(|target| target.offset == offset)?;
+ let (line, node) = side.lines().iter().find_map(|line| {
+ let position = line
+ .forced_break
+ .filter(|position| line.fragment_count == 0 && node_slots.contains(&position.node))?;
+ let line_offset = layout_arena.dom_offset_for_rendered_text_offset(
+ position.node,
+ position.rendered_offset as usize,
+ crate::layout::RenderedTextBoundary::Start,
+ );
+ (line_offset == offset).then_some((line, position.node))
+ })?;
+ let root_position = paintable_geometry::LineRootPositions::new(layout_arena, block).of_fragment(line.box_fragment);
Some(CaretRectResult {
- rect: target.rect,
- style_source: text_fragment::style_source(layout_arena, first_fragment),
+ rect: CssPixelRect::from(line.rect).translated_by(root_position),
+ style_source: layout_arena.node_parent_if_live(node)?,
owner: block,
- node: first_fragment.layout_node,
+ node,
})
}
diff --git a/Libraries/LibWeb/Rust/src/painting/client_rects.rs b/Libraries/LibWeb/Rust/src/painting/client_rects.rs
index a19b3c230bc..faf9817b85b 100644
--- a/Libraries/LibWeb/Rust/src/painting/client_rects.rs
+++ b/Libraries/LibWeb/Rust/src/painting/client_rects.rs
@@ -288,7 +288,11 @@ fn line_break_rect(arena: &impl PaintRead, break_node: NodeSlotId) -> Option<(No
while let Some(row) = arena.node(ancestor) {
if arena.paintable_row_is_populated(ancestor) {
let side = arena.committed_side_data(ancestor);
- if let Some(line) = side.lines().iter().find(|line| line.forced_break_node == break_node) {
+ if let Some(line) = side
+ .lines()
+ .iter()
+ .find(|line| line.forced_break.is_some_and(|position| position.node == break_node))
+ {
let style = arena.node_style_if_live(ancestor)?;
let root_position =
paintable_geometry::LineRootPositions::new(arena, ancestor).of_fragment(line.box_fragment);
diff --git a/Libraries/LibWeb/Rust/src/painting/record/hit_test_items.rs b/Libraries/LibWeb/Rust/src/painting/record/hit_test_items.rs
index d08e4cfd8c2..4a663986b0c 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/hit_test_items.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/hit_test_items.rs
@@ -11,6 +11,7 @@ use super::{PaintPhase, PaintRecorder};
use crate::css::computed_value_types::SVG_PAINT_NONE;
use crate::css::css_enums;
use crate::css::css_pixels::{CssPixelRect, CssPixels};
+use crate::layout::inline_content::ForcedBreakPosition;
use crate::layout::node_data::{DomPaintFact, NodeKind, NodeSlotId};
use crate::layout::node_facts::{self, NodeShape};
use crate::painting::display_list::commands::ContextRef;
@@ -266,11 +267,7 @@ impl<'a, O: Observer> PaintRecorder<'a, O> {
}
fn record_empty_line_caret_items(&mut self, paintable: NodeSlotId, context: ContextRef) {
- let targets = crate::painting::visual_lines::empty_line_caret_targets(self.source, paintable);
- for target in targets {
- self.append_empty_line_for_fragment(paintable, 0, target.offset, target.line_index, target.rect, context);
- }
- let empty_lines_ended_by_forced_breaks: Vec<(usize, NodeSlotId, CssPixelRect, u32)> = {
+ let empty_lines: Vec<(usize, ForcedBreakPosition, CssPixelRect, u32)> = {
let side = self.source.committed_side_data(paintable);
if side.fragments().is_empty() {
return;
@@ -278,26 +275,37 @@ impl<'a, O: Observer> PaintRecorder<'a, O> {
side.lines()
.iter()
.enumerate()
- .filter(|(_, line)| {
- line.fragment_count == 0 && self.forced_break_node_is_caret_target(line.forced_break_node)
- })
- .map(|(line_index, line)| {
- (
- line_index,
- line.forced_break_node,
- CssPixelRect::from(line.rect),
- line.box_fragment,
- )
+ .filter_map(|(line_index, line)| {
+ let position = line.forced_break.filter(|position| {
+ line.fragment_count == 0 && self.forced_break_is_caret_target(position.node)
+ })?;
+ Some((line_index, position, CssPixelRect::from(line.rect), line.box_fragment))
})
.collect()
};
- if empty_lines_ended_by_forced_breaks.is_empty() {
+ if empty_lines.is_empty() {
return;
}
let positions = paintable_geometry::LineRootPositions::new(self.source, paintable);
- for (line_index, forced_break_node, line_rect, box_fragment) in empty_lines_ended_by_forced_breaks {
+ for (line_index, forced_break, line_rect, box_fragment) in empty_lines {
+ let caret_offset = if self.source.node_kind_if_live(forced_break.node) == Some(NodeKind::BreakNode) {
+ 0
+ } else {
+ self.source.dom_offset_for_rendered_text_offset(
+ forced_break.node,
+ forced_break.rendered_offset as usize,
+ crate::layout::RenderedTextBoundary::Start,
+ )
+ };
let line_rect = line_rect.translated_by(positions.of_fragment(box_fragment));
- self.append_empty_line_for_node(paintable, forced_break_node, line_index, line_rect, context);
+ self.append_empty_line(
+ paintable,
+ forced_break.node,
+ caret_offset,
+ line_index,
+ line_rect,
+ context,
+ );
}
}
@@ -557,14 +565,15 @@ impl<'a, O: Observer> PaintRecorder<'a, O> {
// A text node has no style of its own, so its parent both decides whether the fragment can be hit and is what an
// event dispatched from it resolves against. Returns that node, or None when the fragment is not hit-testable.
- fn forced_break_node_is_caret_target(&self, break_node: NodeSlotId) -> bool {
- let Some(row) = self.source.node(break_node) else {
+ /// Whether the line that the <br> or the preserved newline in the text `node` ends is a caret target.
+ fn forced_break_is_caret_target(&self, node: NodeSlotId) -> bool {
+ let Some(row) = self.source.node(node) else {
return false;
};
- if row.kind() != NodeKind::BreakNode || row.dom_paint_facts() & DomPaintFact::Inert as u8 != 0 {
+ if row.dom_paint_facts() & DomPaintFact::Inert as u8 != 0 {
return false;
}
- let Some(style) = row.style() else {
+ let Some(style) = row.style().or_else(|| self.source.node_style_if_live(row.parent())) else {
return false;
};
if style.visibility() != css_enums::visibility::VISIBLE
@@ -712,51 +721,18 @@ impl<'a, O: Observer> PaintRecorder<'a, O> {
self.list.append(item);
}
- fn append_empty_line_for_fragment(
- &mut self,
- owner: NodeSlotId,
- sibling_fragment_index: u32,
- caret_offset: usize,
- line_box_index: usize,
- line_rect: CssPixelRect,
- context: ContextRef,
- ) {
- let fragment = self.fragment(owner, sibling_fragment_index as usize);
- let Some(hit_node) = self.hit_node_for_text_fragment(&fragment) else {
- return;
- };
- // Empty lines are only reachable through caret lines, never through regular hit testing,
- // so they are recorded with the base's empty rect and stay out of the spatial index.
- let block_container = self.block_container_of_fragment(&fragment);
- let item = HitTestItem {
- text_fragment_index: Some(sibling_fragment_index),
- caret_node: fragment.layout_node,
- caret_offset,
- caret_rect: line_rect,
- caret_line_index: Some(line_box_index),
- block_container,
- containing_block: self
- .source
- .node_containing_block_if_live(fragment.layout_node)
- .unwrap_or(NodeSlotId::INVALID),
- can_produce_caret_position: self.node_has_dom_node(fragment.layout_node),
- hit_node,
- ..self.base_hit_test_item(HitTestItemKind::EmptyLine, owner, context)
- };
- self.list.append(item);
- }
-
- fn append_empty_line_for_node(
+ fn append_empty_line(
&mut self,
block_container: NodeSlotId,
caret_node: NodeSlotId,
+ caret_offset: usize,
caret_line_index: usize,
line_rect: CssPixelRect,
context: ContextRef,
) {
let item = HitTestItem {
caret_node,
- caret_offset: 0,
+ caret_offset,
caret_rect: line_rect,
caret_line_index: Some(caret_line_index),
block_container,
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs b/Libraries/LibWeb/Rust/src/painting/visual_lines.rs
index e94346a58e4..1153441a639 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_lines.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_lines.rs
@@ -4,10 +4,10 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use crate::css::css_pixels::{CssPixelRect, CssPixels};
-use crate::layout::node_data::{NodeKind, NodeSlotId};
+use crate::css::css_pixels::CssPixels;
+use crate::layout::node_data::NodeSlotId;
use crate::painting::paint_read::PaintRead;
-use crate::painting::{paintable_geometry, text_fragment};
+use crate::painting::text_fragment;
pub(crate) struct RecordVisualLine {
pub start_offset: usize,
@@ -18,74 +18,6 @@ pub(crate) struct RecordVisualLine {
pub line_index: u32,
}
-pub(crate) fn text_preserves_newlines(layout_arena: &impl PaintRead, text_node: NodeSlotId) -> bool {
- let Some(parent) = layout_arena.node_parent_if_live(text_node) else {
- return false;
- };
- let Some(parent_style) = layout_arena.node_style_if_live(parent) else {
- return false;
- };
- matches!(
- parent_style.white_space_collapse(),
- crate::css::css_enums::white_space_collapse::PRESERVE
- | crate::css::css_enums::white_space_collapse::PRESERVE_BREAKS
- )
-}
-
-fn for_each_empty_visual_line_position(
- layout_arena: &impl PaintRead,
- node_slots: &[NodeSlotId],
- mut callback: impl FnMut(usize) -> bool,
-) {
- let mut segments: Vec<(NodeSlotId, &[u16])> = Vec::new();
- for &node in node_slots {
- if let Some(content) = layout_arena.rendered_text(node) {
- segments.push((node, &content.text));
- }
- }
- // A text that starts with a newline starts with an empty line.
- if let Some(&(node, text)) = segments.first()
- && text.first() == Some(&u16::from(b'\n'))
- {
- let dom_offset =
- layout_arena.dom_offset_for_rendered_text_offset(node, 0, crate::layout::RenderedTextBoundary::Start);
- if !callback(dom_offset) {
- return;
- }
- }
- for (segment_index, &(node, text)) in segments.iter().enumerate() {
- for (rendered_offset, code_unit) in text.iter().enumerate() {
- if *code_unit != u16::from(b'\n') {
- continue;
- }
- let next_code_unit = text.get(rendered_offset + 1).copied().or_else(|| {
- segments[segment_index + 1..]
- .iter()
- .find_map(|(_, following_text)| following_text.first().copied())
- });
- if next_code_unit.is_none() || next_code_unit == Some(u16::from(b'\n')) {
- let dom_offset = layout_arena.dom_offset_for_rendered_text_offset(
- node,
- rendered_offset + 1,
- crate::layout::RenderedTextBoundary::End,
- );
- if !callback(dom_offset) {
- return;
- }
- }
- }
- }
-}
-
-fn has_empty_visual_line_positions(layout_arena: &impl PaintRead, node_slots: &[NodeSlotId]) -> bool {
- let mut found = false;
- for_each_empty_visual_line_position(layout_arena, node_slots, |_| {
- found = true;
- false
- });
- found
-}
-
pub(crate) fn collect_visual_lines(layout_arena: &impl PaintRead, node_slots: &[NodeSlotId]) -> Vec<RecordVisualLine> {
let mut lines: Vec<RecordVisualLine> = Vec::new();
text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |block, _, fragment| {
@@ -114,119 +46,36 @@ pub(crate) fn collect_visual_lines(layout_arena: &impl PaintRead, node_slots: &[
}
true
});
- if let Some(&primary) = node_slots.last()
- && text_preserves_newlines(layout_arena, primary)
- {
- // The empty line after a text control's trailing newline holds a zero-length fragment, so its line is already
- // in the list.
- let empty_lines_with_fragments: Vec<usize> = lines
- .iter()
- .filter(|line| line.start_offset == line.end_offset)
- .map(|line| line.start_offset)
- .collect();
- for_each_empty_visual_line_position(layout_arena, node_slots, |position| {
- if empty_lines_with_fragments.contains(&position) {
- return true;
- }
- lines.push(RecordVisualLine {
- start_offset: position,
- end_offset: position,
- end_offset_with_trailing_whitespace: position,
- has_fragments: false,
- owner: NodeSlotId::INVALID,
- line_index: 0,
- });
- true
- });
- }
- lines.sort_by_key(|line| line.start_offset);
- lines
-}
-
-pub(crate) struct EmptyLineCaretTarget {
- pub offset: usize,
- pub line_index: usize,
- pub rect: CssPixelRect,
-}
-
-pub(crate) fn empty_line_caret_targets(layout_arena: &impl PaintRead, block: NodeSlotId) -> Vec<EmptyLineCaretTarget> {
- let side = layout_arena.committed_side_data(block);
- if side.fragments().is_empty() || side.lines().is_empty() {
- return Vec::new();
- }
- let text_layout_node = side.fragments()[0].layout_node;
- if layout_arena.node_kind_if_live(text_layout_node) != Some(NodeKind::TextNode) {
- return Vec::new();
- }
- if !text_preserves_newlines(layout_arena, text_layout_node) {
- return Vec::new();
- }
- let block_node = block;
- let Some(block_style) = layout_arena.node_style_if_live(block_node) else {
- return Vec::new();
- };
- if block_style.writing_mode() != crate::css::css_enums::writing_mode::HORIZONTAL_TB {
- return Vec::new();
- }
- let node_slots = [text_layout_node];
- if !has_empty_visual_line_positions(layout_arena, &node_slots) {
- return Vec::new();
- }
- if side
- .fragments()
+ // A preserved newline that ends a line with nothing on it gives the line no fragment.
+ let mut blocks: Vec<NodeSlotId> = node_slots
.iter()
- .any(|fragment| fragment.layout_node != text_layout_node)
- {
- return Vec::new();
- }
-
- let lines = collect_visual_lines(layout_arena, &node_slots);
-
- if lines.len() < side.lines().len() {
- return Vec::new();
- }
- for (i, line) in lines.iter().enumerate() {
- if i >= side.lines().len() {
- if line.has_fragments {
- return Vec::new();
+ .filter_map(|&node| text_fragment::containing_block_paintable_of_node(layout_arena, node))
+ .collect();
+ blocks.dedup();
+ for block in blocks {
+ for (line_index, line) in layout_arena.committed_side_data(block).lines().iter().enumerate() {
+ if let Some(position) = line.forced_break
+ && line.fragment_count == 0
+ && node_slots.contains(&position.node)
+ {
+ let offset = layout_arena.dom_offset_for_rendered_text_offset(
+ position.node,
+ position.rendered_offset as usize,
+ crate::layout::RenderedTextBoundary::Start,
+ );
+ lines.push(RecordVisualLine {
+ start_offset: offset,
+ end_offset: offset,
+ end_offset_with_trailing_whitespace: offset,
+ has_fragments: false,
+ owner: block,
+ line_index: line_index as u32,
+ });
}
- continue;
- }
- if line.has_fragments != (side.lines()[i].fragment_count != 0) {
- return Vec::new();
- }
- if line.has_fragments && line.line_index as usize != i {
- return Vec::new();
}
}
-
- let content_width = paintable_geometry::committed_content_size(layout_arena, block).width;
- let root_positions = paintable_geometry::LineRootPositions::new(layout_arena, block);
- let mut targets = Vec::new();
- for (i, line) in lines.iter().enumerate() {
- if line.has_fragments {
- continue;
- }
- let content_position = root_positions.of_line(side.lines(), i.min(side.lines().len() - 1));
- let rect = if i < side.lines().len() {
- CssPixelRect::from(side.lines()[i].rect).translated_by(content_position)
- } else {
- let last = CssPixelRect::from(side.lines().last().unwrap().rect).translated_by(content_position);
- let steps = (i - (side.lines().len() - 1)) as i32;
- CssPixelRect {
- x: content_position.x,
- y: last.y + last.height + CssPixels::from_raw(last.height.raw_value() * (steps - 1)),
- width: content_width,
- height: last.height,
- }
- };
- targets.push(EmptyLineCaretTarget {
- offset: line.start_offset,
- line_index: i,
- rect,
- });
- }
- targets
+ lines.sort_by_key(|line| line.start_offset);
+ lines
}
fn fragments_of_line(
@@ -235,14 +84,21 @@ fn fragments_of_line(
line_index: u32,
node_slots: &[NodeSlotId],
) -> Vec<(NodeSlotId, u32)> {
- let mut fragments = Vec::new();
- text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |block, index, fragment| {
- if block.index == owner_paintable && fragment.line_index == line_index {
- fragments.push((block, index));
- }
- true
- });
- fragments
+ 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(
diff --git a/Libraries/LibWeb/VisualLines.h b/Libraries/LibWeb/VisualLines.h
index 9c5b122ab38..72df046e2f3 100644
--- a/Libraries/LibWeb/VisualLines.h
+++ b/Libraries/LibWeb/VisualLines.h
@@ -65,6 +65,4 @@ Optional<CSSPixels> cursor_inline_coordinate(Layout::BegunRead const&, DOM::Text
Optional<CursorLinePosition> cursor_position_at_visual_start(DOM::Text const&);
Optional<CursorLinePosition> cursor_position_at_visual_end(DOM::Text const&);
-// Whether any position in the text renders as an empty visual line (between two consecutive newlines, or after a
-
}
diff --git a/Tests/LibWeb/Text/expected/hit_testing/caret-position-on-empty-line-of-preserved-newlines.txt b/Tests/LibWeb/Text/expected/hit_testing/caret-position-on-empty-line-of-preserved-newlines.txt
new file mode 100644
index 00000000000..abca283939d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/hit_testing/caret-position-on-empty-line-of-preserved-newlines.txt
@@ -0,0 +1,2 @@
+vertical: vertical text 4
+split: newlines text 1
diff --git a/Tests/LibWeb/Text/input/hit_testing/caret-position-on-empty-line-of-preserved-newlines.html b/Tests/LibWeb/Text/input/hit_testing/caret-position-on-empty-line-of-preserved-newlines.html
new file mode 100644
index 00000000000..31bf862afb9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/hit_testing/caret-position-on-empty-line-of-preserved-newlines.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<style>
+body { margin: 0; }
+pre { font: 16px/20px "Liberation Mono", monospace; margin: 0 0 10px 0; height: 80px; }
+#vertical { writing-mode: vertical-rl; width: 80px; }
+</style>
+<pre id="vertical">one
+
+three</pre>
+<pre id="split">one<span id="newlines">
+
+</span>three</pre>
+<script src="../include.js"></script>
+<script>
+ // A point on the empty line between two preserved newlines takes the position between them, also in vertical
+ // text and where the newlines are in a text node of their own.
+ test(() => {
+ const describe = position => {
+ const node = position.offsetNode;
+ const owner = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
+ return `${owner.id} ${node.nodeType === Node.TEXT_NODE ? "text" : node.nodeName} ${position.offset}`;
+ };
+ const vertical = document.getElementById("vertical").getBoundingClientRect();
+ println(`vertical: ${describe(document.caretPositionFromPoint(vertical.right - 30, vertical.top + 10))}`);
+ const split = document.getElementById("split").getBoundingClientRect();
+ println(`split: ${describe(document.caretPositionFromPoint(split.left + 30, split.top + 30))}`);
+ });
+</script>