Skip to content

Truly independent web browser

LibWeb: Lay out and paint SVG text in document order

sideshowbarker71a933e376d9
diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
index 540ebc3c913..8bf7016f750 100644
--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
@@ -124,11 +124,22 @@ pub(crate) struct GridPayload {
pub(crate) used_tracks: Option<std::sync::Arc<grid_formatting_context::OwnedUsedGridTracks>>,
}
+/// A part of the glyph outlines of a text content element's own text, which paints after one of the element's children.
+#[derive(Clone, PartialEq)]
+pub(crate) struct SvgTextSegment {
+ /// The child element the part follows, or the invalid slot for the part that comes before every child element.
+ pub(crate) after_child: crate::layout::node_data::NodeSlotId,
+ pub(crate) path: libgfx_rust::path::Path,
+}
+
#[derive(Clone, Default)]
pub(crate) struct SvgPayload {
pub(crate) facts: CommittedSvgFacts,
pub(crate) geometry: svg_formatting_context::SvgGeometry,
pub(crate) path: Option<std::sync::Arc<CommittedSvgPath>>,
+ /// The path of a text content element, in the parts that paint apart: Text that follows a child element paints
+ /// after that child. None where all of the element's text comes before its child elements.
+ pub(crate) text_segments: Option<std::sync::Arc<Vec<SvgTextSegment>>>,
pub(crate) text_character_cells: Option<std::sync::Arc<Vec<svg_formatting_context::FfiSvgTextCharacterCell>>>,
}
@@ -207,6 +218,7 @@ impl PartialEq for FcPayload {
left.facts == right.facts
&& left.geometry == right.geometry
&& same_allocation(left.path.as_ref(), right.path.as_ref())
+ && same_allocation(left.text_segments.as_ref(), right.text_segments.as_ref())
&& same_allocation(left.text_character_cells.as_ref(), right.text_character_cells.as_ref())
}
_ => false,
@@ -229,6 +241,7 @@ impl FcPayload {
left.facts == right.facts
&& left.geometry == right.geometry
&& left.path == right.path
+ && left.text_segments == right.text_segments
&& left.text_character_cells == right.text_character_cells
}
_ => false,
@@ -242,6 +255,7 @@ impl FcPayload {
svg.facts == CommittedSvgFacts::default()
&& svg.geometry == Default::default()
&& svg.path.is_none()
+ && svg.text_segments.is_none()
&& svg.text_character_cells.is_none()
}
Self::Table(_) | Self::Flex(_) | Self::Multicol(_) | Self::Math(_) => false,
diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
index 350e378b559..ed30248b938 100644
--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
@@ -512,6 +512,52 @@ fn view_box_transform(
.translated(-view_box.min_x as f32, -view_box.min_y as f32)
}
+/// What laying out a <text>, a <tspan>, or an <a> inside one yields.
+#[derive(Default)]
+struct SvgTextBoxContents {
+ /// The glyph outlines of the element's own text nodes.
+ path: libgfx_rust::path::Path,
+ /// Those outlines split by the child elements between them, where text follows a child element.
+ segments: Option<Vec<fragment_tree::SvgTextSegment>>,
+ /// The cells the glyphs of the element's own text nodes occupy.
+ glyph_cells: SvgCssPixelRect,
+ /// The glyph cell of each character in the element's subtree, in document order.
+ character_cells: Vec<FfiSvgTextCharacterCell>,
+ /// The union of the boxes of the element's text content child elements.
+ children_bounding_box: SvgCssPixelRect,
+}
+
+/// The glyphs a text content element paints, in parts: each part with the child element it paints after, in paint order.
+#[derive(Default)]
+struct SvgTextPaintParts {
+ parts: Vec<(Node, Vec<libgfx_rust::path::GlyphRun>)>,
+}
+
+impl SvgTextPaintParts {
+ fn add_glyphs(&mut self, after_child: Node, runs: Vec<libgfx_rust::path::GlyphRun>) {
+ if runs.is_empty() {
+ return;
+ }
+ if let Some((last_after_child, last_runs)) = self.parts.last_mut()
+ && *last_after_child == after_child
+ {
+ last_runs.extend(runs);
+ return;
+ }
+ self.parts.push((after_child, runs));
+ }
+
+ /// Whether the parts are just the glyphs of text that comes before every child element, which the element's
+ /// path paints as it is.
+ fn are_one_path(&self) -> bool {
+ match self.parts.as_slice() {
+ [] => true,
+ [(after_child, _)] => after_child.is_invalid(),
+ _ => false,
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq)]
struct SvgTextChunkMeasurement {
advance: f32,
@@ -527,14 +573,15 @@ impl Default for SvgTextChunkMeasurement {
}
}
-/// Processes the white space in an SVG text content element's character data, as the element's
-/// 'white-space-collapse' value directs.
+/// Processes the white space in the character data of a text content block element: `sources` holds the text of each
+/// of its text nodes, in document order, with the 'white-space-collapse' value of the element the text node is in.
+/// Returns the characters each text node renders.
/// https://svgwg.org/svg2-draft/text.html#WhiteSpace
/// Rendering of white space in SVG 2 is controlled by the white-space property. [...] Values and
/// their meanings are defined in CSS Text Module Level 3.
/// NB: SVG text is laid out as one line, so both phases of CSS Text's white space processing
/// happen here, on the characters themselves, before they are shaped.
-fn process_svg_text_white_space(text: &mut Vec<u16>, white_space_collapse: u8) {
+fn process_svg_text_white_space(sources: &[(&[u16], u8)]) -> Vec<Vec<u16>> {
const SPACE: u16 = b' ' as u16;
const TAB: u16 = b'\t' as u16;
const LINE_FEED: u16 = b'\n' as u16;
@@ -545,65 +592,67 @@ fn process_svg_text_white_space(text: &mut Vec<u16>, white_space_collapse: u8) {
let is_segment_break = |unit: u16| unit == LINE_FEED || unit == CARRIAGE_RETURN;
let is_white_space = |unit: u16| unit == SPACE || unit == TAB || is_segment_break(unit);
- match white_space_collapse {
- // https://drafts.csswg.org/css-text-4/#valdef-white-space-collapse-discard
- // This value directs user agents to "discard" all white space in the element.
- white_space_collapse::DISCARD => text.retain(|&unit| !is_white_space(unit)),
- // https://drafts.csswg.org/css-text-4/#white-space-phase-1
- // If white-space-collapse is set to collapse or preserve-breaks, white space characters are
- // considered collapsible and are processed by performing the following steps:
- // 1. Any sequence of collapsible spaces and tabs immediately preceding or following a
- // segment break is removed.
- // 2. Collapsible segment breaks are transformed for rendering according to the segment
- // break transformation rules.
- // 3. Every collapsible tab is converted to a collapsible space (U+0020).
- // 4. Any collapsible space immediately following another collapsible space [...] is
- // collapsed to have zero advance width.
- // https://drafts.csswg.org/css-text-4/#white-space-phase-2
- // 1. A sequence of collapsible spaces at the beginning of a line is removed.
- // 3. A sequence of collapsible spaces at the end of a line is removed [...]
- // Together, those steps turn every run of collapsible white space into a single space, and
- // drop the runs at either end of the one line SVG text renders as.
- // https://drafts.csswg.org/css-text-4/#line-break-transform
- // Then any remaining segment break is either transformed into a space (U+0020) or removed
- // depending on the context before and after the break. The rules for this operation are
- // UA-defined in this level.
- // We transform every remaining segment break into a space.
- // AD-HOC: preserve-breaks keeps segment breaks as forced line breaks, but SVG text has no
- // line breaking here, so its segment breaks collapse like collapse's do.
- white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS => {
- let mut processed = Vec::with_capacity(text.len());
- let mut after_white_space = false;
- for &unit in text.iter() {
- if is_white_space(unit) {
- after_white_space = true;
- continue;
- }
- if after_white_space && !processed.is_empty() {
- processed.push(SPACE);
+ let mut processed: Vec<Vec<u16>> = sources.iter().map(|(text, _)| Vec::with_capacity(text.len())).collect();
+ // The text node that holds the first character of a run of collapsible white space the line hasn't ended in yet.
+ let mut collapsible_space_owner: Option<usize> = None;
+ let mut at_line_start = true;
+ for (index, (text, white_space_collapse)) in sources.iter().enumerate() {
+ for &unit in *text {
+ if is_white_space(unit) {
+ match *white_space_collapse {
+ // https://drafts.csswg.org/css-text-4/#valdef-white-space-collapse-discard
+ // This value directs user agents to "discard" all white space in the element.
+ white_space_collapse::DISCARD => continue,
+ // https://drafts.csswg.org/css-text-4/#white-space-phase-1
+ // If white-space-collapse is set to collapse or preserve-breaks, white space characters are
+ // considered collapsible and are processed by performing the following steps:
+ // 1. Any sequence of collapsible spaces and tabs immediately preceding or following a
+ // segment break is removed.
+ // 2. Collapsible segment breaks are transformed for rendering according to the segment
+ // break transformation rules.
+ // 3. Every collapsible tab is converted to a collapsible space (U+0020).
+ // 4. Any collapsible space immediately following another collapsible space—even one
+ // outside the boundary of the inline containing that space, provided both spaces are
+ // within the same inline formatting context—is collapsed to have zero advance width.
+ // https://drafts.csswg.org/css-text-4/#white-space-phase-2
+ // 1. A sequence of collapsible spaces at the beginning of a line is removed.
+ // 3. A sequence of collapsible spaces at the end of a line is removed [...]
+ // Together, those steps turn every run of collapsible white space into a single space, which
+ // the text node the run starts in renders, and drop the runs at either end of the one line SVG
+ // text renders as.
+ // https://drafts.csswg.org/css-text-4/#line-break-transform
+ // Then any remaining segment break is either transformed into a space (U+0020) or removed
+ // depending on the context before and after the break. The rules for this operation are
+ // UA-defined in this level.
+ // We transform every remaining segment break into a space.
+ // AD-HOC: preserve-breaks keeps segment breaks as forced line breaks, but SVG text has no
+ // line breaking here, so its segment breaks collapse like collapse's do.
+ white_space_collapse::COLLAPSE | white_space_collapse::PRESERVE_BREAKS => {
+ if !at_line_start && collapsible_space_owner.is_none() {
+ collapsible_space_owner = Some(index);
+ }
+ continue;
+ }
+ // https://drafts.csswg.org/css-text-4/#white-space-phase-1
+ // If white-space-collapse is set to preserve-spaces, each tab and segment break is
+ // converted to a space.
+ // https://drafts.csswg.org/css-text-4/#valdef-white-space-collapse-preserve
+ // preserve: This value prevents user agents from collapsing sequences of white space.
+ // Segment breaks such as line feeds are preserved as forced line breaks.
+ // AD-HOC: SVG text has no line breaking here, so preserve and break-spaces render each
+ // segment break as a space too, rather than as a forced line break. Likewise a
+ // preserved tab renders as a space rather than as a shift to the next tab stop.
+ _ => {}
}
- after_white_space = false;
- processed.push(unit);
}
- *text = processed;
- }
- // https://drafts.csswg.org/css-text-4/#white-space-phase-1
- // If white-space-collapse is set to preserve-spaces, each tab and segment break is
- // converted to a space.
- // https://drafts.csswg.org/css-text-4/#valdef-white-space-collapse-preserve
- // preserve: This value prevents user agents from collapsing sequences of white space.
- // Segment breaks such as line feeds are preserved as forced line breaks.
- // AD-HOC: SVG text has no line breaking here, so preserve and break-spaces render each
- // segment break as a space too, rather than as a forced line break. Likewise a
- // preserved tab renders as a space rather than as a shift to the next tab stop.
- _ => {
- for unit in text.iter_mut() {
- if *unit == TAB || is_segment_break(*unit) {
- *unit = SPACE;
- }
+ if let Some(owner) = collapsible_space_owner.take() {
+ processed[owner].push(SPACE);
}
+ at_line_start = false;
+ processed[index].push(if is_white_space(unit) { SPACE } else { unit });
}
}
+ processed
}
fn code_point_length_at(text: &[u16], offset: usize) -> usize {
@@ -637,6 +686,10 @@ pub(super) struct SvgFormattingContext<'pass> {
/// sets it once the root is definite. A nested context takes it from the context that creates it.
percentage_block_insets_of_run_root_children_have_definite_basis: bool,
current_text_position: FfiFloatPoint,
+ /// The characters each text node of the text content elements laid out so far renders.
+ processed_svg_text: RefCell<std::collections::HashMap<Node, std::sync::Arc<[u16]>>>,
+ /// The glyph cells of the text content element laid out last: those of its whole subtree, in document order.
+ last_text_subtree_cells: Option<std::sync::Arc<Vec<FfiSvgTextCharacterCell>>>,
/// What the run's root, where this is the context of the root, hands the root's fragment.
root_payload: RefCell<fragment_tree::PendingPayload>,
}
@@ -674,6 +727,8 @@ impl<'pass> SvgFormattingContext<'pass> {
viewport_is_committed_viewport: false,
percentage_block_insets_of_run_root_children_have_definite_basis,
current_text_position: FfiFloatPoint::default(),
+ processed_svg_text: RefCell::new(std::collections::HashMap::new()),
+ last_text_subtree_cells: None,
root_payload: RefCell::new(fragment_tree::PendingPayload::default()),
}
}
@@ -1337,45 +1392,25 @@ impl<'pass> SvgFormattingContext<'pass> {
}
}
- /// The character data an SVG text content element renders: its direct child text, with its
- /// white space processed as the element's 'white-space-collapse' directs. SVG shapes the
- /// element's own characters, not the text a line box would lay out, so this reads the source
- /// text the row kept beside its rendering.
- fn svg_text_contents(&self, node: Node) -> Vec<u16> {
- let mut text: Vec<u16> = Vec::new();
- for child in self.run.pass.children(node) {
- if node_facts::kind_is_text(self.node_kind(child)) {
- self.append_svg_source_text(child, &mut text);
- }
- }
- // FIXME: White space is processed per element, so a collapsible space at an element
- // boundary (<text>a <tspan>b</tspan></text>) collapses away instead of surviving as
- // the one space between the runs. Collapsing across the whole <text> subtree needs
- // its text walked in document order.
- process_svg_text_white_space(&mut text, self.style(node).white_space_collapse());
- text
- }
-
- /// The character data text on a path renders: the source text of every text node in its
- /// subtree whose parent has a box, rather than of its direct children alone.
- /// AD-HOC: The subtree's text is processed as one run, with the <textPath>'s own
- /// 'white-space-collapse', rather than each child's text with that child's value.
- fn rendered_svg_text_contents(&self, root: Node) -> Vec<u16> {
- let mut text: Vec<u16> = Vec::new();
+ /// Calls `visit` with each text node below `root` that renders, in document order: The text nodes of `root`, and
+ /// of the text content elements below it. Text in any other element inside a <text> isn't rendered.
+ fn for_each_svg_text_node(&self, root: Node, mut visit: impl FnMut(Node)) {
let mut current = root;
loop {
- if node_facts::kind_is_text(self.node_kind(current)) {
- self.append_svg_source_text(current, &mut text);
+ let kind = self.node_kind(current);
+ if node_facts::kind_is_text(kind) {
+ visit(current);
}
- let child = self.first_child(current);
- if !child.is_invalid() {
- current = child;
- continue;
+ if matches!(kind, NodeKind::SVGTextBox | NodeKind::SVGTextPathBox) {
+ let child = self.first_child(current);
+ if !child.is_invalid() {
+ current = child;
+ continue;
+ }
}
loop {
if current == root {
- process_svg_text_white_space(&mut text, self.style(root).white_space_collapse());
- return text;
+ return;
}
let sibling = self.next_sibling(current);
if !sibling.is_invalid() {
@@ -1387,6 +1422,77 @@ impl<'pass> SvgFormattingContext<'pass> {
}
}
+ /// The characters the given text node of a text content element renders: its character data, with its white space
+ /// processed as the 'white-space-collapse' of the element it's in directs. White space collapses across element
+ /// boundaries, so the text of the whole text content block element is processed in one go, in document order.
+ /// SVG shapes the element's own characters, not the text a line box would lay out, so this reads the source text
+ /// the row kept beside its rendering.
+ fn processed_svg_text(&self, text_node: Node) -> std::sync::Arc<[u16]> {
+ if let Some(text) = self.processed_svg_text.borrow().get(&text_node) {
+ return text.clone();
+ }
+ let mut root = self.parent(text_node);
+ loop {
+ let parent = self.parent(root);
+ if parent.is_invalid() || !matches!(self.node_kind(parent), NodeKind::SVGTextBox | NodeKind::SVGTextPathBox)
+ {
+ break;
+ }
+ root = parent;
+ }
+ let mut text_nodes = Vec::new();
+ self.for_each_svg_text_node(root, |node| text_nodes.push(node));
+ let sources: Vec<(Vec<u16>, u8)> = text_nodes
+ .iter()
+ .map(|&node| {
+ let mut source = Vec::new();
+ self.append_svg_source_text(node, &mut source);
+ (source, self.style(self.parent(node)).white_space_collapse())
+ })
+ .collect();
+ let borrowed_sources: Vec<(&[u16], u8)> = sources
+ .iter()
+ .map(|(source, white_space_collapse)| (source.as_slice(), *white_space_collapse))
+ .collect();
+ let mut processed_text = self.processed_svg_text.borrow_mut();
+ for (node, text) in text_nodes.iter().zip(process_svg_text_white_space(&borrowed_sources)) {
+ processed_text.insert(*node, std::sync::Arc::from(text));
+ }
+ processed_text
+ .get(&text_node)
+ .cloned()
+ .unwrap_or_else(|| std::sync::Arc::from(Vec::new()))
+ }
+
+ /// The characters of the run of adjacent text nodes that starts at `text_node`: its own, and those of the text
+ /// nodes that come right after it. Where one text node ends and the next starts is no boundary to the text, so the
+ /// run is shaped as one. None where `text_node` comes right after another text node, whose run it belongs to.
+ fn svg_text_run_starting_at(&self, text_node: Node) -> Option<std::sync::Arc<[u16]>> {
+ let is_text = |node: Node| !node.is_invalid() && node_facts::kind_is_text(self.node_kind(node));
+ if is_text(self.run.pass.previous_sibling(text_node)) {
+ return None;
+ }
+ let text = self.processed_svg_text(text_node);
+ let mut next = self.next_sibling(text_node);
+ if !is_text(next) {
+ return Some(text);
+ }
+ let mut run = text.to_vec();
+ while is_text(next) {
+ run.extend_from_slice(&self.processed_svg_text(next));
+ next = self.next_sibling(next);
+ }
+ Some(std::sync::Arc::from(run))
+ }
+
+ /// The character data text on a path renders: the text of every text node in its subtree that renders, rather
+ /// than of its direct children alone.
+ fn rendered_svg_text_contents(&self, root: Node) -> Vec<u16> {
+ let mut text: Vec<u16> = Vec::new();
+ self.for_each_svg_text_node(root, |node| text.extend_from_slice(&self.processed_svg_text(node)));
+ text
+ }
+
fn append_svg_source_text(&self, text_node: Node, out: &mut Vec<u16>) {
let content = self.run.pass.arena().text_content(text_node);
debug_assert!(content.is_some(), "SVG text child was not synced before layout");
@@ -1403,9 +1509,21 @@ impl<'pass> SvgFormattingContext<'pass> {
/// element always positions its first character absolutely, and so always starts a chunk.
fn svg_text_box_starts_text_chunk(&self, text_box: Node) -> bool {
let attributes = self.svg_attributes(text_box);
- attributes.is_text_element
- || attributes.text_x.kind != SVG_LENGTH_KIND_NONE
- || attributes.text_y.kind != SVG_LENGTH_KIND_NONE
+ if attributes.is_text_element {
+ return true;
+ }
+ // NB: The attributes position the element's first character, so they do nothing on an element without one.
+ (attributes.text_x.kind != SVG_LENGTH_KIND_NONE || attributes.text_y.kind != SVG_LENGTH_KIND_NONE)
+ && self.svg_text_box_renders_characters(text_box)
+ }
+
+ /// Whether any text node below the given box renders a character.
+ fn svg_text_box_renders_characters(&self, text_box: Node) -> bool {
+ let mut renders_characters = false;
+ self.for_each_svg_text_node(text_box, |node| {
+ renders_characters = renders_characters || !self.processed_svg_text(node).is_empty();
+ });
+ renders_characters
}
fn apply_svg_text_positioning(&mut self, text_box: Node, attributes: FfiSvgAttributeFacts) {
@@ -1549,7 +1667,7 @@ impl<'pass> SvgFormattingContext<'pass> {
shaped_text
}
- /// The advance of the text run rendered by the given box; that is, of its direct child text.
+ /// The advance of `text`, the characters of one text node of the given box.
fn svg_text_run_advance(&self, text_box: Node, text: &[u16]) -> f32 {
let mut advance = 0.0f32;
let style = self.style(text_box);
@@ -1572,7 +1690,7 @@ impl<'pass> SvgFormattingContext<'pass> {
/// Measures the total advance of the text chunk that starts at the given box, and determines
/// the 'text-anchor' value that applies to the chunk. The chunk extends in document order
/// through the subtree of the containing <text> element until the next box that starts a chunk
- /// of its own.
+ /// of its own, so it takes in the text that follows the box in the elements the box is in.
fn measure_svg_text_chunk(&self, chunk_start_box: Node) -> SvgTextChunkMeasurement {
let mut subtree_root = chunk_start_box;
let mut ancestor = self.parent(chunk_start_box);
@@ -1587,30 +1705,30 @@ impl<'pass> SvgFormattingContext<'pass> {
let mut current = subtree_root;
'walk: loop {
let kind = self.node_kind(current);
- // AD-HOC: Text on a path is laid out independently; see compute_path_for_svg_text_path().
- let descend = kind != NodeKind::SVGTextPathBox;
if kind == NodeKind::SVGTextBox {
if current == chunk_start_box {
found_chunk_start = true;
} else if found_chunk_start && self.svg_text_box_starts_text_chunk(current) {
break 'walk;
}
- if found_chunk_start {
- let text = self.svg_text_contents(current);
- if !text.is_empty() {
- if !found_first_rendered_text {
- // https://svgwg.org/svg2-draft/text.html#TextLayoutAlgorithm
- // Adjust shift based on the value of 'text-anchor' and 'direction' of
- // the element the character at index i.
- // FIXME: Take text direction into account.
- measurement.anchor = self.style(current).inherited_svg().text_anchor;
- found_first_rendered_text = true;
- }
- measurement.advance += self.svg_text_run_advance(current, &text);
- }
+ } else if found_chunk_start
+ && node_facts::kind_is_text(kind)
+ && let Some(text) = self.svg_text_run_starting_at(current)
+ && !text.is_empty()
+ {
+ let text_box = self.parent(current);
+ if !found_first_rendered_text {
+ // https://svgwg.org/svg2-draft/text.html#TextLayoutAlgorithm
+ // Adjust shift based on the value of 'text-anchor' and 'direction' of
+ // the element the character at index i.
+ // FIXME: Take text direction into account.
+ measurement.anchor = self.style(text_box).inherited_svg().text_anchor;
+ found_first_rendered_text = true;
}
+ measurement.advance += self.svg_text_run_advance(text_box, &text);
}
- if descend {
+ // AD-HOC: Text on a path is laid out independently; see svg_text_path_box_path().
+ if kind == NodeKind::SVGTextBox {
let child = self.first_child(current);
if !child.is_invalid() {
current = child;
@@ -1632,12 +1750,13 @@ impl<'pass> SvgFormattingContext<'pass> {
measurement
}
- /// The glyph outlines a <text> or <tspan> renders, the cells they occupy, and the glyph cell of each of its
- /// characters, advancing the current text position.
- fn svg_text_box_path(
+ /// Lays out what a <text>, a <tspan>, or an <a> inside one renders, in document order: its text nodes, which it
+ /// shapes itself, and its text content child elements. Every character advances the current text position.
+ fn layout_svg_text_box_contents(
&mut self,
+ run: &FormattingContextRun<'pass>,
text_box: Node,
- ) -> (libgfx_rust::path::Path, SvgCssPixelRect, Vec<FfiSvgTextCharacterCell>) {
+ ) -> SvgTextBoxContents {
let attributes = self.svg_attributes(text_box);
// https://svgwg.org/svg2-draft/text.html#TextElementXAttribute
// the starting X (Y) coordinate for rendering the glyphs corresponding to the given
@@ -1649,7 +1768,14 @@ impl<'pass> SvgFormattingContext<'pass> {
if attributes.is_text_element {
self.current_text_position = FfiFloatPoint::default();
}
- self.apply_svg_text_positioning(text_box, attributes);
+ // https://svgwg.org/svg2-draft/text.html#TextElementXAttribute
+ // If a comma- or space-separated list of n <length>s is provided, then the values represent new absolute X (Y)
+ // coordinates for the current text position for rendering the glyphs corresponding to each of the first n
+ // addressable characters within this element or any of its descendants.
+ // NB: So, the attributes of an element without a character don't move the current text position.
+ if attributes.is_text_element || self.svg_text_box_renders_characters(text_box) {
+ self.apply_svg_text_positioning(text_box, attributes);
+ }
if self.svg_text_box_starts_text_chunk(text_box) {
// https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties
// The 'text-anchor' property is applied to each individual text chunk within a given
@@ -1676,25 +1802,65 @@ impl<'pass> SvgFormattingContext<'pass> {
}
}
- let style = self.style(text_box);
- let text_offset = FfiFloatPoint {
- x: self.current_text_position.x,
- y: self.current_text_position.y + self.svg_dominant_baseline_offset(style),
- };
- let text = self.svg_text_contents(text_box);
- let shaped = self.shape_svg_text(style, &text, text_offset);
-
- // https://svgwg.org/svg2-draft/text.html#TextLayoutIntroduction
- // After each glyph is placed, the current text position is advanced by the glyph's advance
- // value (typically the width for horizontal text or height for vertical text).
- // FIXME: Take writing mode and text direction into account.
- self.current_text_position.x += shaped.advance;
+ let dominant_baseline_offset = self.svg_dominant_baseline_offset(self.style(text_box));
+ let mut contents = SvgTextBoxContents::default();
+ // Text that follows a child element paints after that child, so it's kept apart from the text before it.
+ let mut paint_parts = SvgTextPaintParts::default();
+ let mut after_child = Node::INVALID;
+ for child in self.run.pass.children(text_box) {
+ let kind = self.node_kind(child);
+ if node_facts::kind_is_text(kind) {
+ let Some(text) = self.svg_text_run_starting_at(child) else {
+ continue;
+ };
+ let text_offset = FfiFloatPoint {
+ x: self.current_text_position.x,
+ y: self.current_text_position.y + dominant_baseline_offset,
+ };
+ let shaped = self.shape_svg_text(self.style(text_box), &text, text_offset);
+
+ // https://svgwg.org/svg2-draft/text.html#TextLayoutIntroduction
+ // After each glyph is placed, the current text position is advanced by the glyph's advance
+ // value (typically the width for horizontal text or height for vertical text).
+ // FIXME: Take writing mode and text direction into account.
+ self.current_text_position.x += shaped.advance;
+
+ paint_parts.add_glyphs(after_child, shaped.runs);
+
+ contents.glyph_cells.unite(shaped.glyph_cells);
+ contents.character_cells.extend(shaped.character_cells);
+ } else if matches!(kind, NodeKind::SVGTextBox | NodeKind::SVGTextPathBox) {
+ // <text> and <tspan> elements can contain more text elements, whose glyph cells count toward this
+ // box too.
+ let child_geometry = self.layout_graphics_element(run, child);
+ contents
+ .children_bounding_box
+ .unite(float_rect_to_css_pixels(child_geometry.stroke_bounding_box));
+ if let Some(cells) = self.last_text_subtree_cells.take() {
+ contents.character_cells.extend(cells.iter().copied());
+ }
+ after_child = child;
+ }
+ }
- (
- libgfx_rust::path::Path::from_glyph_runs(&shaped.runs),
- shaped.glyph_cells,
- shaped.character_cells,
- )
+ // NB: Where the element's text all comes before its child elements, its path paints as it is.
+ let paints_as_one_path = paint_parts.are_one_path();
+ let mut glyph_outlines = libgfx_rust::path::Path::new();
+ let mut segments = Vec::new();
+ for (after_child, runs) in paint_parts.parts {
+ let path = libgfx_rust::path::Path::from_glyph_runs(&runs);
+ if paints_as_one_path {
+ glyph_outlines = path;
+ break;
+ }
+ glyph_outlines.append_path(&path);
+ segments.push(fragment_tree::SvgTextSegment { after_child, path });
+ }
+ contents.path = glyph_outlines;
+ if !paints_as_one_path {
+ contents.segments = Some(segments);
+ }
+ contents
}
/// The glyph outlines a <textPath> renders: its whole subtree's text, shaped from the origin
@@ -2315,11 +2481,19 @@ impl<'pass> SvgFormattingContext<'pass> {
// A shape's geometry is its own attributes and computed style against the viewport, and
// text is its own character data shaped with its own font cascade, so the pass draws both.
let kind = self.node_kind(graphics_box);
+ let mut text_segments = None;
+ let mut text_children_bounding_box = SvgCssPixelRect::default();
let (path, glyph_cells, character_cells) = match kind {
NodeKind::SVGGeometryBox => (self.svg_geometry_path(graphics_box), None, None),
NodeKind::SVGTextBox => {
- let (path, glyph_cells, character_cells) = self.svg_text_box_path(graphics_box);
- (path, Some(glyph_cells), Some(character_cells))
+ let contents = self.layout_svg_text_box_contents(run, graphics_box);
+ text_segments = contents.segments;
+ text_children_bounding_box = contents.children_bounding_box;
+ (
+ contents.path,
+ Some(contents.glyph_cells),
+ Some(contents.character_cells),
+ )
}
NodeKind::SVGTextPathBox => {
let (path, character_cells) = self.svg_text_path_box_path(graphics_box);
@@ -2347,19 +2521,14 @@ impl<'pass> SvgFormattingContext<'pass> {
bounding_box.inflate(stroke_width, stroke_width);
}
- if kind == NodeKind::SVGTextBox {
- // <text> and <tspan> elements can contain more text elements, whose glyph cells count toward this box too.
- for child in self.run.pass.children(graphics_box) {
- if matches!(self.node_kind(child), NodeKind::SVGTextBox | NodeKind::SVGTextPathBox) {
- let child_geometry = self.layout_graphics_element(run, child);
- bounding_box.unite(float_rect_to_css_pixels(child_geometry.stroke_bounding_box));
- }
- }
- }
+ bounding_box.unite(text_children_bounding_box);
+ let character_cells = character_cells.map(std::sync::Arc::new);
+ self.last_text_subtree_cells = character_cells.clone();
self.update_svg_payload_of(graphics_box, |svg| {
svg.path = Some(std::sync::Arc::new(fragment_tree::CommittedSvgPath::new(path)));
- svg.text_character_cells = character_cells.map(std::sync::Arc::new);
+ svg.text_segments = text_segments.map(std::sync::Arc::new);
+ svg.text_character_cells = character_cells;
});
let object_bounding_box = if is_text_content_box {
bounding_box.to_float_rect()
diff --git a/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs b/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs
index 85f9386d121..c670594a964 100644
--- a/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs
@@ -153,8 +153,22 @@ pub(crate) fn committed_svg_path(
arena.with_committed_fragment_link(slot, |link| link.and_then(|link| link.fragment.svg()?.path.clone()))
}
-/// The glyph cell of every code unit of a text content element's own character data, as its box
-/// committed them; None for any other box, and for a text box that has not been committed.
+/// The parts a text content element's path paints in, as its box committed them; None for a box whose path paints in
+/// one go.
+pub(crate) fn committed_svg_text_segments(
+ arena: &impl GeometryRead,
+ slot: NodeSlotId,
+) -> Option<std::sync::Arc<Vec<crate::layout::fragment_tree::SvgTextSegment>>> {
+ if arena.node_kind_if_live(slot) != Some(crate::layout::node_data::NodeKind::SVGTextBox) {
+ return None;
+ }
+ arena.with_committed_fragment_link(slot, |link| {
+ link.and_then(|link| link.fragment.svg()?.text_segments.clone())
+ })
+}
+
+/// The glyph cell of every code unit of the character data in a text content element's subtree, in document order, as
+/// its box committed them; None for any other box, and for a text box that has not been committed.
pub(crate) fn committed_svg_text_character_cells(
arena: &impl GeometryRead,
slot: NodeSlotId,
diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
index 28327370651..5586f2677fb 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
@@ -392,6 +392,89 @@ fn references_pattern<O: Observer>(recorder: &PaintRecorder<'_, O>, paintable: N
}
pub(crate) fn paint_path<O: Observer>(recorder: &mut PaintRecorder<'_, O>, paintable: NodeSlotId, phase: PaintPhase) {
+ paint_path_parts(recorder, paintable, phase, PathParts::BeforeChildren);
+}
+
+/// Which parts of a path to paint. A text content element paints in document order, so its text that follows a child
+/// element paints after that child, apart from the text before it.
+enum PathParts {
+ /// All of a path that paints in one go, or the parts that come before every child element.
+ BeforeChildren,
+ /// The parts in the given range of the parts the box committed.
+ Range(std::ops::Range<usize>),
+}
+
+/// How many parts the text content element `paintable` paints before its first child element; None where its path
+/// paints in one go.
+pub(crate) fn text_parts_before_children<O: Observer>(
+ recorder: &PaintRecorder<'_, O>,
+ paintable: NodeSlotId,
+) -> Option<usize> {
+ let segments = crate::painting::paintable_geometry::committed_svg_text_segments(recorder.source, paintable)?;
+ Some(
+ segments
+ .iter()
+ .take_while(|segment| segment.after_child.is_invalid())
+ .count(),
+ )
+}
+
+/// Paints the parts of the text content element `paintable` that follow `child`, one of its child elements.
+/// `next_part` is the first part that hasn't painted yet, which this moves past the parts it paints.
+pub(crate) fn paint_text_after_child<O: Observer>(
+ recorder: &mut PaintRecorder<'_, O>,
+ paintable: NodeSlotId,
+ child: NodeSlotId,
+ next_part: &mut usize,
+) {
+ let Some(segments) = crate::painting::paintable_geometry::committed_svg_text_segments(recorder.source, paintable)
+ else {
+ return;
+ };
+ let start = (*next_part).min(segments.len());
+ let end = start
+ + segments[start..]
+ .iter()
+ .take_while(|segment| segment.after_child == child)
+ .count();
+ if end > start {
+ paint_path_parts(
+ recorder,
+ paintable,
+ PaintPhase::Foreground,
+ PathParts::Range(start..end),
+ );
+ *next_part = end;
+ }
+}
+
+/// Paints the parts of the text content element `paintable` from `next_part` on: those left once its child elements
+/// have painted, which follow a child that didn't.
+pub(crate) fn paint_text_after_children<O: Observer>(
+ recorder: &mut PaintRecorder<'_, O>,
+ paintable: NodeSlotId,
+ next_part: usize,
+) {
+ let Some(segments) = crate::painting::paintable_geometry::committed_svg_text_segments(recorder.source, paintable)
+ else {
+ return;
+ };
+ if next_part < segments.len() {
+ paint_path_parts(
+ recorder,
+ paintable,
+ PaintPhase::Foreground,
+ PathParts::Range(next_part..segments.len()),
+ );
+ }
+}
+
+fn paint_path_parts<O: Observer>(
+ recorder: &mut PaintRecorder<'_, O>,
+ paintable: NodeSlotId,
+ phase: PaintPhase,
+ path_parts: PathParts,
+) {
let Some(computed_path) = crate::painting::paintable_geometry::committed_svg_path(recorder.source, paintable)
else {
return;
@@ -414,7 +497,9 @@ pub(crate) fn paint_path<O: Observer>(recorder: &mut PaintRecorder<'_, O>, paint
return;
}
- super::paint_base(recorder, paintable, phase);
+ if matches!(path_parts, PathParts::BeforeChildren) {
+ super::paint_base(recorder, paintable, phase);
+ }
if phase != PaintPhase::Foreground {
return;
@@ -424,109 +509,143 @@ pub(crate) fn paint_path<O: Observer>(recorder: &mut PaintRecorder<'_, O>, paint
// ratio; the visual context tree applies the viewport and element transforms at replay.
let device_scale = recorder.inputs.device_pixels_per_css_pixel as f32;
let paint_transform = [device_scale, 0.0, 0.0, device_scale, 0.0, 0.0];
- let path = computed_path.copy_transformed(paint_transform);
+ let segments = crate::painting::paintable_geometry::committed_svg_text_segments(recorder.source, paintable);
+ // Each part of the path to paint, with its bounding box in user units.
+ let parts: Vec<(libgfx_rust::path::Path, FloatRect)> = match &segments {
+ Some(segments) => {
+ let range = match path_parts {
+ PathParts::BeforeChildren => {
+ 0..segments
+ .iter()
+ .take_while(|segment| segment.after_child.is_invalid())
+ .count()
+ }
+ PathParts::Range(range) => range,
+ };
+ segments[range]
+ .iter()
+ .map(|segment| {
+ (
+ segment.path.copy_transformed(paint_transform),
+ FloatRect::from_array(segment.path.bounding_box()),
+ )
+ })
+ .collect()
+ }
+ None => vec![(
+ computed_path.copy_transformed(paint_transform),
+ FloatRect::from_array(computed_path.bounding_box()),
+ )],
+ };
let anti_alias = should_anti_alias(facts.should_anti_alias);
if recorder.draws_clip_path_geometry() {
// https://drafts.fxtf.org/css-masking/#ClipPathElement: the raw geometry of each child
// element, exclusive of rendering properties, defines a 1-bit mask.
- recorder.recorder.fill_path(FillPathParams {
- force_dark_role: ForceDarkRole::Svg,
- path: &path,
- opacity: 1.0,
- paint_style_or_color: PaintStyleOrColor::Color(Color::from_rgb(0, 0, 0)),
- winding_rule: WindingRule::from_raw(facts.clip_rule_winding),
- should_anti_alias: anti_alias,
- });
+ for (path, _) in &parts {
+ recorder.recorder.fill_path(FillPathParams {
+ force_dark_role: ForceDarkRole::Svg,
+ path,
+ opacity: 1.0,
+ paint_style_or_color: PaintStyleOrColor::Color(Color::from_rgb(0, 0, 0)),
+ winding_rule: WindingRule::from_raw(facts.clip_rule_winding),
+ should_anti_alias: anti_alias,
+ });
+ }
return;
}
let geometry =
crate::painting::paintable_geometry::committed_svg_geometry(recorder.source, paintable).unwrap_or_default();
- let paint_context = SvgPaintContext {
- viewport: geometry.viewport_user_rect,
- path_bounding_box: FloatRect::from_array(computed_path.bounding_box()),
- object_bounding_box: geometry.object_bounding_box,
- paint_transform: affine(paint_transform),
- content_scale: recorder.own_accumulated_2d_scale(paintable),
- };
-
- for index in 0..facts.paint_order_count as usize {
- match facts.paint_order[index] {
- paint_order::FILL => {
- let fill_opacity = facts.fill_opacity;
- let fill_winding = WindingRule::from_raw(facts.fill_winding);
- if let Some(paint_style) = paint_server_style(recorder, paintable, false, &paint_context) {
- recorder.recorder.fill_path(FillPathParams {
- force_dark_role: ForceDarkRole::Svg,
- path: &path,
- opacity: fill_opacity,
- paint_style_or_color: PaintStyleOrColor::PaintStyle(paint_style),
- winding_rule: fill_winding,
- should_anti_alias: anti_alias,
- });
- } else if let Some(fill_color) = facts.fill_color {
- recorder.recorder.fill_path(FillPathParams {
- force_dark_role: ForceDarkRole::Svg,
- path: &path,
- opacity: 1.0,
- paint_style_or_color: PaintStyleOrColor::Color(Color(fill_color).with_opacity(fill_opacity)),
- winding_rule: fill_winding,
- should_anti_alias: anti_alias,
- });
- }
- }
- paint_order::STROKE => {
- // https://svgwg.org/svg2-draft/painting.html#PaintingVectorEffects
- // With the non-scaling-stroke vector effect, stroke outline shall be calculated in
- // the "host" coordinate space instead of user coordinate system.
- let mut stroke_scale = device_scale;
- if facts.non_scaling_stroke {
- let accumulated_scale = recorder.own_accumulated_2d_scale(paintable);
- let accumulated_scale_area = accumulated_scale.width * accumulated_scale.height;
- if accumulated_scale_area > 0.0 {
- stroke_scale = device_scale / accumulated_scale_area.sqrt();
+ for (path, path_bounding_box) in &parts {
+ // NB: A paint server is placed from the bounding box of the path it paints, so each part is painted with its
+ // own.
+ let paint_context = SvgPaintContext {
+ viewport: geometry.viewport_user_rect,
+ path_bounding_box: *path_bounding_box,
+ object_bounding_box: geometry.object_bounding_box,
+ paint_transform: affine(paint_transform),
+ content_scale: recorder.own_accumulated_2d_scale(paintable),
+ };
+ for index in 0..facts.paint_order_count as usize {
+ match facts.paint_order[index] {
+ paint_order::FILL => {
+ let fill_opacity = facts.fill_opacity;
+ let fill_winding = WindingRule::from_raw(facts.fill_winding);
+ if let Some(paint_style) = paint_server_style(recorder, paintable, false, &paint_context) {
+ recorder.recorder.fill_path(FillPathParams {
+ force_dark_role: ForceDarkRole::Svg,
+ path,
+ opacity: fill_opacity,
+ paint_style_or_color: PaintStyleOrColor::PaintStyle(paint_style),
+ winding_rule: fill_winding,
+ should_anti_alias: anti_alias,
+ });
+ } else if let Some(fill_color) = facts.fill_color {
+ recorder.recorder.fill_path(FillPathParams {
+ force_dark_role: ForceDarkRole::Svg,
+ path,
+ opacity: 1.0,
+ paint_style_or_color: PaintStyleOrColor::Color(
+ Color(fill_color).with_opacity(fill_opacity),
+ ),
+ winding_rule: fill_winding,
+ should_anti_alias: anti_alias,
+ });
}
}
- let stroke_thickness = facts.stroke_width * stroke_scale;
- let stroke_dasharray: Vec<f32> = dash_array.iter().map(|value| value * stroke_scale).collect();
- let stroke_dashoffset = facts.stroke_dashoffset * stroke_scale;
- let stroke_opacity = facts.stroke_opacity;
-
- if let Some(paint_style) = paint_server_style(recorder, paintable, true, &paint_context) {
- recorder.recorder.stroke_path(StrokePathParams {
- force_dark_role: ForceDarkRole::Svg,
- cap_style: facts.cap_style,
- join_style: facts.join_style,
- miter_limit: facts.miter_limit,
- dash_array: stroke_dasharray,
- dash_offset: stroke_dashoffset,
- path: &path,
- opacity: stroke_opacity,
- paint_style_or_color: PaintStyleOrColor::PaintStyle(paint_style),
- thickness: stroke_thickness,
- should_anti_alias: anti_alias,
- });
- } else if let Some(stroke_color) = facts.stroke_color {
- recorder.recorder.stroke_path(StrokePathParams {
- force_dark_role: ForceDarkRole::Svg,
- cap_style: facts.cap_style,
- join_style: facts.join_style,
- miter_limit: facts.miter_limit,
- dash_array: stroke_dasharray,
- dash_offset: stroke_dashoffset,
- path: &path,
- opacity: 1.0,
- paint_style_or_color: PaintStyleOrColor::Color(
- Color(stroke_color).with_opacity(stroke_opacity),
- ),
- thickness: stroke_thickness,
- should_anti_alias: anti_alias,
- });
+ paint_order::STROKE => {
+ // https://svgwg.org/svg2-draft/painting.html#PaintingVectorEffects
+ // With the non-scaling-stroke vector effect, stroke outline shall be calculated in
+ // the "host" coordinate space instead of user coordinate system.
+ let mut stroke_scale = device_scale;
+ if facts.non_scaling_stroke {
+ let accumulated_scale = recorder.own_accumulated_2d_scale(paintable);
+ let accumulated_scale_area = accumulated_scale.width * accumulated_scale.height;
+ if accumulated_scale_area > 0.0 {
+ stroke_scale = device_scale / accumulated_scale_area.sqrt();
+ }
+ }
+ let stroke_thickness = facts.stroke_width * stroke_scale;
+ let stroke_dasharray: Vec<f32> = dash_array.iter().map(|value| value * stroke_scale).collect();
+ let stroke_dashoffset = facts.stroke_dashoffset * stroke_scale;
+ let stroke_opacity = facts.stroke_opacity;
+
+ if let Some(paint_style) = paint_server_style(recorder, paintable, true, &paint_context) {
+ recorder.recorder.stroke_path(StrokePathParams {
+ force_dark_role: ForceDarkRole::Svg,
+ cap_style: facts.cap_style,
+ join_style: facts.join_style,
+ miter_limit: facts.miter_limit,
+ dash_array: stroke_dasharray,
+ dash_offset: stroke_dashoffset,
+ path,
+ opacity: stroke_opacity,
+ paint_style_or_color: PaintStyleOrColor::PaintStyle(paint_style),
+ thickness: stroke_thickness,
+ should_anti_alias: anti_alias,
+ });
+ } else if let Some(stroke_color) = facts.stroke_color {
+ recorder.recorder.stroke_path(StrokePathParams {
+ force_dark_role: ForceDarkRole::Svg,
+ cap_style: facts.cap_style,
+ join_style: facts.join_style,
+ miter_limit: facts.miter_limit,
+ dash_array: stroke_dasharray,
+ dash_offset: stroke_dashoffset,
+ path,
+ opacity: 1.0,
+ paint_style_or_color: PaintStyleOrColor::Color(
+ Color(stroke_color).with_opacity(stroke_opacity),
+ ),
+ thickness: stroke_thickness,
+ should_anti_alias: anti_alias,
+ });
+ }
}
+ // FIXME: Implement marker painting
+ _ => {}
}
- // FIXME: Implement marker painting
- _ => {}
}
}
}
diff --git a/Libraries/LibWeb/Rust/src/painting/record/svg_resources.rs b/Libraries/LibWeb/Rust/src/painting/record/svg_resources.rs
index f6ee3dafce4..67dd8a15986 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/svg_resources.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/svg_resources.rs
@@ -9,7 +9,7 @@ use crate::layout::node_data::{NodeKind, NodeSlotId};
use crate::painting::display_list::builder::PendingInlineClip;
use crate::painting::display_list::commands::ContextRef;
use crate::painting::display_list::recorder::{IsolatedGroupEffects, OpenRecorderGroup};
-use crate::painting::paint_read::PaintRead;
+use crate::painting::paint_read::{GeometryRead, PaintRead};
use crate::painting::record::order_tree::ProducerKind;
use crate::painting::record::trace::{Action, Observer, Operation};
use crate::painting::record::{PaintPhase, PaintRecorder};
@@ -386,9 +386,24 @@ impl<O: Observer> PaintRecorder<'_, O> {
self.recorder
.set_ambient_inline_transform(Some(descendants_to_enclosing_space));
let mut child = crate::painting::paint_order::first_paint_child(self.source, svg_box);
+ let mut next_text_part = if self.source.node_kind_if_live(svg_box) == Some(NodeKind::SVGTextBox) {
+ crate::painting::record::paint::svg::text_parts_before_children(self, svg_box)
+ } else {
+ None
+ };
while let Some(current) = child {
child = crate::painting::paint_order::next_paint_sibling(self.source, current);
self.paint_svg_box_inside_resource(current, descendants_to_enclosing_space, true);
+ if let Some(next_text_part) = &mut next_text_part {
+ self.recorder.set_ambient_inline_transform(Some(to_enclosing_space));
+ crate::painting::record::paint::svg::paint_text_after_child(self, svg_box, current, next_text_part);
+ self.recorder
+ .set_ambient_inline_transform(Some(descendants_to_enclosing_space));
+ }
+ }
+ if let Some(next_text_part) = next_text_part {
+ self.recorder.set_ambient_inline_transform(Some(to_enclosing_space));
+ crate::painting::record::paint::svg::paint_text_after_children(self, svg_box, next_text_part);
}
self.recorder.truncate_ambient_inline_clips(clip_depth);
self.recorder.set_ambient_inline_transform(enclosing_transform);
diff --git a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs b/Libraries/LibWeb/Rust/src/painting/record/traversal.rs
index e9204b97864..cc6acc377b5 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/traversal.rs
@@ -512,14 +512,33 @@ impl<O: Observer> PaintRecorder<'_, O> {
}
fn svg_paint_descendants(&mut self, paintable: NodeSlotId) {
+ // A text content element paints in document order: its text that follows a child element paints after that
+ // child.
+ // FIXME: Hit testing still tests all of the element's own text after its child elements.
+ let is_text_box =
+ self.source.node_kind_if_live(paintable) == Some(crate::layout::node_data::NodeKind::SVGTextBox);
+ let mut next_text_part = if is_text_box {
+ crate::painting::record::paint::svg::text_parts_before_children(self, paintable)
+ } else {
+ None
+ };
let mut next_child = crate::painting::paint_order::first_paint_child(self.source, paintable);
while let Some(child) = next_child {
next_child = crate::painting::paint_order::next_paint_sibling(self.source, child);
// A child that establishes a stacking context is painted by that context.
- if self.has_stacking_context(child) {
- continue;
+ if !self.has_stacking_context(child) {
+ self.paint_svg_box(child);
}
- self.paint_svg_box(child);
+ if let Some(next_text_part) = &mut next_text_part {
+ let context = self.own_context(paintable);
+ self.recorder.set_accumulated_visual_context(context);
+ crate::painting::record::paint::svg::paint_text_after_child(self, paintable, child, next_text_part);
+ }
+ }
+ if let Some(next_text_part) = next_text_part {
+ let context = self.own_context(paintable);
+ self.recorder.set_accumulated_visual_context(context);
+ crate::painting::record::paint::svg::paint_text_after_children(self, paintable, next_text_part);
}
}
diff --git a/Libraries/LibWeb/SVG/SVGTextContentElement.cpp b/Libraries/LibWeb/SVG/SVGTextContentElement.cpp
index 839749b87c3..268f72ab917 100644
--- a/Libraries/LibWeb/SVG/SVGTextContentElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGTextContentElement.cpp
@@ -28,10 +28,9 @@ SVGTextContentElement::SVGTextContentElement(DOM::Document& document, DOM::Quali
// A character that is addressable by text positioning attributes and SVG DOM text methods.
// Characters discarded during layout such as collapsed white space characters are not addressable, neither are
// characters within an element with a value of none for the display property.
-// Layout commits one cell per code unit of each rendered text content element's own character data, after processing
-// its white space. An element that isn't rendered has no committed box, and so no cells at all.
-// AD-HOC: Layout shapes an element's own character data as one run ahead of its text content children, so the cells
-// come in that order rather than in document order when text and child elements interleave.
+// Layout commits one cell per code unit of the character data in each rendered text content element's subtree, in
+// document order, after processing its white space. An element that isn't rendered has no committed box, and so no
+// cells at all.
Vector<Layout::RustFFI::FfiSvgTextCharacterCell> SVGTextContentElement::character_cells()
{
Layout::ForcedReadScope read { document() };
@@ -40,22 +39,8 @@ Vector<Layout::RustFFI::FfiSvgTextCharacterCell> SVGTextContentElement::characte
auto const* layout_node = this->layout_node(read);
if (!layout_node)
return cells;
- auto collect = [&cells](auto& self, Layout::Node const& node) -> void {
- if (!Painting::has_committed_box(node))
- return;
- cells.extend(Painting::svg_text_character_cells(node));
- for (auto const* child = node.first_child_ptr(); child; child = child->next_sibling_ptr()) {
- switch (child->kind()) {
- case Layout::RustFFI::NodeKind::SVGTextBox:
- case Layout::RustFFI::NodeKind::SVGTextPathBox:
- self(self, *child);
- break;
- default:
- break;
- }
- }
- };
- collect(collect, *layout_node);
+ if (Painting::has_committed_box(*layout_node))
+ cells = Painting::svg_text_character_cells(*layout_node);
return cells;
}
diff --git a/Libraries/LibWeb/SVG/SVGTextElement.cpp b/Libraries/LibWeb/SVG/SVGTextElement.cpp
index 71411969178..4cb49913f59 100644
--- a/Libraries/LibWeb/SVG/SVGTextElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGTextElement.cpp
@@ -19,6 +19,11 @@ SVGTextElement::SVGTextElement(DOM::Document& document, DOM::QualifiedName quali
CSS::ElementBoxKind SVGTextElement::box_kind() const
{
+ // https://svgwg.org/svg2-draft/text.html#TextLayoutAlgorithm
+ // The used value of the 'display' property on an element that is a descendant of a text content block element and
+ // is not a correctly parented text content child element or 'a' element must be none.
+ if (first_flat_tree_ancestor_of_type<SVGTextElement>())
+ return CSS::ElementBoxKind::NoBox;
return CSS::ElementBoxKind::SvgText;
}
diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/whitespace-only-text-boxes.txt b/Tests/LibWeb/Layout/expected/block-and-inline/whitespace-only-text-boxes.txt
index f5b1bb8ac7d..fe339bedca4 100644
--- a/Tests/LibWeb/Layout/expected/block-and-inline/whitespace-only-text-boxes.txt
+++ b/Tests/LibWeb/Layout/expected/block-and-inline/whitespace-only-text-boxes.txt
@@ -153,12 +153,12 @@ Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children
"b"
TextNode <#text> (not painted)
SVGSVGBox <svg#svg-text> at [8,528] [0+0+0 50 0+0+734] [0+0+0 20 0+0+0] viewport-transform=[1 0 0 1 0 0] [SVG] children: not-inline
- SVGTextBox <text> at [0,2.203125] [0+0+0 27.703125 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <text> at [0,2.203125] [0+0+0 43.703125 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [9.34375,2.203125] [0+0+0 9.46875 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <tspan> at [17.34375,2.203125] [0+0+0 9.46875 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [18.8125,2.203125] [0+0+0 8.890625 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <tspan> at [34.8125,2.203125] [0+0+0 8.890625 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
BlockContainer <div#abspos> at [8,564] positioned [0+0+0 784 0+0+0] [0+0+0 48 0+0+0] children: not-inline
BlockContainer <p> at [8,564] [0+0+0 784 0+0+0] [16+0+0 16 0+0+16] children: inline
diff --git a/Tests/LibWeb/Layout/expected/svg/svg-text-positioning.txt b/Tests/LibWeb/Layout/expected/svg/svg-text-positioning.txt
index 3425bc26f35..4f3255365ce 100644
--- a/Tests/LibWeb/Layout/expected/svg/svg-text-positioning.txt
+++ b/Tests/LibWeb/Layout/expected/svg/svg-text-positioning.txt
@@ -4,15 +4,15 @@ Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children
frag 0 from SVGSVGBox start: 0, length: 0, rect: [8,8 300x120] baseline: 120
SVGSVGBox <svg> at [8,8] [0+0+0 300 0+0+0] [0+0+0 120 0+0+0] viewport-transform=[1 0 0 1 0 0] [SVG] children: not-inline
SVGGeometryBox <rect> at [0,0] [0+0+0 300 0+0+0] [0+0+0 120 0+0+0] children: not-inline
- SVGTextBox <text> at [40,13.609375] [0+0+0 193.53125 0+0+0] [0+0+0 87 0+0+0] children: inline
+ SVGTextBox <text> at [40,13.609375] [0+0+0 221.53125 0+0+0] [0+0+0 87 0+0+0] children: inline
TextNode <#text> (not painted)
SVGTextBox <tspan> at [40,13.609375] [0+0+0 47.515625 0+0+0] [0+0+0 28 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [107.515625,37.609375] [0+0+0 48.390625 0+0+0] [0+0+0 28 0+0+0] children: inline
+ SVGTextBox <tspan> at [121.515625,37.609375] [0+0+0 48.390625 0+0+0] [0+0+0 28 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [185.90625,72.609375] [0+0+0 47.625 0+0+0] [0+0+0 28 0+0+0] children: inline
+ SVGTextBox <tspan> at [213.90625,72.609375] [0+0+0 47.625 0+0+0] [0+0+0 28 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
TextNode <#text> (not painted)
diff --git a/Tests/LibWeb/Layout/expected/tree-builder/svg-text-tspan-textpath.txt b/Tests/LibWeb/Layout/expected/tree-builder/svg-text-tspan-textpath.txt
index c63a4c76010..fc061b2f4f9 100644
--- a/Tests/LibWeb/Layout/expected/tree-builder/svg-text-tspan-textpath.txt
+++ b/Tests/LibWeb/Layout/expected/tree-builder/svg-text-tspan-textpath.txt
@@ -3,12 +3,12 @@ Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children
BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 103 0+0+8] children: inline
frag 0 from SVGSVGBox start: 0, length: 0, rect: [8,8 300x100] baseline: 100
SVGSVGBox <svg> at [8,8] [0+0+0 300 0+0+0] [0+0+0 100 0+0+0] viewport-transform=[1 0 0 1 0 0] [SVG] children: not-inline
- SVGTextBox <text> at [10,7.203125] [0+0+0 143.484375 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <text> at [10,7.203125] [0+0+0 159.484375 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [82.78125,7.203125] [0+0+0 44.578125 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <tspan> at [57.78125,7.203125] [0+0+0 44.578125 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
- SVGTextBox <a> at [127.359375,7.203125] [0+0+0 26.125 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <a> at [110.359375,7.203125] [0+0+0 26.125 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
SVGTextBox <text> at [10.921875,67.6875] [0+0+0 79.453125 0+0+0] [0+0+0 13.0625 0+0+0] children: not-inline
diff --git a/Tests/LibWeb/Layout/expected/tree-builder/whitespace-in-svg-text-and-textpath.txt b/Tests/LibWeb/Layout/expected/tree-builder/whitespace-in-svg-text-and-textpath.txt
index c6ac1ffd4da..34469443e6b 100644
--- a/Tests/LibWeb/Layout/expected/tree-builder/whitespace-in-svg-text-and-textpath.txt
+++ b/Tests/LibWeb/Layout/expected/tree-builder/whitespace-in-svg-text-and-textpath.txt
@@ -5,12 +5,12 @@ Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children
SVGSVGBox <svg> at [8,8] [0+0+0 300 0+0+0] [0+0+0 100 0+0+0] viewport-transform=[1 0 0 1 0 0] [SVG] children: not-inline
SVGGraphicsBox <g> at [0,0] [0+0+0 5 0+0+0] [0+0+0 5 0+0+0] children: not-inline
SVGGeometryBox <rect> at [0,0] [0+0+0 5 0+0+0] [0+0+0 5 0+0+0] children: not-inline
- SVGTextBox <text> at [10,7.203125] [0+0+0 18.8125 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <text> at [10,7.203125] [0+0+0 26.8125 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
SVGTextBox <tspan> at [10,7.203125] [0+0+0 9.34375 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
- SVGTextBox <tspan> at [19.34375,7.203125] [0+0+0 9.46875 0+0+0] [0+0+0 16 0+0+0] children: inline
+ SVGTextBox <tspan> at [27.34375,7.203125] [0+0+0 9.46875 0+0+0] [0+0+0 16 0+0+0] children: inline
TextNode <#text> (not painted)
TextNode <#text> (not painted)
SVGTextBox <text> at [10.8125,72.125] [0+0+0 7 0+0+0] [0+0+0 7.28125 0+0+0] children: not-inline
diff --git a/Tests/LibWeb/Ref/expected/svg-text-paints-in-document-order-ref.html b/Tests/LibWeb/Ref/expected/svg-text-paints-in-document-order-ref.html
new file mode 100644
index 00000000000..0f79e7a8286
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg-text-paints-in-document-order-ref.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<style>
+ body {
+ margin: 0;
+ }
+ @font-face {
+ font-family: Ahem;
+ src: url("../data/fonts/Ahem.ttf");
+ }
+ svg {
+ display: block;
+ font: 20px Ahem;
+ }
+</style>
+<svg width="200" height="200">
+ <rect x="17" y="41" width="46" height="26" fill="red" />
+ <rect x="20" y="44" width="40" height="20" fill="green" />
+ <rect x="17" y="101" width="46" height="26" fill="green" />
+ <linearGradient id="gradient" gradientUnits="userSpaceOnUse" x1="20" x2="140">
+ <stop offset="0" stop-color="blue" />
+ <stop offset="1" stop-color="yellow" />
+ </linearGradient>
+ <text x="20" y="180" fill="url(#gradient)">XXXXXX</text>
+</svg>
diff --git a/Tests/LibWeb/Ref/input/svg-text-paints-in-document-order.html b/Tests/LibWeb/Ref/input/svg-text-paints-in-document-order.html
new file mode 100644
index 00000000000..ada515b2ebd
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg-text-paints-in-document-order.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<link rel="match" href="../expected/svg-text-paints-in-document-order-ref.html" />
+<style>
+ @font-face {
+ font-family: Ahem;
+ src: url("../data/fonts/Ahem.ttf");
+ }
+ body {
+ margin: 0;
+ }
+ svg {
+ display: block;
+ font: 20px Ahem;
+ }
+</style>
+<svg width="200" height="200">
+ <!-- Text that follows a <tspan> paints over that <tspan>. -->
+ <text x="20" y="60" fill="green"><tspan fill="red" stroke="red" stroke-width="6">XX</tspan><tspan x="20">X</tspan>X</text>
+ <!-- Text that comes before a <tspan> paints under it. -->
+ <text x="20" y="120" fill="red">XX<tspan x="20" fill="green" stroke="green" stroke-width="6">XX</tspan></text>
+ <!-- A gradient runs across the text before and after a <tspan> as it does across text in one piece. -->
+ <linearGradient id="gradient" gradientUnits="userSpaceOnUse" x1="20" x2="140">
+ <stop offset="0" stop-color="blue" />
+ <stop offset="1" stop-color="yellow" />
+ </linearGradient>
+ <text x="20" y="180" fill="url(#gradient)">XX<tspan>XX</tspan>XX</text>
+</svg>
diff --git a/Tests/LibWeb/Text/expected/SVG/text-and-tspans-in-document-order.txt b/Tests/LibWeb/Text/expected/SVG/text-and-tspans-in-document-order.txt
new file mode 100644
index 00000000000..e6e12f19c15
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/text-and-tspans-in-document-order.txt
@@ -0,0 +1,17 @@
+interleaved: 6 characters, length 120: 10,14 30,14 50,14 70,14 90,14 110,14; box 10,14 120x20
+interleaved-tspan: 2 characters, length 40: 50,14 70,14; box 50,14 40x20
+nested: 5 characters, length 100: 10,44 40,49 60,44 80,44 100,44; box 10,44 110x25
+nested-outer: 3 characters, length 60: 40,49 60,44 80,44; box 40,44 60x25
+nested-inner: 1 characters, length 20: 60,44; box 60,44 20x20
+anchor-middle: 6 characters, length 120: 240,74 260,74 280,74 300,74 320,74 340,74; box 240,74 120x20
+anchor-middle-tspan: 2 characters, length 40: 280,74 300,74; box 280,74 40x20
+anchor-end-two-chunks: 6 characters, length 120: 260,104 280,104 220,104 240,104 260,104 280,104; box 220,104 80x20
+anchor-end-tspan: 2 characters, length 40: 220,104 240,104; box 220,104 40x20
+chunk-in-nested-tspan: 6 characters, length 120: 270,134 290,134 310,134 270,134 290,134 310,134; box 270,134 60x20
+chunk-outer: 4 characters, length 80: 270,134 290,134 310,134 270,134; box 270,134 60x20
+chunk-inner: 1 characters, length 20: 270,134; box 270,134 20x20
+empty-tspan-with-x: 2 characters, length 40: 10,164 30,164; box 10,164 40x20
+empty-tspan: 0 characters, length 0: ; box 0,0 0x0
+empty-tspan-in-chunk: 4 characters, length 80: 260,194 280,194 300,194 320,194; box 260,194 80x20
+hidden-tspan: 2 characters, length 40: 10,224 30,224; box 10,224 40x20
+other-elements: 3 characters, length 60: 10,254 30,254 50,254; box 10,254 60x20
diff --git a/Tests/LibWeb/Text/expected/SVG/text-in-a-link.txt b/Tests/LibWeb/Text/expected/SVG/text-in-a-link.txt
index ec6e0c84bae..61bdd6fd7b8 100644
--- a/Tests/LibWeb/Text/expected/SVG/text-in-a-link.txt
+++ b/Tests/LibWeb/Text/expected/SVG/text-in-a-link.txt
@@ -1,6 +1,21 @@
+link: 9 characters, length 180: 10,14 30,14 50,14 70,14 90,14 110,14 130,14 150,14 170,14; box 10,14 180x20
+link-a: box 70,14 80x20
+link-in-tspan: 4 characters, length 80: 10,44 30,44 50,44 70,44; box 10,44 80x20
+link-in-tspan-tspan: 2 characters, length 40: 30,44 50,44; box 30,44 40x20
+link-in-tspan-a: box 30,44 20x20
+tspan-in-link: 5 characters, length 100: 10,74 30,74 50,74 70,74 90,74; box 10,74 100x20
+tspan-in-link-a: box 30,74 60x20
+tspan-in-link-tspan: 1 characters, length 20: 50,74; box 50,74 20x20
+link-with-anchor: 6 characters, length 120: 240,104 260,104 280,104 300,104 320,104 340,104; box 240,104 120x20
+link-with-anchor-a: box 280,104 40x20
link-around-text: box 10,134 40x20
text-in-link: 2 characters, length 40: 10,134 30,134; box 10,134 40x20
link-last: 6 characters, length 120: 10,164 30,164 50,164 70,164 90,164 110,164; box 10,164 120x20
link-last-a: box 50,164 80x20
elementFromPoint(80, 170): link-last-a
elementFromPoint(20, 170): link-last
+elementFromPoint(80, 20): link-a
+elementFromPoint(20, 20): link
+elementFromPoint(40, 50): link-in-tspan-a
+elementFromPoint(60, 80): tspan-in-link-tspan
+elementFromPoint(300, 110): link-with-anchor-a
diff --git a/Tests/LibWeb/Text/expected/SVG/text-white-space-across-elements.txt b/Tests/LibWeb/Text/expected/SVG/text-white-space-across-elements.txt
new file mode 100644
index 00000000000..a88fc339750
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/text-white-space-across-elements.txt
@@ -0,0 +1,24 @@
+space-before-tspan: 3 characters, length 60: 10,14 30,14 50,14; box 10,14 60x20
+space-before-tspan-child: 1 characters, length 20: 50,14; box 50,14 20x20
+space-between-tspans: 3 characters, length 60: 10,44 30,44 50,44; box 10,44 60x20
+between-first: 1 characters, length 20: 10,44; box 10,44 20x20
+between-second: 1 characters, length 20: 50,44; box 50,44 20x20
+space-in-both-tspans: 3 characters, length 60: 10,74 30,74 50,74; box 10,74 60x20
+both-first: 2 characters, length 40: 10,74 30,74; box 10,74 40x20
+both-second: 1 characters, length 20: 50,74; box 50,74 20x20
+spaces-everywhere: 5 characters, length 100: 10,104 30,104 50,104 70,104 90,104; box 10,104 100x20
+spaces-everywhere-child: 2 characters, length 40: 50,104 70,104; box 50,104 40x20
+word-per-tspan: 3 characters, length 60: 10,134 30,134 100,134; box 10,134 110x20
+word-first: 1 characters, length 20: 10,134; box 10,134 20x20
+word-second: 1 characters, length 20: 100,134; box 100,134 20x20
+space-before-chunk: 3 characters, length 60: 10,164 30,164 100,164; box 10,164 110x20
+space-before-chunk-child: 1 characters, length 20: 100,164; box 100,164 20x20
+space-across-empty-tspan: 3 characters, length 60: 10,194 30,194 50,194; box 10,194 60x20
+xml-space-preserve: 9 characters, length 180: 10,224 30,224 50,224 70,224 90,224 110,224 130,224 150,224 170,224; box 10,224 180x20
+xml-space-preserve-child: 3 characters, length 60: 70,224 90,224 110,224; box 70,224 60x20
+preserved-tspan: 9 characters, length 180: 10,254 30,254 50,254 70,254 90,254 110,254 130,254 150,254 170,254; box 10,254 180x20
+preserved-tspan-child: 5 characters, length 100: 50,254 70,254 90,254 110,254 130,254; box 50,254 100x20
+collapsing-tspan: 9 characters, length 180: 10,284 30,284 50,284 70,284 90,284 110,284 130,284 150,284 170,284; box 10,284 180x20
+collapsing-tspan-child: 3 characters, length 60: 70,284 90,284 110,284; box 70,284 60x20
+only-white-space: 0 characters, length 0: ; box 0,0 0x0
+only-white-space-child: 0 characters, length 0: ; box 0,0 0x0
diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getextentofchar.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getextentofchar.txt
new file mode 100644
index 00000000000..dcb29f87d22
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getextentofchar.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 2 tests
+
+1 Pass
+1 Fail
+Fail Multiple chunks in a tspan
+Pass With dominant-baseline
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getnumberofchars.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getnumberofchars.txt
new file mode 100644
index 00000000000..ada24792525
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/getnumberofchars.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 4 tests
+
+4 Pass
+Pass latin text
+Pass latin text and tspan
+Pass mixed-rtl text and tspan
+Pass mixed-rtl text and tested tspan
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/SVG/text-and-tspans-in-document-order.html b/Tests/LibWeb/Text/input/SVG/text-and-tspans-in-document-order.html
new file mode 100644
index 00000000000..2d0d9afdc6f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/text-and-tspans-in-document-order.html
@@ -0,0 +1,50 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @font-face {
+ font-family: Ahem;
+ src: url("../../../Ref/data/fonts/Ahem.ttf");
+ }
+ body {
+ margin: 0;
+ }
+ svg {
+ display: block;
+ font: 20px Ahem;
+ }
+</style>
+<svg width="800" height="300">
+ <text id="interleaved" x="10" y="30">AB<tspan id="interleaved-tspan">CD</tspan>EF</text>
+ <text id="nested" x="10" y="60">A<tspan id="nested-outer" dx="10" dy="5">B<tspan id="nested-inner" dy="-5">C</tspan>D</tspan>E</text>
+ <text id="anchor-middle" x="300" y="90" text-anchor="middle">AB<tspan id="anchor-middle-tspan">CD</tspan>EF</text>
+ <text id="anchor-end-two-chunks" x="300" y="120" text-anchor="end">AB<tspan id="anchor-end-tspan" x="300">CD</tspan>EF</text>
+ <text id="chunk-in-nested-tspan" x="300" y="150" text-anchor="middle"><tspan id="chunk-outer">ABC<tspan id="chunk-inner" x="300">D</tspan></tspan>EF</text>
+ <text id="empty-tspan-with-x" x="10" y="180">A<tspan id="empty-tspan" x="100" dy="50"></tspan>B</text>
+ <text id="empty-tspan-in-chunk" x="300" y="210" text-anchor="middle">AB<tspan x="100"></tspan>CD</text>
+ <text id="hidden-tspan" x="10" y="240">A<tspan style="display: none" x="100">X</tspan>B</text>
+ <text id="other-elements" x="10" y="270">A<g>G</g><rect width="5" height="5" />B<text>T</text>C</text>
+</svg>
+<script>
+ const round = value => Math.round(value * 100) / 100;
+ const characters = element => {
+ const positions = [];
+ for (let index = 0; index < element.getNumberOfChars(); ++index) {
+ const cell = element.getExtentOfChar(index);
+ positions.push(`${round(cell.x)},${round(cell.y)}`);
+ }
+ return `${positions.length} characters, length ${round(element.getComputedTextLength())}: ${positions.join(" ")}`;
+ };
+ const box = element => {
+ const rect = element.getBBox();
+ return `${round(rect.x)},${round(rect.y)} ${round(rect.width)}x${round(rect.height)}`;
+ };
+
+ asyncTest(async done => {
+ await document.fonts.load("20px Ahem");
+ for (const element of document.querySelectorAll("svg [id]")) {
+ const queries = element.getNumberOfChars ? `${characters(element)}; ` : "";
+ println(`${element.id}: ${queries}box ${box(element)}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/text-in-a-link.html b/Tests/LibWeb/Text/input/SVG/text-in-a-link.html
index 64b1c745c89..156b29f02c4 100644
--- a/Tests/LibWeb/Text/input/SVG/text-in-a-link.html
+++ b/Tests/LibWeb/Text/input/SVG/text-in-a-link.html
@@ -14,6 +14,10 @@
}
</style>
<svg width="800" height="200">
+ <text id="link" x="10" y="30">S: <a id="link-a" href="#">LINK</a> E</text>
+ <text id="link-in-tspan" x="10" y="60">S<tspan id="link-in-tspan-tspan"><a id="link-in-tspan-a" href="#">L</a>M</tspan>E</text>
+ <text id="tspan-in-link" x="10" y="90">A<a id="tspan-in-link-a" href="#"> <tspan id="tspan-in-link-tspan">B</tspan> </a>C</text>
+ <text id="link-with-anchor" x="300" y="120" text-anchor="middle">AB<a id="link-with-anchor-a" href="#">CD</a>EF</text>
<a id="link-around-text" href="#"><text id="text-in-link" x="10" y="150">AB</text></a>
<text id="link-last" x="10" y="180">S:<a id="link-last-a" href="#">LINK</a></text>
</svg>
@@ -40,7 +44,7 @@
}
// The link's text is what a click on it lands on.
const svg = document.querySelector("svg").getBoundingClientRect();
- for (const [x, y] of [[80, 170], [20, 170]]) {
+ for (const [x, y] of [[80, 170], [20, 170], [80, 20], [20, 20], [40, 50], [60, 80], [300, 110]]) {
const hit = document.elementFromPoint(svg.x + x, svg.y + y);
println(`elementFromPoint(${x}, ${y}): ${hit.id || hit.localName}`);
}
diff --git a/Tests/LibWeb/Text/input/SVG/text-white-space-across-elements.html b/Tests/LibWeb/Text/input/SVG/text-white-space-across-elements.html
new file mode 100644
index 00000000000..e3124da1232
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/text-white-space-across-elements.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @font-face {
+ font-family: Ahem;
+ src: url("../../../Ref/data/fonts/Ahem.ttf");
+ }
+ body {
+ margin: 0;
+ }
+ svg {
+ display: block;
+ font: 20px Ahem;
+ }
+</style>
+<svg width="800" height="400">
+ <text id="space-before-tspan" x="10" y="30">A <tspan id="space-before-tspan-child"> B</tspan></text>
+ <text id="space-between-tspans" x="10" y="60"><tspan id="between-first">A</tspan> <tspan id="between-second">B</tspan></text>
+ <text id="space-in-both-tspans" x="10" y="90"><tspan id="both-first">A </tspan><tspan id="both-second"> B</tspan></text>
+ <text id="spaces-everywhere" x="10" y="120"> A <tspan id="spaces-everywhere-child"> B </tspan> C </text>
+ <text id="word-per-tspan" x="10" y="150">
+ <tspan id="word-first" x="10">A</tspan>
+ <tspan id="word-second" x="100">B</tspan>
+ </text>
+ <text id="space-before-chunk" x="10" y="180">A <tspan id="space-before-chunk-child" x="100"> B</tspan></text>
+ <text id="space-across-empty-tspan" x="10" y="210">A <tspan></tspan> B</text>
+ <text id="xml-space-preserve" x="10" y="240" xml:space="preserve"> A <tspan id="xml-space-preserve-child"> B </tspan> C </text>
+ <text id="preserved-tspan" x="10" y="270">A <tspan id="preserved-tspan-child" style="white-space: pre"> B </tspan> C</text>
+ <text id="collapsing-tspan" x="10" y="300" style="white-space: pre">A <tspan id="collapsing-tspan-child" style="white-space: normal"> B </tspan> C</text>
+ <text id="only-white-space" x="10" y="330"> <tspan id="only-white-space-child"> </tspan> </text>
+</svg>
+<script>
+ const round = value => Math.round(value * 100) / 100;
+ const characters = element => {
+ const positions = [];
+ for (let index = 0; index < element.getNumberOfChars(); ++index) {
+ const cell = element.getExtentOfChar(index);
+ positions.push(`${round(cell.x)},${round(cell.y)}`);
+ }
+ return `${positions.length} characters, length ${round(element.getComputedTextLength())}: ${positions.join(" ")}`;
+ };
+ const box = element => {
+ const rect = element.getBBox();
+ return `${round(rect.x)},${round(rect.y)} ${round(rect.width)}x${round(rect.height)}`;
+ };
+
+ asyncTest(async done => {
+ await document.fonts.load("20px Ahem");
+ for (const element of document.querySelectorAll("svg [id]")) {
+ const queries = element.getNumberOfChars ? `${characters(element)}; ` : "";
+ println(`${element.id}: ${queries}box ${box(element)}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getextentofchar.html b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getextentofchar.html
new file mode 100644
index 00000000000..ea7371c81e9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getextentofchar.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>SVGTextContentElement.getExtentOfChar</title>
+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/text.html#__svg__SVGTextContentElement__getExtentOfChar">
+<script src="../../../resources/testharness.js"></script>
+<script src="../../../resources/testharnessreport.js"></script>
+
+<svg width="800" height="200">
+<text><tspan id="tspan1" x="50 150 100" y="100">abc</tspan>d</text>
+<text dominant-baseline="hanging"><tspan id="tspan2" x="50" y="150">abc</tspan></text>
+</svg>
+
+<script>
+test(() => {
+ const element = document.querySelector('#tspan1');
+ assert_equals(element.getNumberOfChars(), 3);
+ assert_equals(element.getExtentOfChar(0).x, 50);
+ assert_equals(element.getExtentOfChar(1).x, 150);
+ assert_equals(element.getExtentOfChar(2).x, 100);
+ assert_throws_dom("IndexSizeError", () => element.getExtentOfChar(3));
+}, 'Multiple chunks in a tspan');
+
+test(() => {
+ const element = document.querySelector('#tspan2');
+ assert_equals(element.getNumberOfChars(), 3);
+ assert_equals(element.getExtentOfChar(0).x, 50);
+ assert_approx_equals(element.getExtentOfChar(0).y, 147.5, 1);
+}, 'With dominant-baseline');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getnumberofchars.html b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getnumberofchars.html
new file mode 100644
index 00000000000..d72d59f44a6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/getnumberofchars.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>SVGTextContentElement.getNumberOfChars</title>
+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/text.html#__svg__SVGTextContentElement__getNumberOfChars">
+<link rel="stylesheet" href="../../../fonts/ahem.css">
+<script src="../../../resources/testharness.js"></script>
+<script src="../../../resources/testharnessreport.js"></script>
+
+<svg width="800" height="600">
+<style>
+text {
+ font: 20px/1 Ahem;
+}
+</style>
+<text id="t1" x="40" y="100">abc</text>
+<text id="t2"><tspan id="ts2" x="40" y="100">ab</tspan>c</text>
+<text id="t3"><tspan id="ts3" x="40" y="100">هيab</tspan>c</text>
+<text id="t4"><tspan id="ts4" x="40" y="100">هي<tspan>ab</tspan></tspan>c</text>
+</svg>
+
+<script>
+setup({ explicit_done: true });
+
+document.fonts.ready.then(() => {
+ test(() => {
+ const text = document.querySelector('#t1');
+ assert_equals(text.getNumberOfChars(), 3);
+ }, 'latin text');
+
+ test(() => {
+ const text = document.querySelector('#t2');
+ assert_equals(text.getNumberOfChars(), 3);
+ const tspan = document.querySelector('#ts2');
+ assert_equals(tspan.getNumberOfChars(), 2);
+ }, 'latin text and tspan');
+
+ test(() => {
+ const text = document.querySelector('#t3');
+ assert_equals(text.getNumberOfChars(), 5);
+ const tspan = document.querySelector('#ts3');
+ assert_equals(tspan.getNumberOfChars(), 4);
+ }, 'mixed-rtl text and tspan');
+
+ test(() => {
+ const text = document.querySelector('#t4');
+ assert_equals(text.getNumberOfChars(), 5);
+ const tspan = document.querySelector('#ts4');
+ assert_equals(tspan.getNumberOfChars(), 4);
+ }, 'mixed-rtl text and tested tspan');
+
+ done();
+});
+</script>