Truly independent web browser
LibWeb: Apply text-transform to SVG text
sideshowbarker677e3b64832c
diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rsindex 5667c2047ce..d60fa834488 100644--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs@@ -103,7 +103,7 @@ pub(super) struct TextRenderingKey {locale: Option<Vec<u16>>,}-fn transform_uses_locale(transform: u8) -> bool {+pub(super) fn transform_uses_locale(transform: u8) -> bool {matches!(transform,text_transform::LOWERCASE | text_transform::UPPERCASE | text_transform::CAPITALIZEdiff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex c45029fba91..994d985a913 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -44,6 +44,30 @@ pub struct FfiSvgTextCharacterCell {pub starts_typographic_character: bool,}+/// Appends the cell of each character the edits map the given cells back to: Where an edit turned characters into+/// others, the characters it took share the cell of those it made.+fn append_svg_text_cells_through_edits<'a>(+ cells: &[FfiSvgTextCharacterCell],+ edits: impl IntoIterator<Item = &'a super::rendered_text::RenderedTextEdit>,+ out: &mut Vec<FfiSvgTextCharacterCell>,+) {+ let mut cursor = 0;+ for edit in edits {+ let start = edit.rendered_start_offset;+ let end = start + edit.rendered_length_in_code_units;+ out.extend_from_slice(&cells[cursor..start]);+ cursor = end;+ if edit.dom_length_in_code_units == 0 {+ continue;+ }+ let mut cell = svg_text_cell_for_source_span(cells, start, end);+ out.push(cell);+ cell.starts_typographic_character = false;+ out.extend(std::iter::repeat_n(cell, edit.dom_length_in_code_units - 1));+ }+ out.extend_from_slice(&cells[cursor..]);+}+fn svg_text_cell_for_source_span(cells: &[FfiSvgTextCharacterCell],start: usize,@@ -886,6 +910,9 @@ pub(super) struct SvgFormattingContext<'pass> {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]>>>,+ /// Where text-transform changed the characters of a text node in `processed_svg_text`, how its characters map to+ /// those it had before the transform.+ svg_text_transform_edits: RefCell<std::collections::HashMap<Node, Vec<super::rendered_text::RenderedTextEdit>>>,/// 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>>>,/// The stretches of text in the subtree of the <text>, <tspan>, or <a> laid out last, in document order.@@ -929,6 +956,7 @@ impl<'pass> SvgFormattingContext<'pass> {current_text_position: FfiFloatPoint::default(),text_length_adjustment: SvgTextLengthAdjustment::None,processed_svg_text: RefCell::new(std::collections::HashMap::new()),+ svg_text_transform_edits: RefCell::new(std::collections::HashMap::new()),last_text_subtree_cells: None,last_text_subtree_spans: Vec::new(),root_payload: RefCell::new(fragment_tree::PendingPayload::default()),@@ -1666,6 +1694,7 @@ impl<'pass> SvgFormattingContext<'pass> {.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)) {+ let text = self.apply_svg_text_transform(*node, text);processed_text.insert(*node, std::sync::Arc::from(text));}processed_text@@ -1674,6 +1703,44 @@ impl<'pass> SvgFormattingContext<'pass> {.unwrap_or_else(|| std::sync::Arc::from(Vec::new()))}+ /// The characters of a text node once its white space is processed, with its text-transform applied. The transform+ /// comes after the white space processing, so that the characters it changes map to those SVG addresses.+ /// NB: Masked text was transformed before it was masked, and has no white space left to process.+ fn apply_svg_text_transform(&self, text_node: Node, text: Vec<u16>) -> Vec<u16> {+ let inherited_text = self.style(self.parent(text_node)).inherited_text();+ if inherited_text.text_transform == crate::css::css_enums::text_transform::NONE+ || inherited_text.text_security != crate::css::css_enums::text_security::NONE+ {+ return text;+ }+ let uses_locale = super::rendered_text::transform_uses_locale(inherited_text.text_transform);+ let locale = self+ .run+ .pass+ .arena()+ .published_text_source(text_node, uses_locale)+ .locale;+ let length = text.len();+ let transformed = super::text_transform::render_text(+ text,+ locale.as_deref(),+ super::text_transform::TextRenderingOptions {+ text_transform: inherited_text.text_transform,+ text_security: crate::css::css_enums::text_security::NONE,+ white_space_collapse: crate::css::css_enums::white_space_collapse::PRESERVE,+ is_password_input: false,+ dom_start_offset: 0,+ dom_length_in_code_units: length,+ },+ );+ if !transformed.edits.is_empty() {+ self.svg_text_transform_edits+ .borrow_mut()+ .insert(text_node, transformed.edits);+ }+ transformed.text+ }+/// 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.@@ -1696,7 +1763,7 @@ impl<'pass> SvgFormattingContext<'pass> {}// SVG DOM indices address UTF-16 code units before text transformation. Keep the painted glyphs and their- // spacing, and publish the cell occupied by each source code unit of the masked run.+ // spacing, and publish the cell occupied by each source code unit of a masked or transformed run.// https://svgwg.org/svg2-draft/text.html#TermAddressableCharacterfn append_svg_run_dom_cells(&self,@@ -1704,33 +1771,31 @@ impl<'pass> SvgFormattingContext<'pass> {cells: Vec<FfiSvgTextCharacterCell>,out: &mut Vec<FfiSvgTextCharacterCell>,) {- if self.style(self.parent(node)).inherited_text().text_security == crate::css::css_enums::text_security::NONE {+ let inherited_text = self.style(self.parent(node)).inherited_text();+ let is_masked = inherited_text.text_security != crate::css::css_enums::text_security::NONE;+ if !is_masked && inherited_text.text_transform == crate::css::css_enums::text_transform::NONE {out.extend(cells);return;}let mut cells = cells.as_slice();while !node.is_invalid() && node_facts::kind_is_text(self.node_kind(node)) {- let content = self.run.pass.text_content(node);+ let current = node;node = self.next_sibling(node);- let Some(masked_text) = &content.svg_source_text else {- continue;- };- let (node_cells, rest) = cells.split_at(masked_text.len());- let mut cursor = 0;- for edit in content.rendered_text_edits() {- let start = edit.rendered_start_offset;- let end = start + edit.rendered_length_in_code_units;- out.extend_from_slice(&node_cells[cursor..start]);- cursor = end;- if edit.dom_length_in_code_units == 0 {+ if is_masked {+ let content = self.run.pass.text_content(current);+ let Some(masked_text) = &content.svg_source_text else {continue;- }- let mut cell = svg_text_cell_for_source_span(node_cells, start, end);- out.push(cell);- cell.starts_typographic_character = false;- out.extend(std::iter::repeat_n(cell, edit.dom_length_in_code_units - 1));+ };+ let (node_cells, rest) = cells.split_at(masked_text.len());+ append_svg_text_cells_through_edits(node_cells, content.rendered_text_edits(), out);+ cells = rest;+ continue;+ }+ let (node_cells, rest) = cells.split_at(self.processed_svg_text(current).len());+ match self.svg_text_transform_edits.borrow().get(¤t) {+ Some(edits) => append_svg_text_cells_through_edits(node_cells, edits, out),+ None => out.extend_from_slice(node_cells),}- out.extend_from_slice(&node_cells[cursor..]);cells = rest;}}diff --git a/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-001-ref.htmlnew file mode 100644index 00000000000..bf1b063eeb1--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-001-ref.html@@ -0,0 +1,7 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>Reference: text-transform with SVG text</title>++<p>Test passes if the greeting below is in <b>ALL-UPPERCASE</b>:</p>++<svg><text y="50">HELLO, WORLD!</text></svg>diff --git a/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-002-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-002-ref.htmlnew file mode 100644index 00000000000..f15615c2c3f--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/svg/text/reftests/text-transform-002-ref.html@@ -0,0 +1,7 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>Reference: text-transform with SVG text</title>++<p>Test passes if the greeting below has <b>Initial Capitals</b>:</p>++<svg><text y="50">Hello, World!</text></svg>diff --git a/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-001.html b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-001.htmlnew file mode 100644index 00000000000..aac3640f4e9--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-001.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>text-transform with SVG text</title>+<meta name="assert" content="The CSS text-transform property should work">+<link rel="author" title="Jonathan Kew" href="mailto:[email protected]">+<link rel="match" href="../../../../../expected/wpt-import/svg/text/reftests/text-transform-001-ref.html">+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1738560">++<p>Test passes if the greeting below is in <b>ALL-UPPERCASE</b>:</p>++<svg><text y="50" style="text-transform: uppercase">Hello, World!</text></svg>diff --git a/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-002.html b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-002.htmlnew file mode 100644index 00000000000..352cc56f38f--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/svg/text/reftests/text-transform-002.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>text-transform with SVG text</title>+<meta name="assert" content="The CSS text-transform property should work">+<link rel="author" title="Jonathan Kew" href="mailto:[email protected]">+<link rel="match" href="../../../../../expected/wpt-import/svg/text/reftests/text-transform-002-ref.html">+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1738560">++<p>Test passes if the greeting below has <b>Initial Capitals</b>:</p>++<svg><text y="50" style="text-transform: capitalize">hello, world!</text></svg>diff --git a/Tests/LibWeb/Text/expected/SVG/text-transform.txt b/Tests/LibWeb/Text/expected/SVG/text-transform.txtnew file mode 100644index 00000000000..7abb7ec0944--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/text-transform.txt@@ -0,0 +1,8 @@+uppercase matches literal capitals: true+capitalize matches literal capitals: true+uppercase tspan matches literal capitals: true+uppercase textPath matches literal capitals: true+characters: 7+start positions: 10 24.96875 40.34375 57.453125 75.28125 105.21875 120.046875+ß is wider than one capital S: true+characters with spaces collapsed: 5diff --git a/Tests/LibWeb/Text/input/SVG/text-source-change-under-text-transform.html b/Tests/LibWeb/Text/input/SVG/text-source-change-under-text-transform.htmlindex 795d932f060..28cc6e16397 100644--- a/Tests/LibWeb/Text/input/SVG/text-source-change-under-text-transform.html+++ b/Tests/LibWeb/Text/input/SVG/text-source-change-under-text-transform.html@@ -2,17 +2,17 @@<script src="../include.js"></script><svg width="400" height="100"><text id="changed" y="50" style="text-transform: uppercase">abc</text>- <text id="reference" y="80">ABC</text>+ <text id="reference" y="80">ABCD</text></svg><script>- // SVG shapes a text node's characters as written, not its rendered text. Under text-transform:- // uppercase, "abc" and "ABC" render the same, so the change must reach SVG through the source.+ // SVG shapes a text node's characters with text-transform applied, but with its own white space processing, so it+ // keeps a copy of them apart from the rendered text. A change to the source must reach that copy too.test(() => {const changed = document.getElementById("changed");const reference = document.getElementById("reference");const width = element => element.getBoundingClientRect().width;println(`differs before the change: ${width(changed) !== width(reference)}`);- changed.firstChild.data = "ABC";+ changed.firstChild.data = "abcd";println(`matches after the change: ${width(changed) === width(reference)}`);});</script>diff --git a/Tests/LibWeb/Text/input/SVG/text-transform.html b/Tests/LibWeb/Text/input/SVG/text-transform.htmlnew file mode 100644index 00000000000..ce7aaad2978--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/text-transform.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<meta charset="utf-8">+<script src="../include.js"></script>+<svg width="600" height="300" font-family="SerenitySans" font-size="20">+ <text id="uppercase" x="10" y="30" style="text-transform: uppercase">trees</text>+ <text id="literal" x="10" y="60">TREES</text>+ <text id="capitalize" x="10" y="90" style="text-transform: capitalize">hello world</text>+ <text id="capitalized" x="10" y="120">Hello World</text>+ <text id="with-tspan" x="10" y="150">a<tspan style="text-transform: uppercase">bcd</tspan>e</text>+ <text id="literal-tspan" x="10" y="180">aBCDe</text>+ <defs><path id="path" d="M 10 240 H 500" /></defs>+ <text id="on-path"><textPath href="#path" style="text-transform: uppercase">trees</textPath></text>+ <text id="expanding" x="10" y="270" style="text-transform: uppercase">straße!</text>+ <text id="spaced" x="300" y="30" style="text-transform: uppercase"> a <tspan> b </tspan> c </text>+</svg>+<script>+ test(() => {+ const byId = id => document.getElementById(id);+ const length = id => byId(id).getComputedTextLength();+ println(`uppercase matches literal capitals: ${length("uppercase") === length("literal")}`);+ println(`capitalize matches literal capitals: ${length("capitalize") === length("capitalized")}`);+ println(`uppercase tspan matches literal capitals: ${length("with-tspan") === length("literal-tspan")}`);+ println(`uppercase textPath matches literal capitals: ${length("on-path") === length("literal")}`);++ // SVG DOM indices address the characters before the transform, so the two capitals that ß becomes make up+ // the one cell of its character.+ const expanding = byId("expanding");+ println(`characters: ${expanding.getNumberOfChars()}`);+ const starts = [];+ for (let i = 0; i < expanding.getNumberOfChars(); ++i)+ starts.push(expanding.getStartPositionOfChar(i).x);+ println(`start positions: ${starts.join(" ")}`);+ println(`ß is wider than one capital S: ${expanding.getExtentOfChar(4).width > expanding.getExtentOfChar(0).width}`);++ // White space processing collapses the spaces around transformed characters as around any others.+ println(`characters with spaces collapsed: ${byId("spaced").getNumberOfChars()}`);+ });+</script>