mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 06:38:44 +00:00
Merge remote-tracking branch 'upstream/main' into feat/4934-retype
# Conflicts: # crates/text/src/fontdb/lookup.rs
This commit is contained in:
Generated
+13
@@ -1044,6 +1044,18 @@ name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
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",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -7109,6 +7121,7 @@ dependencies = [
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-font-catalog",
|
||||
"craft-proof",
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
|
||||
@@ -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 = "d0a9c79933a54883cd5bc3dfe839f1dd699f2c69", default-features = false }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -10,10 +10,7 @@ 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, regular_rank};
|
||||
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;
|
||||
@@ -673,10 +670,9 @@ impl FontDb {
|
||||
/// would otherwise push out the outlines the canvas keeps there.
|
||||
pub fn outline_uncached(&self, face: &FontFace, gid: u32) -> BezPath {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
pen.0
|
||||
}
|
||||
@@ -734,3 +730,89 @@ 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}");
|
||||
}
|
||||
}
|
||||
|
||||
// Generated CFF keeps the differential tests independent of installed fonts.
|
||||
fn cff_font(program: &[u8]) -> Vec<u8> {
|
||||
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() {
|
||||
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
|
||||
.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 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 mut program = vec![139, 139, 21];
|
||||
for _ in 0..100_001 {
|
||||
program.extend_from_slice(&[140, 6]);
|
||||
}
|
||||
program.push(14);
|
||||
let bytes = cff_font(&program);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+35
-57
@@ -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<FontFace>> = 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<Item = char> + '_ {
|
||||
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<FontFace>, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc<FontFace> {
|
||||
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<usize>, 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::<Vec<_>>()
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user