diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index bba563195d..aa5198d209 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -247,6 +247,52 @@ impl Line { } fn push(&mut self, id: NodeId, m: &GlyphMatch) { + self.push_joined(id, m, None); + } + + /// For each of `ms`'s glyphs, the distance along the line to the next when untracked type sets + /// them with no spaces (their advances and pair kerning), and when it sets one space between + /// them (the glyph's own advance plus a space where type draws no such layout), taking the + /// characters laid out from `budget`; `None` when the budget is short or type does not draw + /// every glyph without spaces. + fn pair_steps(&self, ms: &[GlyphMatch], system_layout: bool, budget: &mut usize) -> Option> { + *budget = budget.checked_sub(ms.len().saturating_mul(3))?; + let dir = self.dir(); + let mut bare = self.clone(); + bare.tracking = 0.0; + let mut origins = |text: String| -> Vec { + bare.text = text; + let t = bare.probe(system_layout); + let lay = vectorcraft_text::layout(FontDb::global(), &t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() + }; + let joined = origins(ms.iter().map(|m| m.ch).collect()); + if joined.len() != ms.len() { + return None; + } + let spaced = origins(ms.iter().map(|m| m.ch.to_string()).collect::>().join(" ")); + let space = space_advance(&self.face) * self.scale; + let spaced_ok = spaced.len() == ms.len(); + Some( + ms.iter() + .enumerate() + .zip(joined.windows(2)) + .map(|((i, m), p)| { + let own = m.face.advance(m.gid) * m.scale + space; + let apart = match (spaced_ok, spaced.get(i), spaced.get(i + 1)) { + (true, Some(a), Some(b)) => (*b - *a).dot(dir), + _ => own, + }; + ((p[1] - p[0]).dot(dir), apart) + }) + .collect(), + ) + } + + /// [`Line::push`], with `steps` the distances [`Line::pair_steps`] gives for the pair of the + /// line's last glyph and `m`. A gap reads as spaces only when they fit it better than the + /// joined pair does, as when the tracking is measured. + fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) { // A gap, past the tracking, wider than half a space before the glyph is spaces the // outlines left no shape for. Each space takes the tracking too. let dir = self.dir(); @@ -256,7 +302,16 @@ impl Line { let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; if spaces.is_finite() && spaces > 0.5 { let n = (spaces.round() as usize).clamp(1, 64); - self.text.extend(std::iter::repeat_n(' ', n)); + let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); + let tr = self.tracking_pt(); + let joined_fits = steps.is_some_and(|(joined, apart)| { + let face_space = space_advance(&self.face) * self.scale; + let spaced_err = (d - apart + face_space - tr - n as f64 * (face_space + tr)).abs(); + (d - joined - tr).abs() <= spaced_err + self.size() * 1e-5 + }); + if !joined_fits { + self.text.extend(std::iter::repeat_n(' ', n)); + } } self.text.push(m.ch); self.pieces.push(id); @@ -728,8 +783,13 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) track_budget = track_budget.saturating_sub(n - k); return whole.tracked(system_layout, &mut track_budget); } - for (id, m) in l.pieces.iter().zip(&l.matches).skip(k + span) { - r.push(*id, m); + // The glyphs after those measured follow at that tracking; a gap reads as + // spaces only when they fit it better than the joined pair does, as in + // the glyphs measured, while the budget for laying the pairs out lasts. + let steps = + l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut track_budget)).unwrap_or_default(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); } r }) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b78f432634..ac55ca6fb8 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -886,13 +886,19 @@ fn slight_tracking_without_spaces_is_kept() { /// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's /// first match), before their tracking is measured and their layout checked. fn lines_in(s: &Session, g: u64) -> Vec { + lines_in_family(s, g, None) +} + +/// [`lines_in`] with the face of the first glyph's match in `family` when given. +fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec { let d = &s.doc().unwrap().doc; let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces); let db = vectorcraft_text::FontDb::global(); let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted); - let face = index.matches(&pieces[0].path)[0].face.id(); + let first = index.matches(&pieces[0].path); + let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id(); let mut lines: Vec = vec![]; for pc in &pieces { let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); @@ -1100,6 +1106,42 @@ fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after } } +#[test] +fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_after_a_split() { + // The font adds 120 units to each i before an i. Tracking that leaves a space 120 wide makes the + // gap a kerned pair leaves the same as the gap a word space leaves; the joined reading wins the + // tie, as it does for the glyphs the tracking is measured from. + use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap()); + let mut s = session(); + let text = "i".repeat(60); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap(); + let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0; + let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round(); + assert!(space + tracking >= space / 2.0, "the space must stay at least half its width: {space} {tracking}"); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)]); +} + #[test] fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..fd2fe20c9d 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1816,6 +1816,43 @@ pub fn pair_kerning_font() -> Option> { Some(builder.build()) } +/// The family of [`positive_kerning_font`]. +pub const POSITIVE_KERNING_FAMILY: &str = "Poskern Sans"; + +/// The units [`positive_kerning_font`] adds to the advance of an i that another i follows. +pub const POSITIVE_KERNING_UNITS: i16 = 120; + +/// The bundled Source Sans 3 Regular as family [`POSITIVE_KERNING_FAMILY`], its `GPOS` replaced by +/// one `kern` pair, i followed by i, that adds [`POSITIVE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn positive_kerning_font() -> Option> { + use write_fonts::tables::gpos::{Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let i = GlyphId16::new(u16::try_from(font.charmap().map('i')?.to_u32()).ok()?); + let record = PairValueRecord::new(i, ValueRecord::new().with_x_advance(POSITIVE_KERNING_UNITS), ValueRecord::new()); + let coverage = CoverageFormat1::new(vec![i]); + let pos = PairPos::format_1(coverage.into(), vec![PairSet::new(vec![record])]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Pair(Lookup::new(Default::default(), vec![pos]))]); + let family = POSITIVE_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Poskern Sans Regular"), (6, "PoskernSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`twin_font`]: two versions of one family and style. pub const TWIN_FAMILY: &str = "Twintest Sans";