Truly independent web browser
LibWeb: Fit SVG text to its textLength
sideshowbarkerec77b4625829
diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp b/Libraries/LibWeb/Layout/LayoutRustBridge.cppindex 52c000d5e45..8800c67c16d 100644--- a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.cpp@@ -279,6 +279,11 @@ static RustFFI::FfiSvgAttributeFacts build_svg_attribute_facts(DOM::Element& domif (auto const* text_positioning_element = as_if<SVG::SVGTextPositioningElement>(dom_node))text_positioning = text_positioning_element->parsed_text_positioning();+ // NB: Only the text length of a <text> adjusts its text. One on a <tspan> or a <textPath> is left alone.+ SVG::SVGTextContentElement::ParsedTextLength text_length;+ if (auto const* text_element = as_if<SVG::SVGTextElement>(dom_node))+ text_length = text_element->parsed_text_length();+CSS::StyleAtomID reference_fragment;SVG::NumberPercentage start_offset = SVG::NumberPercentage::create_number(0);if (auto const* text_path_element = as_if<SVG::SVGTextPathElement>(dom_node)) {@@ -342,6 +347,8 @@ static RustFFI::FfiSvgAttributeFacts build_svg_attribute_facts(DOM::Element& dom.text_y = to_ffi_svg_length_value(text_positioning.y),.text_dx = to_ffi_svg_length_value(text_positioning.dx),.text_dy = to_ffi_svg_length_value(text_positioning.dy),+ .text_length = to_ffi_svg_length_value(text_length.text_length),+ .text_length_adjusts_glyphs = text_length.adjusts_glyphs,.reference_fragment_atom = reference_fragment.value(),.mask_reference_atom = style_references[0].value(),.clip_path_reference_atom = style_references[1].value(),diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex d4954bc0d23..9440f06530f 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -51,8 +51,9 @@ struct ShapedSvgText {}/// Appends the glyph cell of each code unit of one shaped run, in code unit order. A typographic-/// character's cell spans its advance; every code unit of it carries that cell, and the first one-/// is marked as the one that starts it.+/// character's cell spans its advance, less the `spacing_after_each_character` the run was shaped+/// with; every code unit of it carries that cell, and the first one is marked as the one that starts+/// it./// https://svgwg.org/svg2-draft/text.html#TermTypographicCharacterUnit/// A unit of a writing system - such as a Latin alphabetic letter (including its diacritics),/// Hangul syllable, Chinese ideographic character, Myanmar syllable cluster - that is indivisible@@ -66,6 +67,7 @@ fn append_svg_text_character_cells(run_end_x: f32,top: f32,height: f32,+ spacing_after_each_character: f32,) {let placed: Vec<_> = glyphs.placed().collect();let mut covered = 0usize;@@ -86,7 +88,7 @@ fn append_svg_text_character_cells(let cell = FfiSvgTextCharacterCell {x: first.x,y: top,- width: end_x - first.x,+ width: end_x - first.x - spacing_after_each_character,height,starts_typographic_character: true,};@@ -227,6 +229,10 @@ pub struct FfiSvgAttributeFacts {pub text_y: FfiSvgLengthValue,pub text_dx: FfiSvgLengthValue,pub text_dy: FfiSvgLengthValue,+ /// The `textLength` of a `<text>`, where it gives a valid one, and whether its `lengthAdjust` is+ /// `spacingAndGlyphs`.+ pub text_length: FfiSvgLengthValue,+ pub text_length_adjusts_glyphs: bool,/// The element this one's `href` names, as the style mirror's id index answers for it: the/// URL's decoded fragment, interned as the atom an element's id is indexed under. Zero when/// the element names nothing, or names a URL with no fragment.@@ -558,6 +564,38 @@ impl SvgTextPaintParts {}}+/// How the 'textLength' of a <text> adjusts its text to that length.+/// https://svgwg.org/svg2-draft/text.html#TextElementLengthAdjustAttribute+#[derive(Clone, Copy, Debug, Default, PartialEq)]+enum SvgTextLengthAdjustment {+ #[default]+ None,+ /// spacing: Indicates that only the advance values are adjusted. The glyphs themselves are not stretched or+ /// compressed.+ /// NB: Holds the space to add after each typographic character.+ Spacing(f32),+ /// spacingAndGlyphs: Indicates that the advance values are adjusted and the glyphs themselves stretched or+ /// compressed in one axis (i.e., a direction parallel to the inline-base direction).+ /// NB: Holds the factor to scale by along that axis.+ SpacingAndGlyphs(f32),+}++impl SvgTextLengthAdjustment {+ fn spacing(self) -> f32 {+ match self {+ Self::Spacing(spacing) => spacing,+ _ => 0.0,+ }+ }++ fn glyph_scale(self) -> f32 {+ match self {+ Self::SpacingAndGlyphs(scale) => scale,+ _ => 1.0,+ }+ }+}+#[derive(Clone, Copy, Debug, PartialEq)]struct SvgTextChunkMeasurement {advance: f32,@@ -686,6 +724,8 @@ 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,+ /// How the <text> element being laid out adjusts its text to its 'textLength'.+ text_length_adjustment: SvgTextLengthAdjustment,/// 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.@@ -727,6 +767,7 @@ impl<'pass> SvgFormattingContext<'pass> {viewport_is_committed_viewport: false,percentage_block_insets_of_run_root_children_have_definite_basis,current_text_position: FfiFloatPoint::default(),+ text_length_adjustment: SvgTextLengthAdjustment::None,processed_svg_text: RefCell::new(std::collections::HashMap::new()),last_text_subtree_cells: None,root_payload: RefCell::new(fragment_tree::PendingPayload::default()),@@ -1394,14 +1435,22 @@ impl<'pass> SvgFormattingContext<'pass> {/// 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)) {+ fn for_each_svg_text_node(&self, root: Node, visit: impl FnMut(Node)) {+ self.for_each_svg_text_node_in(root, true, visit);+ }++ /// As for_each_svg_text_node(), but leaves out the text on a path below `root` where `include_text_on_paths` isn't+ /// set.+ fn for_each_svg_text_node_in(&self, root: Node, include_text_on_paths: bool, mut visit: impl FnMut(Node)) {let mut current = root;loop {let kind = self.node_kind(current);if node_facts::kind_is_text(kind) {visit(current);}- if matches!(kind, NodeKind::SVGTextBox | NodeKind::SVGTextPathBox) {+ let descend = kind == NodeKind::SVGTextBox+ || (kind == NodeKind::SVGTextPathBox && (include_text_on_paths || current == root));+ if descend {let child = self.first_child(current);if !child.is_invalid() {current = child;@@ -1586,11 +1635,28 @@ impl<'pass> SvgFormattingContext<'pass> {})}+ /// The <text> element the given text content element is in, or is.+ fn svg_text_element_of(&self, text_box: Node) -> Node {+ let mut text_element = text_box;+ while !self.svg_attributes(text_element).is_text_element {+ let parent = self.parent(text_element);+ if parent.is_invalid() || self.node_kind(parent) != NodeKind::SVGTextBox {+ break;+ }+ text_element = parent;+ }+ text_element+ }+fn apply_svg_text_positioning(&mut self, text_box: Node, attributes: FfiSvgAttributeFacts) {let viewport_width = self.viewport_width;let viewport_height = self.viewport_height;+ // NB: Text whose glyphs 'textLength' scales is laid out as it is without the scale, and scaled afterward. So,+ // an 'x' is taken to where it lands once scaled.+ let glyph_scale = self.text_length_adjustment.glyph_scale();if attributes.text_x.kind != SVG_LENGTH_KIND_NONE {- self.current_text_position.x = self.resolve_svg_text_length(text_box, attributes.text_x, viewport_width);+ self.current_text_position.x =+ self.resolve_svg_text_length(text_box, attributes.text_x, viewport_width) / glyph_scale;}if attributes.text_y.kind != SVG_LENGTH_KIND_NONE {self.current_text_position.y = self.resolve_svg_text_length(text_box, attributes.text_y, viewport_height);@@ -1607,7 +1673,13 @@ impl<'pass> SvgFormattingContext<'pass> {let shifts_along_x = has_dx && shifts(|attributes| attributes.text_dx);let shifts_along_y = has_dy && shifts(|attributes| attributes.text_dy);if shifts_along_x {- self.current_text_position.x += self.resolve_svg_text_length(text_box, attributes.text_dx, viewport_width);+ let dx = self.resolve_svg_text_length(text_box, attributes.text_dx, viewport_width);+ // NB: A 'dx' between two characters is part of the length 'textLength' scales. One that moves where the+ // text or a text chunk starts isn't, so it's taken to where it lands once scaled, as an 'x' is.+ let is_scaled = glyph_scale != 1.0+ && attributes.text_x.kind == SVG_LENGTH_KIND_NONE+ && first_text_node != self.first_rendered_svg_text_node(self.svg_text_element_of(text_box));+ self.current_text_position.x += if is_scaled { dx } else { dx / glyph_scale };}if shifts_along_y {self.current_text_position.y += self.resolve_svg_text_length(text_box, attributes.text_dy, viewport_height);@@ -1691,14 +1763,22 @@ impl<'pass> SvgFormattingContext<'pass> {/// text the cascade resolves to the same font, each starting where the last one ended. Also/// returns the union of the runs' glyph cells, each run's measured with its own font, and the/// glyph cell of every code unit of the text.- fn shape_svg_text(&self, style: StyleValues<'_>, text: &[u16], baseline_start: FfiFloatPoint) -> ShapedSvgText {+ fn shape_svg_text(+ &self,+ style: StyleValues<'_>,+ text: &[u16],+ baseline_start: FfiFloatPoint,+ text_length_spacing: f32,+ ) -> ShapedSvgText {let mut shaped_text = ShapedSvgText {runs: Vec::new(),advance: 0.0,glyph_cells: SvgCssPixelRect::default(),character_cells: Vec::with_capacity(text.len()),};- let letter_spacing = style.letter_spacing().to_double() as f32;+ // NB: The space 'textLength' adds after each typographic character is laid out as letter spacing is, but isn't+ // part of the character's cell.+ let letter_spacing = style.letter_spacing().to_double() as f32 + text_length_spacing;let word_spacing = style.word_spacing().to_double() as f32;Self::for_each_svg_font_run(style, text, |font, run_text| {let run_start_x = baseline_start.x + shaped_text.advance;@@ -1723,7 +1803,7 @@ impl<'pass> SvgFormattingContext<'pass> {shaped_text.glyph_cells.unite(float_rect_to_css_pixels(FloatRect::new(run_start_x,cell_top,- shaped.width(),+ shaped.width() - text_length_spacing,cell_height,)));append_svg_text_character_cells(@@ -1733,6 +1813,7 @@ impl<'pass> SvgFormattingContext<'pass> {run_start_x + shaped.width(),cell_top,cell_height,+ text_length_spacing,);shaped_text.advance += shaped.width();let mut glyphs = shaped.into_glyphs();@@ -1751,7 +1832,7 @@ impl<'pass> SvgFormattingContext<'pass> {fn svg_text_run_advance(&self, text_box: Node, text: &[u16]) -> f32 {let mut advance = 0.0f32;let style = self.style(text_box);- let letter_spacing = style.letter_spacing().to_double() as f32;+ let letter_spacing = style.letter_spacing().to_double() as f32 + self.text_length_adjustment.spacing();let word_spacing = style.word_spacing().to_double() as f32;Self::for_each_svg_font_run(style, text, |font, run_text| {advance += libgfx_rust::text_layout::shape_text(@@ -1783,6 +1864,7 @@ impl<'pass> SvgFormattingContext<'pass> {let mut found_chunk_start = false;let mut found_first_rendered_text = false;let mut found_first_rendered_text_node = false;+ let mut chunk_ends_the_text = false;let mut current = subtree_root;'walk: loop {let kind = self.node_kind(current);@@ -1829,6 +1911,7 @@ impl<'pass> SvgFormattingContext<'pass> {}loop {if current == subtree_root {+ chunk_ends_the_text = true;break 'walk;}let sibling = self.next_sibling(current);@@ -1839,6 +1922,10 @@ impl<'pass> SvgFormattingContext<'pass> {current = self.parent(current);}}+ // NB: 'textLength' adds no space after the last character of the text.+ if chunk_ends_the_text && found_first_rendered_text {+ measurement.advance -= self.text_length_adjustment.spacing();+ }measurement}@@ -1859,6 +1946,7 @@ impl<'pass> SvgFormattingContext<'pass> {// without 'x'/'y' continues at the current text position.if attributes.is_text_element {self.current_text_position = FfiFloatPoint::default();+ self.text_length_adjustment = self.svg_text_length_adjustment(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)@@ -1895,6 +1983,14 @@ impl<'pass> SvgFormattingContext<'pass> {}let dominant_baseline_offset = self.svg_dominant_baseline_offset(self.style(text_box));+ let glyph_scale = self.text_length_adjustment.glyph_scale();+ let scale_glyphs = |path: libgfx_rust::path::Path| {+ if glyph_scale == 1.0 {+ path+ } else {+ path.copy_transformed([glyph_scale, 0.0, 0.0, 1.0, 0.0, 0.0])+ }+ };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();@@ -1909,7 +2005,25 @@ impl<'pass> SvgFormattingContext<'pass> {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);+ let mut shaped = self.shape_svg_text(+ self.style(text_box),+ &text,+ text_offset,+ self.text_length_adjustment.spacing(),+ );+ if glyph_scale != 1.0 {+ let glyph_cells = shaped.glyph_cells.to_float_rect();+ shaped.glyph_cells = float_rect_to_css_pixels(FloatRect::new(+ glyph_cells.x * glyph_scale,+ glyph_cells.y,+ glyph_cells.width * glyph_scale,+ glyph_cells.height,+ ));+ for cell in &mut shaped.character_cells {+ cell.x *= glyph_scale;+ cell.width *= glyph_scale;+ }+ }// https://svgwg.org/svg2-draft/text.html#TextLayoutIntroduction// After each glyph is placed, the current text position is advanced by the glyph's advance@@ -1946,15 +2060,85 @@ impl<'pass> SvgFormattingContext<'pass> {break;}glyph_outlines.append_path(&path);- segments.push(fragment_tree::SvgTextSegment { after_child, path });+ segments.push(fragment_tree::SvgTextSegment {+ after_child,+ path: scale_glyphs(path),+ });}- contents.path = glyph_outlines;+ contents.path = scale_glyphs(glyph_outlines);if !paints_as_one_path {contents.segments = Some(segments);}+ if attributes.is_text_element {+ self.text_length_adjustment = SvgTextLengthAdjustment::None;+ }contents}+ /// How the given <text> element adjusts its text to its 'textLength'.+ /// https://svgwg.org/svg2-draft/text.html#TextElementTextLengthAttribute+ /// The author's computation of the total sum of all of the advance values that correspond to character data+ /// within this element, including the advance value on the glyph (horizontal or vertical), the effect of+ /// properties letter-spacing and word-spacing and adjustments due to attributes 'dx' and 'dy' on this 'text' or+ /// 'tspan' element or any descendants. This value is used to calibrate the user agent's own calculations with+ /// that of the author.+ /// NB: A 'dx' on the text's first character moves where the text starts, so it's no part of the length.+ /// AD-HOC: Text on a path isn't adjusted, since it's laid out independently.+ fn svg_text_length_adjustment(&self, text_box: Node, attributes: FfiSvgAttributeFacts) -> SvgTextLengthAdjustment {+ if attributes.text_length.kind == SVG_LENGTH_KIND_NONE {+ return SvgTextLengthAdjustment::None;+ }+ let text_length = self.resolve_svg_text_length(text_box, attributes.text_length, self.viewport_width);+ if text_length <= 0.0 {+ return SvgTextLengthAdjustment::None;+ }+ // NB: Text with space between its characters is shaped without optional ligatures, which changes how long it+ // is and how many typographic characters it has. So, text that's about to get that space is measured the way+ // it will be shaped: with a space too small to tell.+ let spacing_while_measuring = if attributes.text_length_adjusts_glyphs {+ 0.0+ } else {+ f32::MIN_POSITIVE+ };+ let mut natural_length = 0.0f32;+ let mut typographic_character_count = 0usize;+ let mut found_first_rendered_text_node = false;+ self.for_each_svg_text_node_in(text_box, false, |node| {+ if !self.processed_svg_text(node).is_empty() {+ if found_first_rendered_text_node {+ natural_length += self.svg_text_dx_before(node);+ }+ found_first_rendered_text_node = true;+ }+ let Some(text) = self.svg_text_run_starting_at(node) else {+ return;+ };+ let shaped = self.shape_svg_text(+ self.style(self.parent(node)),+ &text,+ FfiFloatPoint::default(),+ spacing_while_measuring,+ );+ natural_length += shaped.advance;+ typographic_character_count += shaped+ .character_cells+ .iter()+ .filter(|cell| cell.starts_typographic_character)+ .count();+ });+ if attributes.text_length_adjusts_glyphs {+ if natural_length <= 0.0 {+ return SvgTextLengthAdjustment::None;+ }+ return SvgTextLengthAdjustment::SpacingAndGlyphs(text_length / natural_length);+ }+ // NB: The space is added between the typographic characters, so there's none to add to a single one.+ if typographic_character_count < 2 {+ return SvgTextLengthAdjustment::None;+ }+ SvgTextLengthAdjustment::Spacing((text_length - natural_length) / (typographic_character_count - 1) as f32)+ }+/// The glyph outlines a <textPath> renders: its whole subtree's text, shaped from the origin/// and then laid along the shape its `href` names. Also returns the glyph cell of each of its/// characters.@@ -1969,7 +2153,8 @@ impl<'pass> SvgFormattingContext<'pass> {let style = self.style(text_path_box);let text = self.rendered_svg_text_contents(text_path_box);- let shaped = self.shape_svg_text(style, &text, FfiFloatPoint::default());+ // AD-HOC: Text on a path is laid out independently, so the 'textLength' of the <text> it's in doesn't adjust it.+ let shaped = self.shape_svg_text(style, &text, FfiFloatPoint::default(), 0.0);// https://svgwg.org/svg2-draft/text.html#TextPathElementStartOffsetAttributelet mut start_offset = selfdiff --git a/Libraries/LibWeb/SVG/SVGTextContentElement.cpp b/Libraries/LibWeb/SVG/SVGTextContentElement.cppindex 268f72ab917..0ca9f0cdc16 100644--- a/Libraries/LibWeb/SVG/SVGTextContentElement.cpp+++ b/Libraries/LibWeb/SVG/SVGTextContentElement.cpp@@ -166,6 +166,41 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMRect>> SVGTextContentElement::get_extenreturn Geometry::DOMRect::create(rect);}+void SVGTextContentElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)+{+ Base::attribute_changed(name, old_value, value, namespace_);++ // The attributes adjust the advances of the element's characters, so the text has to be laid out with their new+ // values.+ if (old_value != value && name.is_one_of(AttributeNames::textLength, AttributeNames::lengthAdjust))+ set_needs_layout_update(DOM::SetNeedsLayoutReason::StyleChange);+}++SVGTextContentElement::ParsedTextLength SVGTextContentElement::parsed_text_length() const+{+ CSS::Parser::ParsingParams const parsing_params { document() };+ ParsedTextLength parsed;++ // https://svgwg.org/svg2-draft/text.html#TextElementTextLengthAttribute+ // A negative value is an error (see Error processing).+ auto raw_text_length = get_attribute_value(AttributeNames::textLength);+ if (auto style_value = parse_css_type(parsing_params, raw_text_length, CSS::ValueType::LengthPercentage)) {+ if (auto value = SVGLengthValue::from_style_value(*style_value); value.has_value() && value->kind() != SVGLengthValue::Kind::Number && value->value() >= 0)+ parsed.text_length = value;+ }+ if (!parsed.text_length.has_value()) {+ if (auto style_value = parse_css_type(parsing_params, raw_text_length, CSS::ValueType::Number)) {+ if (auto value = SVGLengthValue::from_style_value(*style_value); value.has_value() && value->kind() == SVGLengthValue::Kind::Number && value->value() >= 0)+ parsed.text_length = value;+ }+ }++ // https://svgwg.org/svg2-draft/text.html#TextElementLengthAdjustAttribute+ // lengthAdjust = "spacing | spacingAndGlyphs"+ parsed.adjusts_glyphs = get_attribute_value(AttributeNames::lengthAdjust) == "spacingAndGlyphs"sv;+ return parsed;+}+// https://svgwg.org/svg2-draft/text.html#__svg__SVGTextContentElement__lengthAdjustGC::Ref<SVGAnimatedEnumeration> SVGTextContentElement::length_adjust(){diff --git a/Libraries/LibWeb/SVG/SVGTextContentElement.h b/Libraries/LibWeb/SVG/SVGTextContentElement.hindex 8fcf8d64157..38cf8bc0346 100644--- a/Libraries/LibWeb/SVG/SVGTextContentElement.h+++ b/Libraries/LibWeb/SVG/SVGTextContentElement.h@@ -28,6 +28,14 @@ public:GC::Ref<SVGAnimatedEnumeration> length_adjust();+ // What the textLength and lengthAdjust attributes ask of layout: The length to fit the text to, where the element+ // gives a valid one, and whether the glyphs stretch along with the spacing between them.+ struct ParsedTextLength {+ Optional<SVGLengthValue> text_length;+ bool adjusts_glyphs { false };+ };+ ParsedTextLength parsed_text_length() const;+// https://svgwg.org/svg2-draft/text.html#__svg__SVGTextContentElement__textLength// The initial value of the ‘textLength’ content attribute is defined to equal the user-agent's calculated length// for the element.@@ -44,6 +52,8 @@ public:protected:SVGTextContentElement(DOM::Document&, DOM::QualifiedName);+ virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;+private:virtual bool is_svg_text_content_element() const final { return true; }diff --git a/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/lengthAdjust-large-font.svg b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/lengthAdjust-large-font.svgnew file mode 100644index 00000000000..67bceb75e06--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/lengthAdjust-large-font.svg@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="utf-8"?>+<svg xmlns="http://www.w3.org/2000/svg" xmlns:h="http://www.w3.org/1999/xhtml">+ <metadata>+ <title>lengthAdjust="spacingAndGlyphs" should render properly</title>+ <h:link rel="help" href="https://www.w3.org/TR/SVG2/text.html#TextElementLengthAdjustAttribute"/>+ <h:link rel="match" href="../../../../../expected/wpt-import/svg/text/reftests/green-100x100.svg"/>+ <h:link rel="stylesheet" type="text/css" href="../../../fonts/ahem.css" />+ </metadata>+ <style>+ text {+ font: 100px/1 Ahem;+ }+ </style>+ <rect fill="green" width="100" height="100"/>+ <rect fill="red" x="80" y="20" width="10" height="60"/>+ <text x="-82" y="70" fill="green" textLength="180" lengthAdjust="spacingAndGlyphs" font-family="Ahem">+ XXXXXXX+ </text>+</svg>diff --git a/Tests/LibWeb/Text/expected/SVG/text-length.txt b/Tests/LibWeb/Text/expected/SVG/text-length.txtnew file mode 100644index 00000000000..9dd86fa3c84--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/text-length.txt@@ -0,0 +1,36 @@+longer: 10+20 70+20 130+20 190+20; length 80; box 10,14 200x20+longer, glyphs too: 10+50 60+50 110+50 160+50; length 200; box 10,14 200x20+shorter: 10+20 16.67+20 23.33+20 30+20; length 80; box 10,14 40x20+shorter, glyphs too: 10+10 20+10 30+10 40+10; length 40; box 10,14 40x20+zero: 10+20 30+20 50+20 70+20; length 80; box 10,14 80x20+negative: 10+20 30+20 50+20 70+20; length 80; box 10,14 80x20+not a length: 10+20 30+20 50+20 70+20; length 80; box 10,14 80x20+percentage of the 900px-wide viewport: 10+20 153.33+20 296.67+20 440+20; length 80; box 10,14 450x20+em: 10+20 70+20 130+20 190+20; length 80; box 10,14 200x20+unknown lengthAdjust: 10+20 70+20 130+20 190+20; length 80; box 10,14 200x20+one character: 10+20; length 20; box 10,14 20x20+one character, glyphs too: 10+200; length 200; box 10,14 200x20+no characters: ; length 0; box 0,0 0x0+anchored in the middle: 200+20 260+20 320+20 380+20; length 80; box 200,14 200x20+anchored at the end: 100+20 160+20 220+20 280+20; length 80; box 100,14 200x20+anchored in the middle, glyphs too: 200+50 250+50 300+50 350+50; length 200; box 200,14 200x20+across a <tspan>: 10+20 70+20 130+20 190+20; length 80; box 10,14 200x20+across two chunks: 10+20 66+20 200+20 256+20 312+20 368+20; length 120; box 10,14 378x20+across two chunks, glyphs too: 10+50 60+50 200+50 250+50 300+50 350+50; length 300; box 10,14 390x20+with letter-spacing: 10+30 66.67+30 123.33+30 180+30; length 120; box 10,14 200x20+with spaces: 10+20 55+20 100+20 145+20 190+20; length 100; box 10,14 200x20+two font sizes, glyphs too: 10+66.67 76.67+66.67 143.33+33.33 176.67+33.33; length 200; box 10,-2 200x40+with a dx inside: 10+20 63.33+20 136.67+20 190+20; length 80; box 10,14 200x20+with a dx inside, glyphs too: 10+40 50+40 130+40 170+40; length 160; box 10,14 200x20+with a negative dx inside, glyphs too: 10+80 90+80 50+80 130+80; length 320; box 10,14 200x20+with a dx on the first character: 30+20 90+20 150+20 210+20; length 80; box 30,14 200x20+with a dx on the first character, glyphs too: 30+50 80+50 130+50 180+50; length 200; box 30,14 200x20+with a dx at the start of a chunk, glyphs too: 10+40 50+40 320+40 360+40; length 160; box 10,14 390x20+with a dx in nested elements, glyphs too: 10+40 50+40 130+40 170+40; length 160; box 10,14 200x20+on a <tspan>: 10+20 30+20 50+20 70+20 90+20 110+20; length 120; box 10,14 120x20+with text on a path: 10+20 70+20 0+20 20+20; length 80; box 10,14 130x40+textLength set: 10+20 70+20 130+20 190+20; length 80; box 10,14 200x20+lengthAdjust set: 10+50 60+50 110+50 160+50; length 200; box 10,14 200x20+textLength.baseVal.value set: 10+35 45+35 80+35 115+35; length 140; box 10,14 140x20+lengthAdjust.baseVal set: 10+20 50+20 90+20 130+20; length 80; box 10,14 140x20+textLength removed: 10+20 30+20 50+20 70+20; length 80; box 10,14 80x20diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/lengthadjust.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/lengthadjust.txtnew file mode 100644index 00000000000..8461c3523df--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/text/scripted/lengthadjust.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass Tests dynamic updates of the "lengthAdjust" content attribute+Pass Tests dynamic updates of the "lengthAdjust" IDL attribute\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/SVG/text-length.html b/Tests/LibWeb/Text/input/SVG/text-length.htmlnew file mode 100644index 00000000000..03ae683abc9--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/text-length.html@@ -0,0 +1,86 @@+<!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="900" height="100"></svg>+<script>+ const round = value => Math.round(value * 100) / 100;+ const describe = text => {+ const cells = [];+ for (let index = 0; index < text.getNumberOfChars(); ++index) {+ const cell = text.getExtentOfChar(index);+ cells.push(`${round(cell.x)}+${round(cell.width)}`);+ }+ const box = text.getBBox();+ return `${cells.join(" ")}; length ${round(text.getComputedTextLength())}; box ${round(box.x)},${round(box.y)} ${round(box.width)}x${round(box.height)}`;+ };++ asyncTest(async done => {+ await document.fonts.load("20px Ahem");+ const svg = document.querySelector("svg");++ // Each glyph of Ahem is 20px wide here, so "ABCD" is 80px long.+ const cases = [+ ["longer", `<text x="10" y="30" textLength="200">ABCD</text>`],+ ["longer, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">ABCD</text>`],+ ["shorter", `<text x="10" y="30" textLength="40">ABCD</text>`],+ ["shorter, glyphs too", `<text x="10" y="30" textLength="40" lengthAdjust="spacingAndGlyphs">ABCD</text>`],+ ["zero", `<text x="10" y="30" textLength="0">ABCD</text>`],+ ["negative", `<text x="10" y="30" textLength="-50">ABCD</text>`],+ ["not a length", `<text x="10" y="30" textLength="bogus">ABCD</text>`],+ ["percentage of the 900px-wide viewport", `<text x="10" y="30" textLength="50%">ABCD</text>`],+ ["em", `<text x="10" y="30" textLength="10em">ABCD</text>`],+ ["unknown lengthAdjust", `<text x="10" y="30" textLength="200" lengthAdjust="bogus">ABCD</text>`],+ ["one character", `<text x="10" y="30" textLength="200">A</text>`],+ ["one character, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">A</text>`],+ ["no characters", `<text x="10" y="30" textLength="200"></text>`],+ ["anchored in the middle", `<text x="300" y="30" textLength="200" text-anchor="middle">ABCD</text>`],+ ["anchored at the end", `<text x="300" y="30" textLength="200" text-anchor="end">ABCD</text>`],+ ["anchored in the middle, glyphs too", `<text x="300" y="30" textLength="200" text-anchor="middle" lengthAdjust="spacingAndGlyphs">ABCD</text>`],+ ["across a <tspan>", `<text x="10" y="30" textLength="200">AB<tspan>CD</tspan></text>`],+ ["across two chunks", `<text x="10" y="30" textLength="300">AB<tspan x="200">CD</tspan>EF</text>`],+ ["across two chunks, glyphs too", `<text x="10" y="30" textLength="300" lengthAdjust="spacingAndGlyphs">AB<tspan x="200">CD</tspan>EF</text>`],+ ["with letter-spacing", `<text x="10" y="30" textLength="200" letter-spacing="10">ABCD</text>`],+ ["with spaces", `<text x="10" y="30" textLength="200">A B C</text>`],+ ["two font sizes, glyphs too", `<text x="10" y="30" style="font-size: 40px" textLength="200" lengthAdjust="spacingAndGlyphs">AB<tspan style="font-size: 20px">CD</tspan></text>`],+ ["with a dx inside", `<text x="10" y="30" textLength="200">AB<tspan dx="20">CD</tspan></text>`],+ ["with a dx inside, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">AB<tspan dx="20">CD</tspan></text>`],+ ["with a negative dx inside, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">AB<tspan dx="-30">CD</tspan></text>`],+ ["with a dx on the first character", `<text x="10" y="30" textLength="200"><tspan dx="20">AB</tspan>CD</text>`],+ ["with a dx on the first character, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs"><tspan dx="20">AB</tspan>CD</text>`],+ ["with a dx at the start of a chunk, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">AB<tspan x="300" dx="20">CD</tspan></text>`],+ ["with a dx in nested elements, glyphs too", `<text x="10" y="30" textLength="200" lengthAdjust="spacingAndGlyphs">AB<tspan dx="100"><tspan dx="20">CD</tspan></tspan></text>`],+ ["on a <tspan>", `<text x="10" y="30">AB<tspan textLength="100">CD</tspan>EF</text>`],+ ["with text on a path", `<path id="path" d="M100 50H500" /><text x="10" y="30" textLength="80">AB<textPath href="#path">CD</textPath></text>`],+ ];+ for (const [name, markup] of cases) {+ svg.innerHTML = markup;+ println(`${name}: ${describe(svg.querySelector("text"))}`);+ }++ svg.innerHTML = `<text x="10" y="30">ABCD</text>`;+ const text = svg.firstChild;+ text.setAttribute("textLength", "200");+ println(`textLength set: ${describe(text)}`);+ text.setAttribute("lengthAdjust", "spacingAndGlyphs");+ println(`lengthAdjust set: ${describe(text)}`);+ text.textLength.baseVal.value = 140;+ println(`textLength.baseVal.value set: ${describe(text)}`);+ text.lengthAdjust.baseVal = SVGTextContentElement.LENGTHADJUST_SPACING;+ println(`lengthAdjust.baseVal set: ${describe(text)}`);+ text.removeAttribute("textLength");+ println(`textLength removed: ${describe(text)}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/lengthadjust.html b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/lengthadjust.htmlnew file mode 100644index 00000000000..a9d9bccfac3--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/svg/text/scripted/lengthadjust.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<title>lengthAdjust content/IDL attribute</title>+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/text.html#TextElementLengthAdjustAttribute">+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/text.html#__svg__SVGTextContentElement__getComputedTextLength">+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>++<svg>+ <text x="0" y="215" textLength="200">Stretched text</text>+ <text x="0" y="215" textLength="200">Stretched text</text>+</svg>++<script>+test(() => {+ const text = document.querySelectorAll('text')[0];+ assert_equals(text.getAttribute('lengthAdjust'), null);+ assert_equals(text.lengthAdjust.baseVal, SVGTextContentElement.LENGTHADJUST_SPACING);+ assert_equals(text.textLength.baseVal.value, 200);+ let lastLength = text.getComputedTextLength();+ assert_between_exclusive(lastLength, 0, 200);++ text.setAttribute('lengthAdjust', 'spacingAndGlyphs');+ assert_equals(text.lengthAdjust.baseVal, SVGTextContentElement.LENGTHADJUST_SPACINGANDGLYPHS);+ assert_equals(text.textLength.baseVal.value, 200);+ assert_greater_than(text.getComputedTextLength(), lastLength);+}, 'Tests dynamic updates of the "lengthAdjust" content attribute');++test(() => {+ const text = document.querySelectorAll('text')[1];+ assert_equals(text.getAttribute('lengthAdjust'), null);+ assert_equals(text.lengthAdjust.baseVal, SVGTextContentElement.LENGTHADJUST_SPACING);+ assert_equals(text.textLength.baseVal.value, 200);+ let lastLength = text.getComputedTextLength();+ assert_between_exclusive(lastLength, 0, 200);++ text.lengthAdjust.baseVal = SVGTextContentElement.LENGTHADJUST_SPACINGANDGLYPHS;+ assert_equals(text.getAttribute('lengthAdjust'), 'spacingAndGlyphs');+ assert_equals(text.lengthAdjust.baseVal, SVGTextContentElement.LENGTHADJUST_SPACINGANDGLYPHS);+ assert_equals(text.textLength.baseVal.value, 200);+ assert_greater_than(text.getComputedTextLength(), lastLength);+}, 'Tests dynamic updates of the "lengthAdjust" IDL attribute');+</script>