From 1eec6d90b7c5acda99c5917085c33e781495ccb3 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:08:27 +0000 Subject: [PATCH] Sketch text: Bold in a variable font sets its weight axis (#8211) (#8331) A variable font (one file for every weight, as most web fonts ship) has no face marked bold, so Bold failed with "has no bold face". Without a bold face, a face whose wght axis reaches past semibold is now set to weight 700. ttf-parser gets its variable-fonts feature for that. Co-authored-by: Claude Opus 5.5 --- Cargo.toml | 2 +- crates/sketch/src/fonts.rs | 29 ++++++++++++++++++++------- crates/sketch/src/text.rs | 5 ++++- crates/sketch/src/text_style_tests.rs | 18 +++++++++++++++++ 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ab33ded6c..6c0538afa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,7 +80,7 @@ cadmpeg-ir = "=0.6.3" cadmpeg-registry = { version = "=0.6.3", default-features = false, features = ["fcstd", "rhino", "step"] } # fonts (sketch text outlines; MIT OR Apache-2.0, pure Rust) -ttf-parser = { version = "0.25", default-features = false, features = ["std"] } +ttf-parser = { version = "0.25", default-features = false, features = ["std", "variable-fonts"] } # Ends a process group with the system call (MIT; already in the tree through zip). nix = { version = "0.31", default-features = false, features = ["signal"] } diff --git a/crates/sketch/src/fonts.rs b/crates/sketch/src/fonts.rs index 95fd45edf..889da62bf 100644 --- a/crates/sketch/src/fonts.rs +++ b/crates/sketch/src/fonts.rs @@ -38,6 +38,8 @@ pub fn set_font_file_check(check: fn(&Path) -> std::result::Result<(), String>) pub struct FontData { bytes: FontBytes, pub index: u32, + /// The weight a variable face is set to (its `wght` axis), when not its default. + pub weight: Option, } #[derive(Clone)] @@ -61,7 +63,7 @@ impl FontData { pub fn font_data(name: Option<&str>) -> Result { let name = name.map(str::trim).unwrap_or(""); if name.is_empty() || normalize(name) == normalize(DEFAULT_FONT_FAMILY) { - return Ok(FontData { bytes: FontBytes::Builtin, index: 0 }); + return Ok(FontData { bytes: FontBytes::Builtin, index: 0, weight: None }); } if name.len() > MAX_FONT_NAME { return Err(SketchError::Invalid("the font name is too long".into())); @@ -76,7 +78,7 @@ pub fn font_data(name: Option<&str>) -> Result { let index = 0; ttf_parser::Face::parse(&bytes, index) .map_err(|e| SketchError::Invalid(format!("font file `{name}` is not a TrueType/OpenType font: {e}")))?; - return Ok(FontData { bytes: FontBytes::File(bytes), index }); + return Ok(FontData { bytes: FontBytes::File(bytes), index, weight: None }); } find_family_in(&font_dirs(), name)? .ok_or_else(|| SketchError::Invalid(format!("unknown font `{name}`: not an installed font family, and not a .ttf/.otf file path"))) @@ -84,16 +86,21 @@ pub fn font_data(name: Option<&str>) -> Result { /// The face of a font for a style: the bold and/or italic face of an installed family (or the /// file or built-in font itself). True with it: the font has no italic face, so the text is to -/// be slanted instead. A bold style the font does not have is an error (bold is not made up). +/// be slanted instead. A variable face without a bold face of its own is set to Bold on its +/// weight axis. A bold style the font does not have is an error (bold is not made up). pub fn font_data_styled(name: Option<&str>, bold: bool, italic: bool) -> Result<(FontData, bool)> { let trimmed = name.map(str::trim).unwrap_or(""); let installed = !(trimmed.is_empty() || normalize(trimmed) == normalize(DEFAULT_FONT_FAMILY) || is_path(trimmed)); if !installed || !(bold || italic) { - let data = font_data(name)?; + let mut data = font_data(name)?; let (face_bold, face_italic) = ttf_parser::Face::parse(data.bytes(), data.index) .map(|face| (face.is_bold(), face.is_italic() || face.is_oblique())) .map_err(|e| SketchError::Invalid(format!("font: {e}")))?; if bold && !face_bold { + if let Some(weight) = variable_bold(&data) { + data.weight = Some(weight); + return Ok((data, italic && !face_italic)); + } let which = if trimmed.is_empty() || normalize(trimmed) == normalize(DEFAULT_FONT_FAMILY) { "the built-in font".to_string() } else { @@ -106,15 +113,23 @@ pub fn font_data_styled(name: Option<&str>, bold: bool, italic: bool) -> Result< if trimmed.len() > MAX_FONT_NAME { return Err(SketchError::Invalid("the font name is too long".into())); } - let Some((data, face_bold, face_italic)) = find_style_in(&font_dirs(), trimmed, bold, italic)? else { + let Some((mut data, face_bold, face_italic)) = find_style_in(&font_dirs(), trimmed, bold, italic)? else { return Err(SketchError::Invalid(format!("unknown font `{trimmed}`: not an installed font family, and not a .ttf/.otf file path"))); }; if bold && !face_bold { - return Err(SketchError::Invalid(format!("the font `{trimmed}` has no bold face"))); + data.weight = Some(variable_bold(&data).ok_or_else(|| SketchError::Invalid(format!("the font `{trimmed}` has no bold face")))?); } Ok((data, italic && !face_italic)) } +/// Bold on a variable face's weight axis: 700 (the weight fonts name Bold), within the axis, when +/// the axis reaches past semibold from a lighter default. None for a face with no such axis. +fn variable_bold(data: &FontData) -> Option { + let face = ttf_parser::Face::parse(data.bytes(), data.index).ok()?; + let axis = face.variation_axes().into_iter().find(|axis| axis.tag == ttf_parser::Tag::from_bytes(b"wght"))?; + (axis.def_value < 600.0 && axis.max_value >= 600.0).then(|| 700_f32.clamp(axis.min_value, axis.max_value)) +} + /// An installed face whose family, full or PostScript name is `name`, searched in `dirs`. pub fn find_family_in(dirs: &[PathBuf], name: &str) -> Result> { Ok(find_style_in(dirs, name, false, false)?.map(|(data, _, _)| data)) @@ -149,7 +164,7 @@ pub fn find_style_in(dirs: &[PathBuf], name: &str, bold: bool, italic: bool) -> } if let Some((_, path, index, face_bold, face_italic)) = best { let bytes = read_font(&path).map_err(|e| SketchError::Invalid(format!("font file `{}`: {e}", path.display())))?; - return Ok(Some((FontData { bytes: FontBytes::File(bytes), index }, face_bold, face_italic))); + return Ok(Some((FontData { bytes: FontBytes::File(bytes), index, weight: None }, face_bold, face_italic))); } } Ok(None) diff --git a/crates/sketch/src/text.rs b/crates/sketch/src/text.rs index 7327fb680..b04a24027 100644 --- a/crates/sketch/src/text.rs +++ b/crates/sketch/src/text.rs @@ -200,7 +200,10 @@ impl<'a> TextMetrics<'a> { /// The face of `font` set in `style`: its letter and line spacing (its bold and italic chose the face). pub fn new(font: &'a FontData, style: &TextStyle) -> Result> { check_spacing(style)?; - let face = ttf_parser::Face::parse(font.bytes(), font.index).map_err(|e| SketchError::Invalid(format!("font: {e}")))?; + let mut face = ttf_parser::Face::parse(font.bytes(), font.index).map_err(|e| SketchError::Invalid(format!("font: {e}")))?; + if let Some(weight) = font.weight { + face.set_variation(ttf_parser::Tag::from_bytes(b"wght"), weight); + } Ok(TextMetrics { cap: cap_height(&face), pitch: f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()), diff --git a/crates/sketch/src/text_style_tests.rs b/crates/sketch/src/text_style_tests.rs index 14b9431dd..b44c7ee58 100644 --- a/crates/sketch/src/text_style_tests.rs +++ b/crates/sketch/src/text_style_tests.rs @@ -84,6 +84,24 @@ fn italic_without_an_italic_face_slants_and_bold_without_a_bold_face_is_an_error assert!(e.to_string().contains("no bold face"), "{e}"); } +/// #8211: a variable font (one file for every weight, as most web fonts ship) has no bold face of +/// its own; Bold sets its weight axis to 700, so the strokes widen at the same height. +#[test] +fn bold_in_a_variable_font_sets_its_weight_axis() { + let file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/ibm-plex-sans/IBMPlexSans-Variable.ttf"); + let font = file.to_string_lossy().into_owned(); + let set = |style: &TextStyle| extent(&text_geometry_styled(Some(&font), "l", Vec2::ZERO, 10.0, 0.0, style, None).unwrap()); + let (plain, bold) = (set(&TextStyle::default()), set(&TextStyle { bold: true, ..TextStyle::default() })); + let width = |(lo, hi): (Vec2, Vec2)| hi.x - lo.x; + assert!(width(bold) > 1.25 * width(plain), "the stroke widens: {plain:?} {bold:?}"); + assert!((bold.1.y - plain.1.y).abs() < 0.05 * 10.0, "the same height: {plain:?} {bold:?}"); + let (data, slanted) = crate::font_data_styled(Some(&font), true, false).unwrap(); + assert_eq!((data.weight, slanted), (Some(700.0), false)); + // A font without a weight axis still has no bold to give. + let e = text_geometry_styled(None, "l", Vec2::ZERO, 10.0, 0.0, &TextStyle { bold: true, ..TextStyle::default() }, None).unwrap_err(); + assert!(e.to_string().contains("no bold face"), "{e}"); +} + #[test] fn text_on_a_straight_path_stands_on_it_reading_left_to_right_whichever_way_it_was_drawn() { let plain = styled("Hi", &TextStyle::default(), None);