diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b0d37a1d61..d598e33065 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -272,17 +272,84 @@ impl Line { } fn push(&mut self, id: NodeId, m: &GlyphMatch) { - // 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. + 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 gap = (m.origin - self.end).dot(dir) - self.tracking_pt(); - // Tracking tighter than a space's width gives each space a negative advance. - let space = space_advance(&self.face) * self.scale + self.tracking_pt(); - 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 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`. With `steps`, a gap reads as spaces only when they fit it better + /// than the joined pair does, as when the tracking is measured, however narrow the gap is. + fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) { + // Without `steps`, 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(); + let tr = self.tracking_pt(); + let gap = (m.origin - self.end).dot(dir) - tr; + // Tracking tighter than a space's width gives each space a negative advance. + let face_space = space_advance(&self.face) * self.scale; + let space = face_space + tr; + let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; + let n = match steps { + Some((joined, apart)) => { + let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); + // How far `n` spaces set the glyph from where the outlines put it: the pair with one + // space between them is `apart`, and each further space adds a space and the tracking. + let spaced_err = |n: usize| (d - apart + face_space - tr - n as f64 * space).abs(); + // Kerning against a space widens or narrows the gap, so the count the gap gives, the + // counts next to it and the count the measured distance gives are compared; the + // rounded count wins a tie. + let measured = (d - apart + face_space - tr) / space; + let best = [spaces.round(), spaces.floor(), spaces.ceil(), measured.round()] + .into_iter() + .filter(|c| c.is_finite()) + .map(|c| (c.max(1.0) as usize).min(64)) + .min_by(|a, b| spaced_err(*a).total_cmp(&spaced_err(*b))) + .unwrap_or(1); + // The joined pair wins a tie. + if (d - joined - tr).abs() <= spaced_err(best) + self.size() * 1e-5 { 0 } else { best } + } + None if spaces.is_finite() && spaces > 0.5 => (spaces.round() as usize).clamp(1, 64), + None => 0, + }; + self.text.extend(std::iter::repeat_n(' ', n)); self.text.push(m.ch); self.pieces.push(id); self.matches.push(m.clone()); @@ -426,6 +493,15 @@ impl Line { /// its characters, spaces included, from `budget` before it runs; without enough left, the /// line stays as it is, or becomes the best tracked reading laid out before the budget ran out. fn tracked(self, system_layout: bool, budget: &mut usize) -> Line { + let reach = self.text.chars().count(); + self.tracked_reaching(system_layout, budget, reach) + } + + /// [`Line::tracked`] for a line whose tracking is applied to `reach` characters, its glyphs and + /// the spaces between them: a measured tracking within 0.05 of a whole number is read as that + /// number only when the difference moves the character `reach` places on by no more than the + /// tolerance [`first_mismatch`] allows. + fn tracked_reaching(self, system_layout: bool, budget: &mut usize, reach: usize) -> Line { let size = self.size(); let n = self.pieces.len(); // A near-matched glyph sits within the tolerance of where the font draws it, so the gaps @@ -534,7 +610,12 @@ impl Line { let mut tries = vec![]; for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() { let Some(measured) = measure(seed) else { continue }; - for t in [round_tracking(measured), measured] { + let rounded = round_tracking(measured); + let drift = (rounded - measured).abs() / 1000.0 * size * reach.saturating_sub(1) as f64; + for t in [rounded, measured] { + if t != measured && drift > (size * 0.01).max(0.01) { + continue; + } if !tries.contains(&t) { tries.push(t); } @@ -582,7 +663,12 @@ impl Line { match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) { // Under a unit of tracking, or a word space the tracked reading drops, where // untracked type draws the line: no tracking. - (None, None) if t.abs() < 1.0 || drops_a_word_space => return self, + (None, None) + if (t.abs() < 1.0 && t.abs() / 1000.0 * size * reach.saturating_sub(1) as f64 <= (size * 0.01).max(0.01)) + || drops_a_word_space => + { + return self; + } (None, _) => return tracked, (Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)), _ => {} @@ -688,6 +774,9 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat (finite(shape), finite(moved)) } +/// The most glyphs [`verified`] measures the tracking of after a split. +const MEASURE_SPAN: usize = 32; + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. @@ -698,8 +787,8 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to // rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers // one measure of each whole line, as `retype` gives the first, and the glyph checks' budget. - // The glyphs measured again after splits are limited apart from it, at six times each rest's - // glyphs from half as much again as the glyph checks' budget. + // The glyphs measured again after splits are limited apart from it, at six times the glyphs + // each measure reads from half as much again as the glyph checks' budget. let mut remeasured = budget.saturating_add(budget / 2); let mut track_budget = lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add); @@ -744,29 +833,10 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // The glyphs before the mismatch, then the rest, each checked as a line of its // own: the type before the mismatch may draw otherwise without what follows it (a // font can place a glyph by the glyph after it), and the first glyph on its own - // may still be drawn as it was (a contextual form changed it in the line). The - // rest takes the tracking its own glyphs are spaced by, while the budget for - // measuring it lasts and when type draws its first glyph as it was, followed by the - // next two (else that glyph splits off first, and the tracking is measured from the - // next one); past it, an untracked line's rest keeps its text as it is. + // may still be drawn as it was (a contextual form changed it in the line). Some(k) => { let k = k.max(1); - // A measure takes at least six times the rest's glyphs from each budget. - let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6); - let first_drawn = measurable && { - budget = budget.saturating_sub(3); - l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) - }; - let rest = if first_drawn { - // Rebuilding the rest for the measure takes its glyphs from the budget. - remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); - track_budget = track_budget.saturating_sub(n - k); - l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) - } else if l.tracking == 0.0 { - l.part(k, n) - } else { - l.respaced(k, n, 0.0) - }; + let rest = rest_after_split(&l, k, system_layout, &mut budget, &mut remeasured, &mut track_budget); match rest { Some(r) => todo.push_front(r), None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()), @@ -780,6 +850,75 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// The rest of `l` from glyph `k` (at least 1) after [`verified`] splits it there. The rest takes +/// the tracking its own glyphs are spaced by, while the budgets for measuring it last and when type +/// draws its first glyph as it was, followed by the next two (else that glyph splits off first, and +/// the tracking is measured from the next one); past it, an untracked line's rest keeps its text as +/// it is. The tracking is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the +/// glyphs after them follow at that tracking, so each split costs the same however long the rest +/// is, and splits at irregular gaps early in a line leave the budget for a long evenly tracked run +/// after them. A gap after the glyphs measured reads as spaces only when they fit it better than +/// the joined pair does, as in the glyphs measured: laying those pairs out is set aside from +/// `track_budget` before the tracking is measured, and without enough for both the rest is not +/// measured. +fn rest_after_split(l: &Line, k: usize, system_layout: bool, budget: &mut usize, remeasured: &mut usize, track_budget: &mut usize) -> Option { + let n = l.pieces.len(); + let span = (n - k).min(MEASURE_SPAN); + let more = n - k - span; + // What [`Line::pair_steps`] takes for the last glyph measured and the glyphs after it. + let pairs = if more > 0 { more.saturating_add(1).saturating_mul(3) } else { 0 }; + // A measure takes at least six times the glyphs it reads from each budget. + let measurable = n - k >= 3 && *remeasured >= span.saturating_mul(6) && *track_budget >= span.saturating_mul(6).saturating_add(pairs); + let first_drawn = measurable && { + *budget = budget.saturating_sub(3); + l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) + }; + if !first_drawn { + return if l.tracking == 0.0 { l.part(k, n) } else { l.respaced(k, n, 0.0) }; + } + // Rebuilding the glyphs measured takes them from the budget. + *remeasured = remeasured.saturating_sub(span.saturating_mul(6)); + *track_budget = track_budget.saturating_sub(span).saturating_sub(pairs); + let mut pair_budget = pairs; + // The characters the rest's tracking applies to: its glyphs and the spaces between them (a + // space before glyph `at` follows glyph `at - 1`). + let reach = l + .text + .chars() + .scan(0usize, |glyph, c| { + let at = *glyph; + *glyph += usize::from(c != ' '); + Some(if c == ' ' { at > k } else { at >= k }) + }) + .filter(|kept| *kept) + .count() + .max(n - k); + let mut r = l.respaced(k, k + span, 0.0)?.tracked_reaching(system_layout, track_budget, reach); + // Tracking that leaves a space under half its advance: the gaps alone do not show the spaces + // past the glyphs measured (only the kerning a space breaks may), so the whole rest is measured + // while the budget lasts. + let space = space_advance(&r.face) * r.scale; + if more > 0 + && space + r.tracking_pt() < space / 2.0 + && *remeasured >= (n - k).saturating_mul(6) + && track_budget.saturating_add(pair_budget) >= (n - k).saturating_mul(6) + && let Some(whole) = l.respaced(k, n, 0.0) + { + *remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); + *track_budget = track_budget.saturating_add(pair_budget).saturating_sub(n - k); + return Some(whole.tracked(system_layout, track_budget)); + } + // The glyphs after those measured follow at that tracking. + let steps = match more { + 0 => vec![], + _ => l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut pair_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()); + } + Some(r) +} + /// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes /// of the area type on the layers Retype changes /// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 2727dd4432..9fbead0346 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1707,13 +1707,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(); @@ -1823,6 +1829,286 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); } +#[test] +fn irregular_gaps_before_a_long_tracked_run_do_not_split_the_run() { + // The first eight gaps each take another tracking, and the 92 glyphs after them are tracked + // 300: measuring the rest after each irregular gap must not use up the budget the run needs, + // so the run is one object with its tracking. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(100), "{r}"); + assert_eq!(r["unmatched"], json!([])); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 92, "{texts:?}"); + assert!(run.runs.iter().all(|r| r.style.tracking == 300.0), "{texts:?}"); +} + +#[test] +fn a_long_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 reads as 300 over the 32 glyphs measured, but 400 glyphs apart the two + // differ by more than the tolerance: the run after the irregular gaps keeps 300.04 and stays + // one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(400), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 392, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + +#[test] +fn a_long_spaced_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 read as 300 moves the last of the 192 glyphs after the irregular gaps by less + // than the tolerance, counting the glyphs alone, but the word spaces between them take the + // tracking too: the run keeps 300.04 and stays one object. + let mut s = session(); + let text = vec!["ii"; 100].join(" "); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + // The first eight glyphs, at 0, 1, 3, 4, 6, 7, 9 and 10 (a space after each two). + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + let at = i + i / 2; + s.execute("text.setRangeStyle", &json!({"id": id, "start": at, "end": at + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat().replace(' ', ""), "i".repeat(200), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().filter(|c| *c == 'i').count(), 192, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + +#[test] +fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { + // Tracking 0.2 moves none of the 32 glyphs measured by more than the tolerance, but moves the + // glyphs 399 places on: the rest after a split keeps it and stays one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 0.2})).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(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert!(near(l.tracking, 0.2, 0.01), "{}", l.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 last = out.last().unwrap(); + assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); +} + +#[test] +fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after_a_split() { + // Tracking tighter than the space is wide, by one half to one and a half spaces more, gives the + // space a negative advance; the word space past the glyphs the tracking is measured from is + // still read. + for (unit, times) in + [("AV", 1.5), ("AV", 1.7), ("TA", 1.5), ("TA", 1.7), ("To", 1.5), ("To", 1.7), ("MM", 1.5), ("MM", 1.7), ("Wo", 1.6), ("Wo", 1.8)] + { + let mut s = session(); + let text = format!("{} {}", unit.repeat(20), unit.repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": unit, "size": 10})).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(&s, pg).into_iter().next().unwrap(); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0 * times).round(); + 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(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}"); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1, "{times}"); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)], "{times}"); + } +} + +#[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_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_when_the_budget_runs_short() { + // As above, with a measuring budget that covers the tracking's measure but not the layout of + // the pairs after the glyphs measured: those pairs still read no space. + 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(); + 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 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)); + // What measuring the tracking of the rest's first 32 glyphs takes. + let span = super::MEASURE_SPAN; + let mut measure = 100_000; + let measured = l.respaced(1, 1 + span, 0.0).unwrap().tracked_reaching(false, &mut measure, 59); + assert_eq!(measured.tracking, tracking); + let measure = 100_000 - measure; + // The pairs after the glyphs measured take three characters each. + let pairs = (60 - 1 - span + 1) * 3; + for short in (0..pairs).step_by(7) { + let mut track_budget = (span + measure + short).max(span * 6); + let (mut glyphs, mut remeasured) = (100_000, 100_000); + let r = super::rest_after_split(&l, 1, false, &mut glyphs, &mut remeasured, &mut track_budget).unwrap(); + assert_eq!(r.text, text[1..], "a budget {short} short of the pairs"); + } +} + +#[test] +fn a_word_space_after_a_glyph_kerned_against_it_reads_as_one_space_past_the_glyphs_measured() { + // The font adds 130 units to an i before a space, so the gap before the next glyph is more than + // one and a half spaces wide; the distance the pair with one space between them is laid out at + // fits one space. + use vectorcraft_text::test_fonts::{SPACE_KERNING_FAMILY, space_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(space_kerning_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_KERNING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + +#[test] +fn a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured() { + // The font takes 130 units off an i before a space, so the gap before the next glyph is under + // half a space wide; the distance the pair with one space between them is laid out at fits it. + use vectorcraft_text::test_fonts::{SPACE_NARROWING_FAMILY, space_narrowing_font}; + + vectorcraft_text::FontDb::global().add_font(space_narrowing_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_NARROWING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_NARROWING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + +#[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 + // breaks shows it is there: the word space past the glyphs the rest's tracking is measured + // from is read by that measure too. + let mut s = session(); + let text = format!("{} {}", "AV".repeat(20), "AV".repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let face = text_of(&s, id).runs[0].style.font_family.clone(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "AV", "size": 10})).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(&s, pg).into_iter().next().unwrap(); + assert_eq!(pl.face.family, face); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0).round(); + 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(&s, g).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 tightly_tracked_type_keeps_its_tracking() { // Tracking tighter than a space: the space moves the next glyph back. diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d8f91f8d50..ab8eb27255 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1991,6 +1991,101 @@ 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 [`space_kerning_font`]. +pub const SPACE_KERNING_FAMILY: &str = "Spacekern Sans"; + +/// The units [`space_kerning_font`] adds to the advance of an i that a space follows. +pub const SPACE_KERNING_UNITS: i16 = 130; + +/// The bundled Source Sans 3 Regular as family [`SPACE_KERNING_FAMILY`], its `GPOS` replaced by one +/// `kern` pair, i followed by a space, that adds [`SPACE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn space_kerning_font() -> Option> { + space_kerned_font(SPACE_KERNING_FAMILY, "Spacekern", SPACE_KERNING_UNITS) +} + +/// The family of [`space_narrowing_font`]. +pub const SPACE_NARROWING_FAMILY: &str = "Spacenarrow Sans"; + +/// The units [`space_narrowing_font`] takes off the advance of an i that a space follows. +pub const SPACE_NARROWING_UNITS: i16 = 130; + +/// [`space_kerning_font`] as family [`SPACE_NARROWING_FAMILY`], its pair taking +/// [`SPACE_NARROWING_UNITS`] off the first glyph's advance instead. `None` when it can't be built. +pub fn space_narrowing_font() -> Option> { + space_kerned_font(SPACE_NARROWING_FAMILY, "Spacenarrow", -SPACE_NARROWING_UNITS) +} + +/// The bundled Source Sans 3 Regular as `family` (`short` Sans in its PostScript name), its `GPOS` +/// replaced by one `kern` pair, i followed by a space, that adds `units` to the first glyph's +/// advance. +fn space_kerned_font(family: &str, short: &str, units: i16) -> 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 charmap = font.charmap(); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let (i, space) = (gid('i')?, gid(' ')?); + let record = PairValueRecord::new(space, ValueRecord::new().with_x_advance(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 (full, ps) = (format!("{family} Regular"), format!("{short}Sans-Regular")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &ps)])?; + 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";