From 4bc874ca79c67c90f0924e22297e84b9af392f1c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:20:29 +0000 Subject: [PATCH 1/6] Share cached glyph outline drawing --- Cargo.lock | 12 ++++++++ crates/text/Cargo.toml | 2 ++ crates/text/src/fontdb/lookup.rs | 48 ++++++++++++++++++++++++-------- 3 files changed, 50 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 887b10ab11..07f06d5ac8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1005,6 +1005,17 @@ name = "craft-eps" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=14bccd4e09094820babc434d2681297be8873bd9#14bccd4e09094820babc434d2681297be8873bd9" +dependencies = [ + "kurbo 0.13.1", + "skrifa 0.47.0", + "thiserror 2.0.21", + "windows-registry", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -6871,6 +6882,7 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-font-catalog", "harfrust 0.13.3", "icu_segmenter", "kurbo 0.13.1", diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 1f8ddc3755..9b95f04301 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -9,6 +9,8 @@ description = "VectorCraft text: font database, shaping, layout, glyph outlines" workspace = true [dependencies] +# Pending shared extraction; pin the immutable official PR head until it merges. +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "14bccd4e09094820babc434d2681297be8873bd9", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 23e00afa0c..a846f2af45 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -3,17 +3,14 @@ use super::PathBuf; use super::build::{instanced, style_distance, style_italic, style_weight}; use super::cache::Catalog; use super::face::{FALLBACK_FAMILY, FontFace, MAX_LIVE_INSTANCES, Variation, VariationAxis}; -use super::glyph_pen::{FlipPen, svg_drawn}; +use super::glyph_pen::svg_drawn; #[cfg(not(target_arch = "wasm32"))] use super::names::SYSTEM_FALLBACKS; use super::names::{norm, norm_chars, script_families}; #[cfg(not(target_arch = "wasm32"))] use super::scan::{enumerate_faces, font_files}; use super::traits::{Alias, FontMatch, FontTraits}; -use super::{ - Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, - Ordering, Size, -}; +use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering}; /// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. const MAX_POSTSCRIPT_FACES: usize = 16; @@ -566,13 +563,13 @@ impl FontDb { if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return p.clone(); } - let mut pen = FlipPen(BezPath::new()); - if let Some(f) = face.skrifa() - && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) - { - let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); - } - let p = Arc::new(pen.0); + let path = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) + .and_then(|font| font.outline_recovering(gid)) + // The old pen kept a partial path when drawing failed. Keep that behavior while + // the shared implementation bounds the number of elements from untrusted fonts. + .map(|(path, _status)| kurbo::Affine::scale_non_uniform(1.0, -1.0) * path) + .unwrap_or_default(); + let p = Arc::new(path); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); @@ -634,3 +631,30 @@ impl FontDb { content } } + +#[cfg(test)] +mod shared_outline_tests { + use super::super::glyph_pen::FlipPen; + use super::*; + use skrifa::instance::Size; + use skrifa::outline::DrawSettings; + use skrifa::{GlyphId, MetadataProvider}; + + #[test] + fn shared_outlines_match_original_pen_for_variable_instances() { + let db = FontDb::with_font_dirs(vec![]); + let Some(bytes) = crate::test_fonts::variable_font() else { return }; + assert!(db.add_font(bytes) > 0); + let face = db.face(crate::test_fonts::VARIABLE_FAMILY, "Bold").expect("named instance is registered"); + let f = face.skrifa().expect("font parses"); + for ch in ['A', 'V', ' ', 'a'] { + let Some(glyph) = f.charmap().map(ch) else { continue }; + let mut old = FlipPen(BezPath::new()); + if let Some(outline) = f.outline_glyphs().get(GlyphId::new(glyph.to_u32())) { + // Match the prior production behavior, including a partial path on error. + let _ = outline.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut old); + } + assert_eq!(*db.outline(&face, glyph.to_u32()), old.0, "glyph {ch}"); + } + } +} From 09f02d70b51a37a06ef69d5bfac9e7b151398cb3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:26:03 +0000 Subject: [PATCH 2/6] Remove superseded outline import --- crates/text/src/fontdb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..df12ce99e7 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, RwLock}; use kurbo::BezPath; use skrifa::instance::{Location, LocationRef, Size}; -use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::outline::OutlinePen; use skrifa::raw::FileRef; use skrifa::string::StringId; use skrifa::{GlyphId, MetadataProvider, Tag}; From 6fa5a6fb56333659dac6fd8a664d7ecb1a439d6d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:28:57 +0000 Subject: [PATCH 3/6] Compare malformed glyph recovery against original pen --- Cargo.lock | 2 +- crates/text/Cargo.toml | 2 +- crates/text/src/fontdb/lookup.rs | 33 ++++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07f06d5ac8..c9ed1d024c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1008,7 +1008,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a9 [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=14bccd4e09094820babc434d2681297be8873bd9#14bccd4e09094820babc434d2681297be8873bd9" +source = "git+https://github.com/storytold/craft-libs?rev=58e2a887e6fe346deff2708513b0c1cd7c2af8c3#58e2a887e6fe346deff2708513b0c1cd7c2af8c3" dependencies = [ "kurbo 0.13.1", "skrifa 0.47.0", diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 9b95f04301..0f311b964b 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # Pending shared extraction; pin the immutable official PR head until it merges. -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "14bccd4e09094820babc434d2681297be8873bd9", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "58e2a887e6fe346deff2708513b0c1cd7c2af8c3", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index a846f2af45..8ff792751b 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -657,4 +657,37 @@ mod shared_outline_tests { assert_eq!(*db.outline(&face, glyph.to_u32()), old.0, "glyph {ch}"); } } + + #[test] + fn malformed_cff_prefix_matches_original_pen() { + 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) = { + let f = skrifa::FontRef::new(&bytes).unwrap(); + let table = f.table_data(skrifa::Tag::new(b"CFF ")).unwrap().as_bytes(); + let cff = CffFontRef::new(table, 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) + }; + bytes[start..start + 8].copy_from_slice(&[139, 139, 21, 239, 139, 5, 10, 14]); + let f = skrifa::FontRef::new(&bytes).unwrap(); + let mut old = FlipPen(BezPath::new()); + let result = f + .outline_glyphs() + .get(GlyphId::new(gid)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old); + assert!(result.is_err()); + assert!(!old.0.elements().is_empty()); + let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + let (path, status) = shared.outline_recovering(gid).unwrap(); + assert!(status.is_err()); + assert_eq!(kurbo::Affine::scale_non_uniform(1.0, -1.0) * path, old.0); + } } From b4fdbdd1acbbd8d5e58819990ef12076063618f9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:39:40 +0000 Subject: [PATCH 4/6] Stream shared outlines into the existing bounded pen --- Cargo.lock | 2 +- crates/text/Cargo.toml | 2 +- crates/text/src/fontdb/glyph_pen.rs | 19 ++++++++++ crates/text/src/fontdb/lookup.rs | 56 +++++++++++++++++++++++------ 4 files changed, 66 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c9ed1d024c..03843d9578 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1008,7 +1008,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a9 [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=58e2a887e6fe346deff2708513b0c1cd7c2af8c3#58e2a887e6fe346deff2708513b0c1cd7c2af8c3" +source = "git+https://github.com/storytold/craft-libs?rev=4d51586a45321b101f608276ce7ccbcec3f1fab3#4d51586a45321b101f608276ce7ccbcec3f1fab3" dependencies = [ "kurbo 0.13.1", "skrifa 0.47.0", diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 0f311b964b..6a6ed42b51 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # Pending shared extraction; pin the immutable official PR head until it merges. -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "58e2a887e6fe346deff2708513b0c1cd7c2af8c3", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4d51586a45321b101f608276ce7ccbcec3f1fab3", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index fdbb27e3a7..5387ff4b55 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -53,6 +53,25 @@ impl OutlinePen for FlipPen { } } +// Share font decoding while preserving the app's existing y-down geometry and resource budget. +impl craft_font_catalog::GlyphPen for FlipPen { + 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); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 8ff792751b..27385253a6 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -3,7 +3,7 @@ use super::PathBuf; use super::build::{instanced, style_distance, style_italic, style_weight}; use super::cache::Catalog; use super::face::{FALLBACK_FAMILY, FontFace, MAX_LIVE_INSTANCES, Variation, VariationAxis}; -use super::glyph_pen::svg_drawn; +use super::glyph_pen::{FlipPen, svg_drawn}; #[cfg(not(target_arch = "wasm32"))] use super::names::SYSTEM_FALLBACKS; use super::names::{norm, norm_chars, script_families}; @@ -563,13 +563,12 @@ impl FontDb { if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return p.clone(); } - let path = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) - .and_then(|font| font.outline_recovering(gid)) - // The old pen kept a partial path when drawing failed. Keep that behavior while - // the shared implementation bounds the number of elements from untrusted fonts. - .map(|(path, _status)| kurbo::Affine::scale_non_uniform(1.0, -1.0) * path) - .unwrap_or_default(); - let p = Arc::new(path); + let mut pen = FlipPen(BezPath::new()); + if let Ok(font) = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) { + // As before, keep the prefix emitted before a malformed glyph reports an error. + let _ = font.draw_to(gid, &mut pen); + } + let p = Arc::new(pen.0); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); @@ -686,8 +685,43 @@ mod shared_outline_tests { assert!(result.is_err()); assert!(!old.0.elements().is_empty()); let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); - let (path, status) = shared.outline_recovering(gid).unwrap(); - assert!(status.is_err()); - assert_eq!(kurbo::Affine::scale_non_uniform(1.0, -1.0) * path, old.0); + let mut streamed = FlipPen(BezPath::new()); + assert!(shared.draw_to(gid, &mut streamed).is_err()); + assert_eq!(streamed.0, old.0); + } + + #[test] + fn large_valid_outline_matches_original_pen() { + 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 = skrifa::FontRef::new(&source).unwrap(); + let mut program = vec![139, 139, 21]; + for _ in 0..100_001 { + program.extend_from_slice(&[140, 6]); + } + program.push(14); + 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(skrifa::Tag::new(tag)).unwrap().as_bytes().to_vec()); + } + builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); + let bytes = builder.build(); + let f = skrifa::FontRef::new(&bytes).unwrap(); + let mut old = FlipPen(BezPath::new()); + f.outline_glyphs() + .get(GlyphId::new(0)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old) + .unwrap(); + assert!(old.0.elements().len() > 100_000); + let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + let mut streamed = FlipPen(BezPath::new()); + shared.draw_to(0, &mut streamed).unwrap(); + assert_eq!(streamed.0, old.0); } } From 71d7253444dd6cef7280bf69359d6e9d87f1c1ed Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:49:21 +0000 Subject: [PATCH 5/6] Run outline differential tests without font installation --- crates/text/src/fontdb/lookup.rs | 51 +++++++++++++------------------- 1 file changed, 21 insertions(+), 30 deletions(-) diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 27385253a6..24a6280755 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -657,24 +657,28 @@ mod shared_outline_tests { } } + // Generated CFF keeps the differential tests independent of 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()); + for (tag, data) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1]), (b"CFF ", cff)] { + builder.add_raw(write_fonts::types::Tag::new(tag), data); + } + builder.build() + } + #[test] fn malformed_cff_prefix_matches_original_pen() { - 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) = { - let f = skrifa::FontRef::new(&bytes).unwrap(); - let table = f.table_data(skrifa::Tag::new(b"CFF ")).unwrap().as_bytes(); - let cff = CffFontRef::new(table, 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) - }; - bytes[start..start + 8].copy_from_slice(&[139, 139, 21, 239, 139, 5, 10, 14]); + let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]); + let gid = 0; let f = skrifa::FontRef::new(&bytes).unwrap(); let mut old = FlipPen(BezPath::new()); let result = f @@ -692,25 +696,12 @@ mod shared_outline_tests { #[test] fn large_valid_outline_matches_original_pen() { - 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 = skrifa::FontRef::new(&source).unwrap(); let mut program = vec![139, 139, 21]; for _ in 0..100_001 { program.extend_from_slice(&[140, 6]); } program.push(14); - 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(skrifa::Tag::new(tag)).unwrap().as_bytes().to_vec()); - } - builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); - let bytes = builder.build(); + let bytes = cff_font(&program); let f = skrifa::FontRef::new(&bytes).unwrap(); let mut old = FlipPen(BezPath::new()); f.outline_glyphs() From 2dd120c0fedc5d5261acb68dfc01aaca2613d6dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:14:14 -0500 Subject: [PATCH 6/6] Use shared contextual run shaping (#7878) --- Cargo.lock | 3 +- crates/text/Cargo.toml | 2 +- crates/text/src/shape.rs | 92 +++++++++++++++------------------------- 3 files changed, 38 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 29921a6d06..745e8c4171 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1039,8 +1039,9 @@ source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc6 [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4d51586a45321b101f608276ce7ccbcec3f1fab3#4d51586a45321b101f608276ce7ccbcec3f1fab3" +source = "git+https://github.com/storytold/craft-libs?rev=d0a9c79933a54883cd5bc3dfe839f1dd699f2c69#d0a9c79933a54883cd5bc3dfe839f1dd699f2c69" dependencies = [ + "harfrust 0.13.3", "kurbo 0.13.1", "skrifa 0.47.0", "thiserror 2.0.21", diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 6a6ed42b51..7feac2bc60 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # Pending shared extraction; pin the immutable official PR head until it merges. -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4d51586a45321b101f608276ce7ccbcec3f1fab3", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d0a9c79933a54883cd5bc3dfe839f1dd699f2c69", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index c9ae809da5..795e2c375b 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -8,7 +8,7 @@ use unicode_bidi::Level; use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; -use harfrust::{BufferClusterLevel, Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use harfrust::{Direction, Feature, Tag}; use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; @@ -673,7 +673,7 @@ pub(crate) fn shape_runs( // Split into segments by font coverage (and case, for Small Caps). let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) }; let mut cache: std::collections::HashMap<&str, Arc> = std::collections::HashMap::new(); - let mut script = Script::Common; + let mut boundary = craft_font_catalog::SegmentBoundary::new(primary.id(), level_at(a)); // A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face. for (i, cluster) in text[a..b].grapheme_indices(true) { let i = a + i; @@ -693,20 +693,16 @@ pub(crate) fn shape_runs( }; let small = small_caps && c.is_lowercase(); let next_script = shaping_script(c); - let strong_script = !matches!(next_script, Script::Common | Script::Inherited); - let script_change = strong_script && script != Script::Common && script != next_script; + let strong_script = (!matches!(next_script, Script::Common | Script::Inherited)).then_some(next_script); // Combining marks, zero width joiners and non-joiners, and variation selectors stay // with the character before them. - if (face.id() != seg.face.id() || small != seg.small || level != seg.level || script_change) && !is_mark(c) { + if boundary.advance(face.id(), level, small, strong_script, is_mark(c)) { if i > seg.range.start { seg.range.end = i; shape_segment(text, &range, &seg, feats, out); } seg = Segment { range: i..i, face, small, level, ..seg }; } - if strong_script { - script = next_script; - } } if b > seg.range.start { seg.range.end = b; @@ -1301,10 +1297,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { /// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or /// variation selectors. fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator + '_ { - cluster - .chars() - .map(move |c| digits.map(c)) - .filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))) + craft_font_catalog::drawable_characters(cluster, move |c| digits.map(c)) } /// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)? @@ -1316,11 +1309,14 @@ fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool { /// first fallback face with all of them, so that a letter's marks are shaped with it and attach to /// it (#4491); when there is none, the face its first character takes on its own. fn fallback_face(db: &FontDb, primary: &Arc, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc { - let fallback = |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic); - drawn_chars(cluster, digits) - .find_map(|c| fallback(c).filter(|f| drawn_chars(cluster, digits).all(|c| f.covers(c)))) - .or_else(|| drawn_chars(cluster, digits).next().filter(|&c| !in_face(pmap, c)).and_then(fallback)) - .unwrap_or_else(|| primary.clone()) + craft_font_catalog::cluster_face( + cluster, + primary, + |c| digits.map(c), + |c| in_face(pmap, c), + |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic), + |face, c| face.covers(c), + ) } /// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and @@ -1606,46 +1602,28 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let along_features = with_more(&|s| feats.resolve(s)); // gid, cluster, x and y advance, x and y offset. let shape = |feats: &[Feature], direction: Direction| { - let mut buf = UnicodeBuffer::new(); - for (i, c) in text_seg.char_indices() { - let cl = (range.start + i) as u32; - let c = st.digits.map(c); - if upper { - for u in c.to_uppercase() { - buf.add(u, cl); - } - } else { - buf.add(c, cl); - } - } - buf.set_direction(direction); - buf.guess_segment_properties(); - if char_level.get() { - buf.set_cluster_level(BufferClusterLevel::Characters); - } - // The characters' language picks the font's forms for it (`locl`: Turkish keeps fi - // apart and the dot on its i). - if let Some(l) = &language { - buf.set_language(l.clone()); - } - // Harfrust keeps this Unicode context for joining/positional shaping, but does not emit - // glyphs for it. This retains context at real style/font segmentation boundaries without - // shaping across those boundaries or claiming cross-style ligatures/mark attachment. - if let Some(pre) = text.get(context.start..range.start) { - buf.set_pre_context(pre); - } - if let Some(post) = text.get(range.end..context.end) { - buf.set_post_context(post); - } - // A buffer whose characters name no script reads as `UNKNOWN`: its plan has none. - let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN); - let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), feats); - let gb = shaper.shape(buf, ShapeOptions::new().features(feats).plan(Some(&plan))); - gb.glyph_infos() - .iter() - .zip(gb.glyph_positions()) - .map(|(info, pos)| (info.glyph_id, info.cluster, pos.x_advance, pos.y_advance, pos.x_offset, pos.y_offset)) - .collect::>() + let input = craft_font_catalog::RunInput { + text: text_seg, + source_start: range.start, + pre_context: text.get(context.start..range.start).unwrap_or_default(), + post_context: text.get(range.end..context.end).unwrap_or_default(), + direction, + language: language.as_ref(), + features: feats, + character_clusters: char_level.get(), + uppercase: upper, + }; + craft_font_catalog::shape_run( + &shaper, + &input, + |c| st.digits.map(c), + |shaper, direction, script, language, features| face.shape_plan(shaper, direction, script, language, features), + ) + // HarfRust clusters are u32; a run beyond that source offset cannot be represented. + .unwrap_or_default() + .into_iter() + .map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset)) + .collect::>() }; let along = if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight }; *raw = shape(&along_features, along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect();