diff --git a/crates/svgr/tests/tests/text/font-weight/650.png b/crates/svgr/tests/tests/text/font-weight/650.png index df2f08deb..0a1ef9b0f 100644 Binary files a/crates/svgr/tests/tests/text/font-weight/650.png and b/crates/svgr/tests/tests/text/font-weight/650.png differ diff --git a/crates/usvgr/src/parser/filter.rs b/crates/usvgr/src/parser/filter.rs index 879741493..08f07599f 100644 --- a/crates/usvgr/src/parser/filter.rs +++ b/crates/usvgr/src/parser/filter.rs @@ -664,10 +664,11 @@ fn convert_convolve_matrix(fe: SvgNode, primitives: &[Primitive]) -> Option(AId::Order) { - let mut s = svgrtypes::NumberListParser::from(value); - let x = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(3); - let y = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(x); + // A list, so that a number set from code, which has no text, is read too. + if let Some(value) = fe.attribute::>(AId::Order) { + let mut s = value.into_iter(); + let x = s.next().map(|n| n as i32).unwrap_or(3); + let y = s.next().map(|n| n as i32).unwrap_or(x); if x > 0 && y > 0 { order_x = x as u32; order_y = y as u32; diff --git a/crates/usvgr/src/parser/svgtree/mod.rs b/crates/usvgr/src/parser/svgtree/mod.rs index 55d58876e..79bbe03a2 100644 --- a/crates/usvgr/src/parser/svgtree/mod.rs +++ b/crates/usvgr/src/parser/svgtree/mod.rs @@ -1394,8 +1394,18 @@ impl<'a, 'input: 'a> FromValue<'a, 'input> for MaybeTransform { } impl<'a, 'input: 'a> FromValue<'a, 'input> for svgrtypes::TransformOrigin { - fn parse(_: SvgNode, _: AId, value: SvgAttributeValueRef<'a>) -> Option { - Self::from_str(value.as_str()?).ok() + fn parse(node: SvgNode, aid: AId, value: SvgAttributeValueRef<'a>) -> Option { + match value { + // A single number or length is the horizontal offset and the vertical one is the + // center, as in the text form. One set from code or parsed at compile time has no + // text to parse. + SvgAttributeValueRef::Float(..) | SvgAttributeValueRef::Length(_) => Some(Self::new( + svgrtypes::Length::parse(node, aid, value)?, + svgrtypes::Length::new(50.0, LengthUnit::Percent), + svgrtypes::Length::new(0.0, LengthUnit::Px), + )), + _ => Self::from_str(value.as_str()?).ok(), + } } } diff --git a/crates/usvgr/src/parser/text.rs b/crates/usvgr/src/parser/text.rs index c3470dbdd..b156b4a12 100644 --- a/crates/usvgr/src/parser/text.rs +++ b/crates/usvgr/src/parser/text.rs @@ -2,6 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. +use std::str::FromStr; use std::sync::Arc; use kurbo::{ParamCurve, ParamCurveArclen}; @@ -589,61 +590,57 @@ fn conv_font_stretch(node: SvgNode) -> FontStretch { } fn resolve_font_weight(node: SvgNode) -> u16 { - fn bound(min: usize, val: usize, max: usize) -> usize { - std::cmp::max(min, std::cmp::min(max, val)) - } - let nodes: Vec<_> = node.ancestors().collect(); let mut weight = 400; for n in nodes.iter().rev().skip(1) { // skip Root - // A number set from code has no text: read the number (CSS allows 1 to 1000). - // A non-finite one is invalid and, like invalid text, keeps the inherited weight. + // A number set from code has no text: read the number. if let Some(SvgAttributeValueRef::Float(number, _)) = n.attribute_value(AId::FontWeight) { - if number.is_finite() { - weight = number.round().clamp(1.0, 1000.0) as usize; - } + weight = font_weight_number(number).unwrap_or(weight); continue; } - weight = match n.attribute(AId::FontWeight).unwrap_or("") { - "normal" => 400, - "bold" => 700, - "100" => 100, - "200" => 200, - "300" => 300, - "400" => 400, - "500" => 500, - "600" => 600, - "700" => 700, - "800" => 800, - "900" => 900, - "bolder" => { - // By the CSS2 spec the default value should be 400 - // so `bolder` will result in 500. - // But Chrome and Inkscape will give us 700. - // Have no idea is it a bug or something, but - // we will follow such behavior for now. - let step = if weight == 400 { 300 } else { 100 }; - - bound(100, weight + step, 900) + // CSS keywords are ASCII case-insensitive. + let text = n.attribute(AId::FontWeight).unwrap_or("").trim(); + weight = if text.eq_ignore_ascii_case("normal") { + 400 + } else if text.eq_ignore_ascii_case("bold") { + 700 + } else if text.eq_ignore_ascii_case("bolder") { + // The relative weights of CSS Fonts 4, as browsers compute them. + match weight { + ..350 => 400, + 350..550 => 700, + 550..900 => 900, + _ => weight, } - "lighter" => { - // By the CSS2 spec the default value should be 400 - // so `lighter` will result in 300. - // But Chrome and Inkscape will give us 200. - // Have no idea is it a bug or something, but - // we will follow such behavior for now. - let step = if weight == 400 { 200 } else { 100 }; - - bound(100, weight.saturating_sub(step), 900) + } else if text.eq_ignore_ascii_case("lighter") { + match weight { + ..100 => weight, + 100..550 => 100, + 550..750 => 400, + _ => 700, } - _ => weight, + } else { + // Any number, not only the multiples of 100: variable fonts have every weight. + svgrtypes::Number::from_str(text) + .ok() + .and_then(|number| font_weight_number(number.0 as f32)) + .unwrap_or(weight) }; } weight as u16 } +/// The weight of a `font-weight` number, the same whether it is written in the SVG or set +/// from code. CSS Fonts 4 allows any number from 1 to 1000, as browsers do; one outside, or +/// not finite, is invalid and keeps the inherited weight, like invalid text. +fn font_weight_number(number: f32) -> Option { + (1.0..=1000.0) + .contains(&number) + .then(|| number.round() as usize) +} + /// Resolves text's character positions. /// /// This includes: x, y, dx, dy. diff --git a/crates/usvgr/tests/parser.rs b/crates/usvgr/tests/parser.rs index 30c14f9cd..5fad1b67f 100644 --- a/crates/usvgr/tests/parser.rs +++ b/crates/usvgr/tests/parser.rs @@ -909,8 +909,52 @@ mod numbers_set_from_code { #[test] fn font_weight_lighter_than_a_small_number() { + // CSS Fonts 4: `lighter` keeps a weight below 100. let doc = nested_weights(SvgAttributeValue::from(1.0), s("lighter")); - assert!(written(&doc).contains(r#"font-weight="100""#)); + assert!(written(&doc).contains(r#"font-weight="1""#)); + } + + /// `bolder` and `lighter` follow the table of CSS Fonts 4, as browsers do (checked in + /// Chrome 154), and keywords are case-insensitive. + #[test] + fn font_weight_relative_keywords() { + let cases = [ + (1.0, "bolder", 400), + (100.0, "bolder", 400), + (300.0, "bolder", 400), + (400.0, "bolder", 700), + (500.0, "bolder", 700), + (600.0, "bolder", 900), + (650.0, "bolder", 900), + (700.0, "bolder", 900), + (800.0, "bolder", 900), + (900.0, "bolder", 900), + (1000.0, "bolder", 1000), + (1.0, "lighter", 1), + (100.0, "lighter", 100), + (200.0, "lighter", 100), + (400.0, "lighter", 100), + (500.0, "lighter", 100), + (600.0, "lighter", 400), + (650.0, "lighter", 400), + (700.0, "lighter", 400), + (800.0, "lighter", 700), + (900.0, "lighter", 700), + (1000.0, "lighter", 700), + (300.0, "BOLD", 700), + (300.0, " Normal ", 400), + (300.0, " 650 ", 650), + ]; + for (parent, child, expected) in cases { + let out = written(&nested_weights(SvgAttributeValue::from(parent), s(child))); + // The writer leaves out the default weight. + let weight = if expected == 400 { + !out.contains("font-weight=") + } else { + out.contains(&format!(r#"font-weight="{expected}""#)) + }; + assert!(weight, "{parent} {child:?} should be {expected}:\n{out}"); + } } #[test] @@ -996,4 +1040,411 @@ mod numbers_set_from_code { )) }); } + + /// Writes the tree twice: with text kept, and with text converted to paths, so that both + /// the resolved attributes and their effect on the layout are compared. + fn written_with_layout(doc: &NestedSvgDocument) -> String { + let mut fontdb = usvgr::fontdb::Database::new(); + for font in [ + &include_bytes!("../../svgr/tests/fonts/NotoSans-Regular.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/NotoSans-Bold.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/NotoSans-Light.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/RobotoFlex.subset.ttf")[..], + ] { + fontdb.load_font_data(font.to_vec()); + } + let tree = + usvgr::Tree::from_nested_svgtree(doc, &usvgr::Options::default(), &fontdb).unwrap(); + let mut out = tree.to_string(&usvgr::WriteOptions { + preserve_text: true, + ..Default::default() + }); + out.push_str(&tree.to_string(&usvgr::WriteOptions::default())); + out + } + + /// Builds the document of `template`, an SVG in which `?` marks the element under test. + /// That element gets `attr` instead of the template's value of it, or none for `None`. + fn from_template( + template: &str, + attr: Option<(AId, SvgAttributeValue<'static>)>, + ) -> NestedSvgDocument<'static> { + fn convert( + node: usvgr::roxmltree::Node, + attr: &Option<(AId, SvgAttributeValue<'static>)>, + ) -> Option> { + if node.is_text() { + let content = node.text()?; + return Some(NestedNodeData { + kind: NestedNodeKind::Text(StringStorage::Owned(content.into())), + attrs: Box::new([]), + children: vec![], + static_hash: None, + }); + } + let mut attrs: Attrs = node + .attributes() + .filter_map(|a| Some((AId::from_str(a.name())?, a.value().to_owned().into()))) + .collect(); + if node.has_attribute("under-test") { + if let Some((aid, value)) = attr { + attrs.retain(|(name, _)| name != aid); + attrs.push((*aid, value.clone())); + } + } + let children = node.children().filter_map(|c| convert(c, attr)).collect(); + Some(el(EId::from_str(node.tag_name().name())?, attrs, children)) + } + + let xml = template.replace('?', "under-test=''"); + let xml = usvgr::roxmltree::Document::parse(&xml).unwrap(); + NestedSvgDocument::from_nodes(vec![convert(xml.root_element(), &attr)]) + } + + macro_rules! doc { + ($body:expr) => { + concat!("", $body, "") + }; + } + + macro_rules! filtered { + ($primitive:literal) => { + doc!(concat!( + "", + $primitive, + "" + )) + }; + } + + macro_rules! painted { + ($server:literal) => { + doc!(concat!( + "", + $server, + "" + )) + }; + } + + const RECT: &str = doc!( + "" + ); + const ROTATED: &str = + doc!(""); + const STROKED: &str = doc!(""); + const CIRCLE: &str = doc!(""); + const ELLIPSE: &str = doc!(""); + const LINE: &str = doc!(""); + const LINEAR: &str = painted!(""); + const RADIAL: &str = painted!(""); + const STOP: &str = painted!(""); + const PATTERN: &str = painted!(""); + const NESTED_SVG: &str = doc!( + "" + ); + const USE: &str = doc!(""); + const MARKER: &str = doc!(""); + const MASK: &str = doc!(""); + const LABEL: &str = + doc!("Ab cd"); + const VARIABLE_LABEL: &str = + doc!("Ab cd"); + const KERNED_LABEL: &str = + doc!("AVAT To"); + const TSPAN: &str = doc!( + "Abcd" + ); + const TEXT_PATH: &str = doc!("Ab cd"); + const FILTER_REGION: &str = doc!(""); + const BLUR: &str = filtered!(""); + const OFFSET: &str = filtered!(""); + const FLOOD: &str = filtered!(""); + const DROP_SHADOW: &str = filtered!(""); + const MORPHOLOGY: &str = filtered!(""); + const TURBULENCE: &str = filtered!(""); + const SATURATE: &str = filtered!(""); + const LINEAR_TRANSFER: &str = + filtered!(""); + const GAMMA_TRANSFER: &str = + filtered!(""); + const ARITHMETIC: &str = filtered!(""); + const CONVOLVE: &str = + filtered!(""); + const CONVOLVE_ONE: &str = filtered!(""); + const CONVOLVE_FOUR: &str = filtered!(""); + const DISPLACEMENT: &str = + filtered!(""); + const DIFFUSE: &str = filtered!( + "" + ); + const SPECULAR: &str = filtered!( + "" + ); + const DISTANT_LIGHT: &str = filtered!( + "" + ); + const POINT_LIGHT: &str = filtered!( + "" + ); + const SPOT_LIGHT: &str = filtered!(""); + const SPOT_LIGHT_CONE: &str = + filtered!(""); + + /// Every attribute usvgr reads that accepts a plain number, in an element where it has an + /// effect, with a number different from its default. + const NUMBERS: &[(&str, f32, &str, &str)] = &[ + ("opacity", 0.5, "0.5", RECT), + ("fill-opacity", 0.5, "0.5", RECT), + ("stroke-opacity", 0.5, "0.5", RECT), + ("stroke-width", 7.0, "7", RECT), + ("x", 20.0, "20", RECT), + ("y", 20.0, "20", RECT), + ("width", 30.0, "30", RECT), + ("height", 30.0, "30", RECT), + ("rx", 5.0, "5", RECT), + ("ry", 5.0, "5", RECT), + ("transform-origin", 40.0, "40", ROTATED), + ("stroke-miterlimit", 1.5, "1.5", STROKED), + ("stroke-dashoffset", 3.0, "3", STROKED), + ("stroke-dasharray", 4.0, "4", STROKED), + ("cx", 40.0, "40", CIRCLE), + ("cy", 40.0, "40", CIRCLE), + ("r", 30.0, "30", CIRCLE), + ("rx", 10.0, "10", ELLIPSE), + ("ry", 10.0, "10", ELLIPSE), + ("x1", 20.0, "20", LINE), + ("y1", 20.0, "20", LINE), + ("x2", 70.0, "70", LINE), + ("y2", 70.0, "70", LINE), + ("x1", 0.2, "0.2", LINEAR), + ("y1", 0.2, "0.2", LINEAR), + ("x2", 0.7, "0.7", LINEAR), + ("y2", 0.7, "0.7", LINEAR), + ("cx", 0.3, "0.3", RADIAL), + ("cy", 0.3, "0.3", RADIAL), + ("r", 0.3, "0.3", RADIAL), + ("fx", 0.4, "0.4", RADIAL), + ("fy", 0.4, "0.4", RADIAL), + ("fr", 0.1, "0.1", RADIAL), + ("offset", 0.3, "0.3", STOP), + ("stop-opacity", 0.5, "0.5", STOP), + ("x", 5.0, "5", PATTERN), + ("y", 5.0, "5", PATTERN), + ("width", 25.0, "25", PATTERN), + ("height", 25.0, "25", PATTERN), + ("x", 10.0, "10", NESTED_SVG), + ("y", 10.0, "10", NESTED_SVG), + ("width", 80.0, "80", NESTED_SVG), + ("height", 80.0, "80", NESTED_SVG), + ("x", 10.0, "10", USE), + ("y", 10.0, "10", USE), + ("width", 80.0, "80", USE), + ("height", 80.0, "80", USE), + ("markerWidth", 6.0, "6", MARKER), + ("markerHeight", 6.0, "6", MARKER), + ("refX", 2.0, "2", MARKER), + ("refY", 2.0, "2", MARKER), + ("orient", 45.0, "45", MARKER), + ("x", 20.0, "20", MASK), + ("y", 20.0, "20", MASK), + ("width", 30.0, "30", MASK), + ("height", 30.0, "30", MASK), + ("font-size", 30.0, "30", LABEL), + ("font-weight", 700.0, "700", LABEL), + ("font-weight", 300.0, "300", LABEL), + ("font-weight", 650.0, "650", LABEL), + ("font-weight", 650.0, "650", VARIABLE_LABEL), + ("font-weight", 550.5, "550.5", VARIABLE_LABEL), + ("letter-spacing", 3.0, "3", LABEL), + ("word-spacing", 9.0, "9", LABEL), + ("x", 20.0, "20", LABEL), + ("y", 70.0, "70", LABEL), + ("dx", 4.0, "4", LABEL), + ("dy", 4.0, "4", LABEL), + ("rotate", 20.0, "20", LABEL), + ("textLength", 150.0, "150", LABEL), + ("kerning", 0.0, "0", KERNED_LABEL), + ("baseline-shift", 6.0, "6", TSPAN), + ("startOffset", 20.0, "20", TEXT_PATH), + ("x", 5.0, "5", FILTER_REGION), + ("y", 5.0, "5", FILTER_REGION), + ("width", 40.0, "40", FILTER_REGION), + ("height", 40.0, "40", FILTER_REGION), + ("stdDeviation", 3.0, "3", BLUR), + ("x", 5.0, "5", BLUR), + ("y", 5.0, "5", BLUR), + ("width", 20.0, "20", BLUR), + ("height", 20.0, "20", BLUR), + ("dx", 5.0, "5", OFFSET), + ("dy", 5.0, "5", OFFSET), + ("flood-opacity", 0.5, "0.5", FLOOD), + ("dx", 5.0, "5", DROP_SHADOW), + ("dy", 5.0, "5", DROP_SHADOW), + ("stdDeviation", 3.0, "3", DROP_SHADOW), + ("flood-opacity", 0.5, "0.5", DROP_SHADOW), + ("radius", 2.0, "2", MORPHOLOGY), + ("baseFrequency", 0.2, "0.2", TURBULENCE), + ("numOctaves", 3.0, "3", TURBULENCE), + ("seed", 7.0, "7", TURBULENCE), + ("values", 0.5, "0.5", SATURATE), + ("slope", 0.5, "0.5", LINEAR_TRANSFER), + ("intercept", 0.5, "0.5", LINEAR_TRANSFER), + ("amplitude", 0.5, "0.5", GAMMA_TRANSFER), + ("exponent", 2.0, "2", GAMMA_TRANSFER), + ("offset", 0.5, "0.5", GAMMA_TRANSFER), + ("k1", 0.5, "0.5", ARITHMETIC), + ("k2", 0.5, "0.5", ARITHMETIC), + ("k3", 0.5, "0.5", ARITHMETIC), + ("k4", 0.5, "0.5", ARITHMETIC), + ("divisor", 2.0, "2", CONVOLVE), + ("bias", 0.5, "0.5", CONVOLVE), + ("targetX", 0.0, "0", CONVOLVE), + ("targetY", 0.0, "0", CONVOLVE), + ("kernelMatrix", 2.0, "2", CONVOLVE_ONE), + ("order", 2.0, "2", CONVOLVE_FOUR), + ("scale", 10.0, "10", DISPLACEMENT), + ("surfaceScale", 3.0, "3", DIFFUSE), + ("diffuseConstant", 2.0, "2", DIFFUSE), + ("specularConstant", 2.0, "2", SPECULAR), + ("specularExponent", 5.0, "5", SPECULAR), + ("surfaceScale", 3.0, "3", SPECULAR), + ("azimuth", 45.0, "45", DISTANT_LIGHT), + ("elevation", 45.0, "45", DISTANT_LIGHT), + ("x", 10.0, "10", POINT_LIGHT), + ("y", 10.0, "10", POINT_LIGHT), + ("z", 10.0, "10", POINT_LIGHT), + ("x", 10.0, "10", SPOT_LIGHT), + ("y", 10.0, "10", SPOT_LIGHT), + ("z", 10.0, "10", SPOT_LIGHT), + ("pointsAtX", 10.0, "10", SPOT_LIGHT), + ("pointsAtY", 10.0, "10", SPOT_LIGHT), + ("pointsAtZ", 10.0, "10", SPOT_LIGHT), + ("specularExponent", 5.0, "5", SPOT_LIGHT), + ("limitingConeAngle", 20.0, "20", SPOT_LIGHT_CONE), + ]; + + /// Every attribute usvgr reads that accepts a length with a unit. svgr-macro parses such a + /// written value at compile time into `Length`, which has no text. + const LENGTHS: &[(&str, &str, &str)] = &[ + ("opacity", "50%", RECT), + ("fill-opacity", "50%", RECT), + ("stroke-opacity", "50%", RECT), + ("stroke-width", "7px", RECT), + ("x", "20%", RECT), + ("width", "30mm", RECT), + ("rx", "5px", RECT), + ("transform-origin", "40px", ROTATED), + ("transform-origin", "50%", ROTATED), + ("stroke-dashoffset", "3px", STROKED), + ("stroke-dasharray", "4px", STROKED), + ("cx", "40%", CIRCLE), + ("r", "30px", CIRCLE), + ("x2", "70%", LINE), + ("x1", "20%", LINEAR), + ("cx", "30%", RADIAL), + ("fr", "10%", RADIAL), + ("offset", "30%", STOP), + ("stop-opacity", "50%", STOP), + ("width", "25px", PATTERN), + ("x", "10px", NESTED_SVG), + ("width", "80%", NESTED_SVG), + ("x", "10px", USE), + ("markerWidth", "6px", MARKER), + ("refX", "2px", MARKER), + ("x", "10%", MASK), + ("font-size", "150%", LABEL), + ("font-size", "2em", LABEL), + ("letter-spacing", "3px", LABEL), + ("word-spacing", "0.5em", LABEL), + ("x", "20px", LABEL), + ("dx", "4px", LABEL), + ("textLength", "150px", LABEL), + ("kerning", "0px", KERNED_LABEL), + ("baseline-shift", "20%", TSPAN), + ("baseline-shift", "6px", TSPAN), + ("startOffset", "20%", TEXT_PATH), + ("x", "10%", FILTER_REGION), + ("width", "5px", BLUR), + ("flood-opacity", "50%", FLOOD), + ]; + + /// Checks that `text` written in the SVG has an effect, and that each of `parsed` renders + /// the same. Returns what differs. + fn same_as_text( + name: &str, + text: &'static str, + template: &str, + parsed: &[(&str, SvgAttributeValue<'static>)], + ) -> Vec { + let aid = AId::from_str(name).unwrap(); + let case = format!("{name}={text} in {template}"); + let runtime = written_with_layout(&from_template(template, Some((aid, s(text))))); + if runtime == written_with_layout(&from_template(template, None)) { + return vec![format!("{case}: the written value has no effect")]; + } + parsed + .iter() + .filter(|(_, value)| { + written_with_layout(&from_template(template, Some((aid, value.clone())))) != runtime + }) + .map(|(form, _)| format!("{case}: the {form} differs from the text")) + .collect() + } + + /// The same number renders the same whether it is written in the SVG (runtime parsing), + /// parsed at compile time, or set from code. + #[test] + fn every_number_attribute() { + let failures: Vec<_> = NUMBERS + .iter() + .flat_map(|&(name, number, text, template)| { + same_as_text( + name, + text, + template, + &[ + ( + "compile-time number", + SvgAttributeValue::Float(number, StringStorage::Borrowed(text)), + ), + ("number from code", SvgAttributeValue::from(number)), + ], + ) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + /// A weight outside 1 to 1000 is invalid in CSS, written or set from code, and keeps the + /// inherited weight. + #[test] + fn font_weight_out_of_range() { + let inherited = written_with_layout(&from_template(LABEL, None)); + for (number, text) in [(1500.0, "1500"), (0.0, "0"), (-700.0, "-700"), (0.5, "0.5")] { + for value in [s(text), SvgAttributeValue::from(number)] { + let doc = from_template(LABEL, Some((AId::FontWeight, value))); + assert_eq!(written_with_layout(&doc), inherited, "font-weight {text}"); + } + } + } + + /// A length written in the SVG renders the same as the one svgr-macro parses at compile + /// time. + #[test] + fn every_length_attribute() { + let failures: Vec<_> = LENGTHS + .iter() + .flat_map(|&(name, text, template)| { + let length = text.parse().unwrap(); + same_as_text( + name, + text, + template, + &[("compile-time length", SvgAttributeValue::Length(length))], + ) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); + } }