From 553c86719ce9d57f01bcfb6442ac68ac58cd65de Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:14:57 +0000 Subject: [PATCH 1/6] Share catalog face metrics and glyph outlines --- Cargo.lock | 1 + crates/font-catalog/Cargo.toml | 1 + crates/font-catalog/src/lib.rs | 2 + crates/font-catalog/src/outline.rs | 133 +++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+) create mode 100644 crates/font-catalog/src/outline.rs diff --git a/Cargo.lock b/Cargo.lock index 9fb46057c..9424cf3fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1761,6 +1761,7 @@ name = "craft-font-catalog" version = "0.1.0" dependencies = [ "fontique", + "kurbo 0.13.1", "skrifa 0.47.0", "thiserror 2.0.21", "windows-registry", diff --git a/crates/font-catalog/Cargo.toml b/crates/font-catalog/Cargo.toml index a95e1c28f..1f0830a63 100644 --- a/crates/font-catalog/Cargo.toml +++ b/crates/font-catalog/Cargo.toml @@ -15,6 +15,7 @@ default = ["system"] system = ["dep:fontique"] [dependencies] +kurbo = { workspace = true } skrifa = { version = "0.47", default-features = false, features = ["std"] } thiserror = { workspace = true } diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index c787d3ece..7da4ca310 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -23,6 +23,7 @@ mod catalog; mod env; mod fontconfig; +mod outline; mod registry; mod scan; mod suitcase; @@ -31,6 +32,7 @@ pub mod system; pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch}; pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs}; pub use fontconfig::fontconfig_dirs; +pub use outline::{FontOutline, OutlineError}; pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width}; #[cfg(test)] diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs new file mode 100644 index 000000000..cd27e0c53 --- /dev/null +++ b/crates/font-catalog/src/outline.rs @@ -0,0 +1,133 @@ +//! Unhinted glyph outlines and metrics for catalog faces. + +use kurbo::BezPath; +use skrifa::instance::{Location, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; + +use crate::{FontData, LoadedFace}; + +/// A parsed face and its variation location. Coordinates use font design units, with y up. +/// The bytes can come from a catalog or any other source, including a collection face. +pub struct FontOutline<'a> { + font: FontRef<'a>, + location: Location, +} + +/// Why a font or glyph outline could not be read. +#[derive(Debug, thiserror::Error)] +pub enum OutlineError { + /// The face index or font data is invalid. + #[error("invalid font face")] + InvalidFace, + /// The glyph has no outline in this face. + #[error("glyph has no outline")] + MissingGlyph, + /// The glyph's outline is malformed. + #[error("cannot draw glyph outline: {0}")] + Draw(#[from] skrifa::outline::DrawError), +} + +impl<'a> FontOutline<'a> { + /// Parse the given face and select axis values in user units. Unknown axes are ignored and + /// values are clamped to their axis ranges by the font parser. + pub fn new(data: &'a FontData, variations: &[([u8; 4], f32)]) -> Result { + Self::from_bytes(&data.bytes, data.index, variations) + } + + /// Parse borrowed bytes and a collection face index without copying the font. + pub fn from_bytes(bytes: &'a [u8], index: u32, variations: &[([u8; 4], f32)]) -> Result { + let font = FontRef::from_index(bytes, index).map_err(|_| OutlineError::InvalidFace)?; + let location = font.axes().location(variations.iter().map(|(tag, value)| (Tag::new(tag), *value))); + Ok(Self { font, location }) + } + + /// Parse a catalog face, retaining the axis settings of a named instance. + pub fn from_loaded(face: &'a LoadedFace) -> Result { + Self::new(&face.data, &face.info.variations) + } + + /// Font-wide metrics in unscaled design units at this variation location. + pub fn metrics(&self) -> skrifa::metrics::Metrics { + self.font.metrics(Size::unscaled(), &self.location) + } + + /// Resolve a Unicode scalar to a glyph identifier. + pub fn glyph_for(&self, character: char) -> Option { + self.font.charmap().map(character).map(|id| id.to_u32()) + } + + /// Draw a glyph in design units. Empty glyphs such as spaces can produce an empty path. + pub fn outline(&self, glyph: u32) -> Result { + let outline = self.font.outline_glyphs().get(GlyphId::new(glyph)).ok_or(OutlineError::MissingGlyph)?; + let mut pen = PathPen(BezPath::new()); + outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut pen)?; + Ok(pen.0) + } +} + +struct PathPen(BezPath); +impl OutlinePen for PathPen { + fn move_to(&mut self, x: f32, y: f32) { + self.0.move_to((f64::from(x), f64::from(y))); + } + fn line_to(&mut self, x: f32, y: f32) { + self.0.line_to((f64::from(x), f64::from(y))); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + self.0.quad_to((f64::from(x1), f64::from(y1)), (f64::from(x), f64::from(y))); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + self.0.curve_to((f64::from(x1), f64::from(y1)), (f64::from(x2), f64::from(y2)), (f64::from(x), f64::from(y))); + } + fn close(&mut self) { + self.0.close_path(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::PathEl; + use std::sync::Arc; + + #[test] + fn rejects_invalid_face_and_collection_index() { + let data = FontData { bytes: Arc::from(&b"not a font"[..]), index: 0 }; + assert!(matches!(FontOutline::new(&data, &[]), Err(OutlineError::InvalidFace))); + } + + #[test] + fn pen_preserves_geometry_and_upward_y() { + let mut pen = PathPen(BezPath::new()); + pen.move_to(1.0, 2.0); + pen.line_to(3.0, 4.0); + pen.quad_to(5.0, 6.0, 7.0, 8.0); + pen.curve_to(9.0, 10.0, 11.0, 12.0, 13.0, 14.0); + pen.close(); + assert_eq!( + pen.0.elements(), + &[ + PathEl::MoveTo((1.0, 2.0).into()), + PathEl::LineTo((3.0, 4.0).into()), + PathEl::QuadTo((5.0, 6.0).into(), (7.0, 8.0).into()), + PathEl::CurveTo((9.0, 10.0).into(), (11.0, 12.0).into(), (13.0, 14.0).into()), + PathEl::ClosePath, + ] + ); + } + + #[test] + fn reads_craft_font_when_available() { + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-hebrew/NotoSansHebrew-Regular.ttf")).unwrap(); + let data = FontData { bytes: bytes.into(), index: 0 }; + let face = FontOutline::new(&data, &[]).unwrap(); + assert!(face.metrics().units_per_em > 0); + let glyph = face.glyph_for('א').unwrap(); + assert!(!face.outline(glyph).unwrap().elements().is_empty()); + assert!(matches!(face.outline(u32::MAX), Err(OutlineError::MissingGlyph))); + let invalid_index = FontData { bytes: data.bytes.clone(), index: u32::MAX }; + assert!(matches!(FontOutline::new(&invalid_index, &[]), Err(OutlineError::InvalidFace))); + } +} From c714810569eab85751713bea62c5833ae10af9b9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:15:51 +0000 Subject: [PATCH 2/6] Test outlines at variable font weights --- crates/font-catalog/src/outline.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs index cd27e0c53..1f550f983 100644 --- a/crates/font-catalog/src/outline.rs +++ b/crates/font-catalog/src/outline.rs @@ -130,4 +130,18 @@ mod tests { let invalid_index = FontData { bytes: data.bytes.clone(), index: u32::MAX }; assert!(matches!(FontOutline::new(&invalid_index, &[]), Err(OutlineError::InvalidFace))); } + + #[test] + fn variation_changes_glyph_geometry() { + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-arabic/NotoSansArabic.ttf")).unwrap(); + let data = FontData { bytes: bytes.into(), index: 0 }; + let light = FontOutline::new(&data, &[(*b"wght", 100.0)]).unwrap(); + let bold = FontOutline::new(&data, &[(*b"wght", 900.0)]).unwrap(); + let glyph = light.glyph_for('ب').unwrap(); + let light_path = light.outline(glyph).unwrap(); + let bold_path = bold.outline(glyph).unwrap(); + assert!(!light_path.elements().is_empty()); + assert_ne!(light_path, bold_path); + } } From 14bccd4e09094820babc434d2681297be8873bd9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:18:57 +0000 Subject: [PATCH 3/6] Bound and expose partial glyph outlines --- crates/font-catalog/src/outline.rs | 92 ++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 11 deletions(-) diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs index 1f550f983..10a1ae8ab 100644 --- a/crates/font-catalog/src/outline.rs +++ b/crates/font-catalog/src/outline.rs @@ -26,6 +26,12 @@ pub enum OutlineError { /// The glyph's outline is malformed. #[error("cannot draw glyph outline: {0}")] Draw(#[from] skrifa::outline::DrawError), + /// The glyph emitted more path elements than the safety limit. + #[error("glyph outline exceeds the element limit")] + TooComplex, + /// The outline starts without a move command. + #[error("glyph outline has no initial move")] + InvalidPath, } impl<'a> FontOutline<'a> { @@ -58,30 +64,83 @@ impl<'a> FontOutline<'a> { } /// Draw a glyph in design units. Empty glyphs such as spaces can produce an empty path. + /// A malformed or excessively complex glyph returns an error instead of partial geometry. pub fn outline(&self, glyph: u32) -> Result { + let (path, status) = self.outline_recovering(glyph)?; + status.map(|()| path) + } + + /// Draw a glyph while retaining the bounded prefix produced before a draw error. This is + /// useful for consumers preserving existing rendering of damaged fonts. The inner result + /// reports whether the returned path is complete; the outer error means no glyph was found. + /// Paths stop growing at 100,000 elements, even when the font is untrusted. + pub fn outline_recovering(&self, glyph: u32) -> Result<(BezPath, Result<(), OutlineError>), OutlineError> { let outline = self.font.outline_glyphs().get(GlyphId::new(glyph)).ok_or(OutlineError::MissingGlyph)?; - let mut pen = PathPen(BezPath::new()); - outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut pen)?; - Ok(pen.0) + let mut pen = PathPen::new(); + let result = outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut pen); + let status = if pen.invalid { + Err(OutlineError::InvalidPath) + } else if pen.truncated { + Err(OutlineError::TooComplex) + } else { + result.map(|_| ()).map_err(OutlineError::Draw) + }; + Ok((pen.path, status)) } } -struct PathPen(BezPath); +const MAX_OUTLINE_ELEMENTS: usize = 100_000; +struct PathPen { + path: BezPath, + truncated: bool, + invalid: bool, +} +impl PathPen { + fn new() -> Self { + Self { path: BezPath::new(), truncated: false, invalid: false } + } + fn has_start(&mut self) -> bool { + if self.path.elements().is_empty() { + self.invalid = true; + false + } else { + true + } + } + fn room(&mut self) -> bool { + if self.path.elements().len() >= MAX_OUTLINE_ELEMENTS { + self.truncated = true; + false + } else { + true + } + } +} impl OutlinePen for PathPen { fn move_to(&mut self, x: f32, y: f32) { - self.0.move_to((f64::from(x), f64::from(y))); + if self.room() { + self.path.move_to((f64::from(x), f64::from(y))); + } } fn line_to(&mut self, x: f32, y: f32) { - self.0.line_to((f64::from(x), f64::from(y))); + if self.has_start() && self.room() { + self.path.line_to((f64::from(x), f64::from(y))); + } } fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { - self.0.quad_to((f64::from(x1), f64::from(y1)), (f64::from(x), f64::from(y))); + if self.has_start() && self.room() { + self.path.quad_to((f64::from(x1), f64::from(y1)), (f64::from(x), f64::from(y))); + } } fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { - self.0.curve_to((f64::from(x1), f64::from(y1)), (f64::from(x2), f64::from(y2)), (f64::from(x), f64::from(y))); + if self.has_start() && self.room() { + self.path.curve_to((f64::from(x1), f64::from(y1)), (f64::from(x2), f64::from(y2)), (f64::from(x), f64::from(y))); + } } fn close(&mut self) { - self.0.close_path(); + if self.has_start() && self.room() { + self.path.close_path(); + } } } @@ -99,14 +158,14 @@ mod tests { #[test] fn pen_preserves_geometry_and_upward_y() { - let mut pen = PathPen(BezPath::new()); + let mut pen = PathPen::new(); pen.move_to(1.0, 2.0); pen.line_to(3.0, 4.0); pen.quad_to(5.0, 6.0, 7.0, 8.0); pen.curve_to(9.0, 10.0, 11.0, 12.0, 13.0, 14.0); pen.close(); assert_eq!( - pen.0.elements(), + pen.path.elements(), &[ PathEl::MoveTo((1.0, 2.0).into()), PathEl::LineTo((3.0, 4.0).into()), @@ -117,6 +176,17 @@ mod tests { ); } + #[test] + fn pen_caps_path_growth() { + let mut pen = PathPen::new(); + pen.move_to(0.0, 0.0); + for _ in 0..MAX_OUTLINE_ELEMENTS { + pen.line_to(1.0, 2.0); + } + assert_eq!(pen.path.elements().len(), MAX_OUTLINE_ELEMENTS); + assert!(pen.truncated); + } + #[test] fn reads_craft_font_when_available() { let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; From 58e2a887e6fe346deff2708513b0c1cd7c2af8c3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:28:01 +0000 Subject: [PATCH 4/6] Compare malformed CFF recovery with direct drawing --- crates/font-catalog/src/outline.rs | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs index 10a1ae8ab..d1b3aafe4 100644 --- a/crates/font-catalog/src/outline.rs +++ b/crates/font-catalog/src/outline.rs @@ -214,4 +214,38 @@ mod tests { assert!(!light_path.elements().is_empty()); assert_ne!(light_path, bold_path); } + + #[test] + fn malformed_cff_recovers_the_same_prefix_as_direct_drawing() { + use skrifa::raw::ps::cff::CffFontRef; + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let mut bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-cjk-sc/NotoSansCJKsc-Regular.otf")).unwrap(); + let (gid, start, len) = { + let f = FontRef::new(&bytes).unwrap(); + let cff = f.table_data(Tag::new(b"CFF ")).unwrap().as_bytes(); + let cff = CffFontRef::new(cff, 0, None).unwrap(); + let (gid, cs) = (0..cff.num_glyphs()) + .find_map(|gid| { + let cs = cff.charstrings().get(gid as usize)?; + (cs.len() >= 8).then_some((gid, cs)) + }) + .unwrap(); + (gid, cs.as_ptr() as usize - bytes.as_ptr() as usize, cs.len()) + }; + assert!(len >= 8); + // A move and line followed by a Type 2 callsubr without an operand. It emits a path + // prefix before the parser reports an error, without changing the font table offsets. + bytes[start..start + 8].copy_from_slice(&[139, 139, 21, 239, 139, 5, 10, 14]); + let f = FontRef::new(&bytes).unwrap(); + let mut old = PathPen::new(); + let result = + f.outline_glyphs().get(GlyphId::new(gid)).unwrap().draw(DrawSettings::unhinted(Size::unscaled(), &Location::default()), &mut old); + assert!(result.is_err()); + assert!(!old.path.elements().is_empty()); + let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + let (prefix, status) = shared.outline_recovering(gid).unwrap(); + assert!(matches!(status, Err(OutlineError::Draw(_)))); + assert_eq!(prefix, old.path); + assert!(matches!(shared.outline(gid), Err(OutlineError::Draw(_)))); + } } From 4d51586a45321b101f608276ce7ccbcec3f1fab3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:38:31 +0000 Subject: [PATCH 5/6] Stream glyph outlines into caller-owned pens --- crates/font-catalog/src/lib.rs | 2 +- crates/font-catalog/src/outline.rs | 152 +++++++++++++++++++++++++++-- 2 files changed, 146 insertions(+), 8 deletions(-) diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index 7da4ca310..3e0e7376e 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -32,7 +32,7 @@ pub mod system; pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch}; pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs}; pub use fontconfig::fontconfig_dirs; -pub use outline::{FontOutline, OutlineError}; +pub use outline::{FontOutline, GlyphPen, OutlineError}; pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width}; #[cfg(test)] diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs index d1b3aafe4..c5a79b72e 100644 --- a/crates/font-catalog/src/outline.rs +++ b/crates/font-catalog/src/outline.rs @@ -14,6 +14,40 @@ pub struct FontOutline<'a> { location: Location, } +/// Receives unhinted glyph commands in design units (y up). Implementations own their +/// storage and resource policy; drawing writes directly to the sink without an intermediate path. +pub trait GlyphPen { + /// Start a contour. + fn move_to(&mut self, x: f32, y: f32); + /// Add a straight segment. + fn line_to(&mut self, x: f32, y: f32); + /// Add a quadratic segment. + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32); + /// Add a cubic segment. + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32); + /// Close the current contour. + fn close(&mut self); +} + +struct Sink<'a>(&'a mut dyn GlyphPen); +impl OutlinePen for Sink<'_> { + fn move_to(&mut self, x: f32, y: f32) { + self.0.move_to(x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + self.0.line_to(x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + self.0.quad_to(x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + self.0.curve_to(x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + self.0.close(); + } +} + /// Why a font or glyph outline could not be read. #[derive(Debug, thiserror::Error)] pub enum OutlineError { @@ -63,6 +97,14 @@ impl<'a> FontOutline<'a> { self.font.charmap().map(character).map(|id| id.to_u32()) } + /// Stream an unhinted glyph into the caller's sink. On an error, commands already sent + /// remain in the sink. The sink owns any allocation and enforces its own resource limit. + pub fn draw_to(&self, glyph: u32, pen: &mut dyn GlyphPen) -> Result<(), OutlineError> { + let outline = self.font.outline_glyphs().get(GlyphId::new(glyph)).ok_or(OutlineError::MissingGlyph)?; + outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut Sink(pen))?; + Ok(()) + } + /// Draw a glyph in design units. Empty glyphs such as spaces can produce an empty path. /// A malformed or excessively complex glyph returns an error instead of partial geometry. pub fn outline(&self, glyph: u32) -> Result { @@ -150,6 +192,24 @@ mod tests { use kurbo::PathEl; use std::sync::Arc; + impl GlyphPen for PathPen { + fn move_to(&mut self, x: f32, y: f32) { + OutlinePen::move_to(self, x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + OutlinePen::line_to(self, x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + OutlinePen::quad_to(self, x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + OutlinePen::curve_to(self, x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + OutlinePen::close(self); + } + } + #[test] fn rejects_invalid_face_and_collection_index() { let data = FontData { bytes: Arc::from(&b"not a font"[..]), index: 0 }; @@ -159,11 +219,11 @@ mod tests { #[test] fn pen_preserves_geometry_and_upward_y() { let mut pen = PathPen::new(); - pen.move_to(1.0, 2.0); - pen.line_to(3.0, 4.0); - pen.quad_to(5.0, 6.0, 7.0, 8.0); - pen.curve_to(9.0, 10.0, 11.0, 12.0, 13.0, 14.0); - pen.close(); + OutlinePen::move_to(&mut pen, 1.0, 2.0); + OutlinePen::line_to(&mut pen, 3.0, 4.0); + OutlinePen::quad_to(&mut pen, 5.0, 6.0, 7.0, 8.0); + OutlinePen::curve_to(&mut pen, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0); + OutlinePen::close(&mut pen); assert_eq!( pen.path.elements(), &[ @@ -179,9 +239,9 @@ mod tests { #[test] fn pen_caps_path_growth() { let mut pen = PathPen::new(); - pen.move_to(0.0, 0.0); + OutlinePen::move_to(&mut pen, 0.0, 0.0); for _ in 0..MAX_OUTLINE_ELEMENTS { - pen.line_to(1.0, 2.0); + OutlinePen::line_to(&mut pen, 1.0, 2.0); } assert_eq!(pen.path.elements().len(), MAX_OUTLINE_ELEMENTS); assert!(pen.truncated); @@ -246,6 +306,84 @@ mod tests { let (prefix, status) = shared.outline_recovering(gid).unwrap(); assert!(matches!(status, Err(OutlineError::Draw(_)))); assert_eq!(prefix, old.path); + let mut streamed = PathPen::new(); + assert!(matches!(shared.draw_to(gid, &mut streamed), Err(OutlineError::Draw(_)))); + assert_eq!(streamed.path, old.path); assert!(matches!(shared.outline(gid), Err(OutlineError::Draw(_)))); } + + #[test] + fn streaming_preserves_a_large_valid_cff_outline() { + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let source = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-cjk-sc/NotoSansCJKsc-Regular.otf")).unwrap(); + let source = FontRef::new(&source).unwrap(); + // Minimal CFF with a single generated Type 2 charstring. The glyph has over 100,000 + // valid line segments; no binary fixture is copied into this repository. + let mut program = vec![139, 139, 21]; // rmoveto 0,0 + for _ in 0..100_001 { + program.extend_from_slice(&[140, 6]); + } // hlineto 1 + program.push(14); // endchar + let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0]; + cff.extend_from_slice(&[0, 1, 4]); + cff.extend_from_slice(&1u32.to_be_bytes()); + cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes()); + cff.extend_from_slice(&program); + let mut builder = write_fonts::FontBuilder::new(); + for tag in [b"head", b"maxp", b"hhea", b"hmtx"] { + builder.add_raw(write_fonts::types::Tag::new(tag), source.table_data(Tag::new(tag)).unwrap().as_bytes().to_vec()); + } + assert!(skrifa::raw::ps::cff::CffFontRef::new(&cff, 0, None).is_ok(), "synthetic CFF parses"); + builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); + let bytes = builder.build(); + let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + struct Count(usize); + impl GlyphPen for Count { + fn move_to(&mut self, _: f32, _: f32) { + self.0 += 1; + } + fn line_to(&mut self, _: f32, _: f32) { + self.0 += 1; + } + fn quad_to(&mut self, _: f32, _: f32, _: f32, _: f32) { + self.0 += 1; + } + fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, _: f32, _: f32) { + self.0 += 1; + } + fn close(&mut self) { + self.0 += 1; + } + } + impl OutlinePen for Count { + fn move_to(&mut self, x: f32, y: f32) { + GlyphPen::move_to(self, x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + GlyphPen::line_to(self, x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + GlyphPen::quad_to(self, x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + GlyphPen::curve_to(self, x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + GlyphPen::close(self); + } + } + let mut old = Count(0); + FontRef::new(&bytes) + .unwrap() + .outline_glyphs() + .get(GlyphId::new(0)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), &Location::default()), &mut old) + .unwrap(); + let mut count = Count(0); + shared.draw_to(0, &mut count).unwrap(); + assert_eq!(count.0, old.0); + assert!(count.0 > MAX_OUTLINE_ELEMENTS); + assert!(matches!(shared.outline(0), Err(OutlineError::TooComplex))); + } } From f43730f887d01c8962b36be628f5e91ddb9792ef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:42:29 +0000 Subject: [PATCH 6/6] Exercise outline recovery without external fonts --- crates/font-catalog/src/outline.rs | 86 +++++++++++++++++------------- 1 file changed, 48 insertions(+), 38 deletions(-) diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs index c5a79b72e..f48b61e4f 100644 --- a/crates/font-catalog/src/outline.rs +++ b/crates/font-catalog/src/outline.rs @@ -236,6 +236,25 @@ mod tests { ); } + #[test] + fn streaming_adapter_forwards_each_command_and_rejects_an_invalid_prefix() { + let mut pen = PathPen::new(); + { + let mut sink = Sink(&mut pen); + OutlinePen::move_to(&mut sink, 1.0, 2.0); + OutlinePen::line_to(&mut sink, 3.0, 4.0); + OutlinePen::quad_to(&mut sink, 5.0, 6.0, 7.0, 8.0); + OutlinePen::curve_to(&mut sink, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0); + OutlinePen::close(&mut sink); + } + assert_eq!(pen.path.elements().len(), 5); + assert_eq!(pen.path.elements()[2], PathEl::QuadTo((5.0, 6.0).into(), (7.0, 8.0).into())); + let mut invalid = PathPen::new(); + OutlinePen::line_to(&mut invalid, 1.0, 2.0); + assert!(invalid.invalid); + assert!(invalid.path.elements().is_empty()); + } + #[test] fn pen_caps_path_growth() { let mut pen = PathPen::new(); @@ -275,27 +294,31 @@ mod tests { assert_ne!(light_path, bold_path); } + // Construct a minimal CFF font so CI can exercise the public API without installed fonts. + fn cff_font(program: &[u8]) -> Vec { + let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0]; + cff.extend_from_slice(&[0, 1, 4]); + cff.extend_from_slice(&1u32.to_be_bytes()); + cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes()); + cff.extend_from_slice(program); + let mut builder = write_fonts::FontBuilder::new(); + let mut head = vec![0; 54]; + head[18..20].copy_from_slice(&1000u16.to_be_bytes()); + let mut hhea = vec![0; 36]; + hhea[34..36].copy_from_slice(&1u16.to_be_bytes()); + builder.add_raw(write_fonts::types::Tag::new(b"head"), head); + builder.add_raw(write_fonts::types::Tag::new(b"hhea"), hhea); + builder.add_raw(write_fonts::types::Tag::new(b"hmtx"), vec![0, 100, 0, 0]); + builder.add_raw(write_fonts::types::Tag::new(b"maxp"), vec![0, 0, 0x50, 0, 0, 1]); + builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); + builder.build() + } + #[test] fn malformed_cff_recovers_the_same_prefix_as_direct_drawing() { - use skrifa::raw::ps::cff::CffFontRef; - let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; - let mut bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-cjk-sc/NotoSansCJKsc-Regular.otf")).unwrap(); - let (gid, start, len) = { - let f = FontRef::new(&bytes).unwrap(); - let cff = f.table_data(Tag::new(b"CFF ")).unwrap().as_bytes(); - let cff = CffFontRef::new(cff, 0, None).unwrap(); - let (gid, cs) = (0..cff.num_glyphs()) - .find_map(|gid| { - let cs = cff.charstrings().get(gid as usize)?; - (cs.len() >= 8).then_some((gid, cs)) - }) - .unwrap(); - (gid, cs.as_ptr() as usize - bytes.as_ptr() as usize, cs.len()) - }; - assert!(len >= 8); - // A move and line followed by a Type 2 callsubr without an operand. It emits a path - // prefix before the parser reports an error, without changing the font table offsets. - bytes[start..start + 8].copy_from_slice(&[139, 139, 21, 239, 139, 5, 10, 14]); + // Move and line, then callsubr without an operand: a prefix is emitted before failure. + let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]); + let gid = 0; let f = FontRef::new(&bytes).unwrap(); let mut old = PathPen::new(); let result = @@ -303,6 +326,8 @@ mod tests { assert!(result.is_err()); assert!(!old.path.elements().is_empty()); let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + assert_eq!(shared.metrics().units_per_em, 1000); + assert_eq!(shared.glyph_for('A'), None); let (prefix, status) = shared.outline_recovering(gid).unwrap(); assert!(matches!(status, Err(OutlineError::Draw(_)))); assert_eq!(prefix, old.path); @@ -314,28 +339,13 @@ mod tests { #[test] fn streaming_preserves_a_large_valid_cff_outline() { - let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; - let source = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-cjk-sc/NotoSansCJKsc-Regular.otf")).unwrap(); - let source = FontRef::new(&source).unwrap(); - // Minimal CFF with a single generated Type 2 charstring. The glyph has over 100,000 - // valid line segments; no binary fixture is copied into this repository. - let mut program = vec![139, 139, 21]; // rmoveto 0,0 + // Minimal CFF with more than 100,000 line segments. + let mut program = vec![139, 139, 21]; for _ in 0..100_001 { program.extend_from_slice(&[140, 6]); - } // hlineto 1 - program.push(14); // endchar - let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0]; - cff.extend_from_slice(&[0, 1, 4]); - cff.extend_from_slice(&1u32.to_be_bytes()); - cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes()); - cff.extend_from_slice(&program); - let mut builder = write_fonts::FontBuilder::new(); - for tag in [b"head", b"maxp", b"hhea", b"hmtx"] { - builder.add_raw(write_fonts::types::Tag::new(tag), source.table_data(Tag::new(tag)).unwrap().as_bytes().to_vec()); } - assert!(skrifa::raw::ps::cff::CffFontRef::new(&cff, 0, None).is_ok(), "synthetic CFF parses"); - builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); - let bytes = builder.build(); + program.push(14); + let bytes = cff_font(&program); let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); struct Count(usize); impl GlyphPen for Count {