mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 20:28:51 +00:00
Merge pull request #8760 from dotCooCoo/feat/retype-tracking
Retype: evenly spaced glyphs keep their spacing as tracking
This commit is contained in:
+367
-22
@@ -10,7 +10,8 @@
|
||||
//! path, inside groups too) is compared with the glyphs of the candidate fonts
|
||||
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
|
||||
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
|
||||
//! apart takes that spacing as its tracking ([`Line::tracked`]). Shapes that match no font stay as
|
||||
//! they are and are reported. Near matches (another version of the font, simplified outlines,
|
||||
//! merged glyphs) and images are phase 2.
|
||||
|
||||
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, tracking (1/1000 em)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -163,8 +164,11 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
|
||||
}
|
||||
|
||||
/// One line of retyped glyphs.
|
||||
#[derive(Clone)]
|
||||
struct Line {
|
||||
pieces: Vec<NodeId>,
|
||||
/// Tracking in 1/1000 em, added after each character, spaces included.
|
||||
tracking: f64,
|
||||
/// What each piece matched, as `pieces`.
|
||||
matches: Vec<GlyphMatch>,
|
||||
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
|
||||
@@ -204,16 +208,53 @@ impl Line {
|
||||
// Wrapped: type turned 180° has angles near +π and −π.
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
&& across < size * 0.05
|
||||
&& (m.origin - self.end).dot(dir) > -size * 0.25
|
||||
// After the line's end, or, for type tracked tighter than that, still ahead of the
|
||||
// last glyph's start (by more than rounding); the layout check decides whether it fits.
|
||||
&& ((m.origin - self.end).dot(dir) > -size * 0.25
|
||||
|| self.matches.last().is_some_and(|last| (m.origin - last.origin).dot(dir) > size * 1e-3))
|
||||
}
|
||||
|
||||
fn size(&self) -> f64 {
|
||||
self.scale * self.face.units_per_em()
|
||||
}
|
||||
|
||||
/// The shapes of the one-contour glyphs that stand alone on this line: neither the glyph before
|
||||
/// nor the one after continues it by starting after the end of the glyph before it. A glyph
|
||||
/// that joined the line only through the tight-tracking test counts as alone. A line of three
|
||||
/// glyphs or more is type (its tracking can be read), so none of its glyphs is alone.
|
||||
fn lone_one_contour(&self) -> Vec<NodeId> {
|
||||
if self.matches.len() >= 3 {
|
||||
return vec![];
|
||||
}
|
||||
let dir = self.dir();
|
||||
let size = self.size();
|
||||
// Does glyph `k` start after the end of the glyph before it, less a quarter em?
|
||||
let after_previous = |k: usize| match (k.checked_sub(1).and_then(|j| self.matches.get(j)), self.matches.get(k)) {
|
||||
(Some(a), Some(b)) => (b.origin - (a.origin + dir * (a.face.advance(a.gid) * a.scale))).dot(dir) > -size * 0.25,
|
||||
_ => false,
|
||||
};
|
||||
let n = self.matches.len();
|
||||
(0..n)
|
||||
.filter(|&k| !after_previous(k) && !after_previous(k + 1))
|
||||
.filter_map(|k| self.matches.get(k).filter(|m| m.contours == 1).and_then(|_| self.pieces.get(k).copied()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The line's tracking in points.
|
||||
fn tracking_pt(&self) -> f64 {
|
||||
self.tracking * self.size() / 1000.0
|
||||
}
|
||||
|
||||
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
|
||||
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
|
||||
// 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 gap = (m.origin - self.end).dot(dir);
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
if space > 0.0 && gap > space * 0.5 {
|
||||
let n = ((gap / space).round() as usize).clamp(1, 64);
|
||||
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));
|
||||
}
|
||||
self.text.push(m.ch);
|
||||
@@ -222,13 +263,49 @@ impl Line {
|
||||
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint, transparency, tracking and
|
||||
/// the spaces between those glyphs.
|
||||
fn part(&self, from: usize, to: usize) -> Option<Line> {
|
||||
let mut text = String::new();
|
||||
let mut glyph = 0usize;
|
||||
for c in self.text.chars() {
|
||||
// The text after glyph `to - 1` is not read.
|
||||
if glyph >= to {
|
||||
break;
|
||||
}
|
||||
if c == ' ' {
|
||||
// Spaces before glyph `glyph`, after glyph `glyph - 1`.
|
||||
if glyph > from {
|
||||
text.push(c);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if glyph >= from {
|
||||
text.push(c);
|
||||
}
|
||||
glyph += 1;
|
||||
}
|
||||
if glyph != to || to > self.matches.len() {
|
||||
return self.respaced(from, to, self.tracking);
|
||||
}
|
||||
let mut l = self.respaced(from, to.min(from.saturating_add(1)), self.tracking)?;
|
||||
l.pieces = self.pieces.get(from..to)?.to_vec();
|
||||
l.matches = self.matches.get(from..to)?.to_vec();
|
||||
let last = l.matches.last()?;
|
||||
l.end = last.origin + l.dir() * (last.face.advance(last.gid) * last.scale);
|
||||
l.text = text;
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to` at `tracking`, with its group, paint and
|
||||
/// transparency, its spaces read again from the gaps at that tracking.
|
||||
fn respaced(&self, from: usize, to: usize, tracking: f64) -> Option<Line> {
|
||||
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
|
||||
let (first, m) = (ids.first()?, ms.first()?);
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
let mut l = Line {
|
||||
pieces: vec![*first],
|
||||
tracking,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: vec![],
|
||||
text: m.ch.to_string(),
|
||||
@@ -248,8 +325,8 @@ impl Line {
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The point type that sets this line.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
/// The point type that sets this line, not yet laid out (for a layout check).
|
||||
fn probe(&self, system_layout: bool) -> TextObject {
|
||||
let style = CharStyle {
|
||||
font_family: self.face.family.clone(),
|
||||
font_style: self.face.style.clone(),
|
||||
@@ -258,6 +335,7 @@ impl Line {
|
||||
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
|
||||
features: vec!["-liga".into()],
|
||||
size: self.scale * self.face.units_per_em(),
|
||||
tracking: self.tracking,
|
||||
fill: self.appearance.fill_paint(),
|
||||
stroke: self.appearance.stroke_paint(),
|
||||
stroke_width: self.appearance.stroke_width(),
|
||||
@@ -277,6 +355,12 @@ impl Line {
|
||||
}
|
||||
t.para = super::create::new_type_para();
|
||||
t.system_layout = system_layout;
|
||||
t
|
||||
}
|
||||
|
||||
/// The point type that sets this line, laid out and measured.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
let mut t = self.probe(system_layout);
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
@@ -298,6 +382,217 @@ impl Line {
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| self.matches.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// This line with the tracking its glyphs are spaced by, when it has at least three glyphs.
|
||||
/// The glyphs are laid out untracked and without spaces, so each gap's extra is how much
|
||||
/// further apart the outlines are than the font's advances and pair kerning set them; a gap
|
||||
/// read as word spaces is measured from the glyph's own advance instead, as no pair kerning
|
||||
/// crosses a space. The extra most gaps share (the lower median, so that the word spaces of a
|
||||
/// few gaps do not count) places the word spaces; the tracking is then the lower median, over
|
||||
/// the gaps, of each gap's extra less its spaces, per character. The upper median of the
|
||||
/// extras is tried next, for a line whose word spaces are its tighter gaps, and last the lower
|
||||
/// median less one space, halved, for a line most of whose gaps hold a word space. A tracking within
|
||||
/// 0.05 of a whole number is tried rounded to it first, then as measured. A tracked line is
|
||||
/// kept when its type draws the whole line in place, or more of it from its start than
|
||||
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
|
||||
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
|
||||
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
|
||||
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
|
||||
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
|
||||
/// 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 size = self.size();
|
||||
let n = self.pieces.len();
|
||||
if n < 3 || size <= 0.0 {
|
||||
return self;
|
||||
}
|
||||
// Each layout takes its characters, spaces included, from `budget` before it runs.
|
||||
let mut take = |text: &str| match budget.checked_sub(text.chars().count()) {
|
||||
Some(left) => {
|
||||
*budget = left;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !take(&self.text) {
|
||||
return self;
|
||||
}
|
||||
let plain_miss = self.first_mismatch(&self.probe(system_layout));
|
||||
let dir = self.dir();
|
||||
// Where untracked type draws the glyphs of `text` (each layout dropped once read).
|
||||
let mut bare = self.clone();
|
||||
bare.tracking = 0.0;
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
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()
|
||||
};
|
||||
// With no spaces.
|
||||
let joined: String = self.matches.iter().map(|m| m.ch).collect();
|
||||
if !take(&joined) {
|
||||
return self;
|
||||
}
|
||||
let drawn = origins(joined);
|
||||
if drawn.len() != n {
|
||||
return self;
|
||||
}
|
||||
// And with one space between each two glyphs (kerning against the space included).
|
||||
let spaced = self.matches.iter().map(|m| m.ch.to_string()).collect::<Vec<_>>().join(" ");
|
||||
if !take(&spaced) {
|
||||
return self;
|
||||
}
|
||||
let drawn_spaced = origins(spaced);
|
||||
// A font whose space has ink draws more glyphs: then the glyph's own advance stands in.
|
||||
let spaced_ok = drawn_spaced.len() == n;
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
// Each gap's extra over the joined pair, and over the pair with one space between them
|
||||
// plus a space (so the extra counts the spaces as the joined pair's extra counts none).
|
||||
let gaps: Vec<(f64, f64)> = self
|
||||
.matches
|
||||
.windows(2)
|
||||
.enumerate()
|
||||
.zip(drawn.windows(2))
|
||||
.filter_map(|((i, m), p)| match (m, p) {
|
||||
([a, b], [pa, pb]) => {
|
||||
let d = (b.origin - a.origin).dot(dir);
|
||||
let apart = match (spaced_ok, drawn_spaced.get(i), drawn_spaced.get(i + 1)) {
|
||||
(true, Some(qa), Some(qb)) => d - (*qb - *qa).dot(dir) + space,
|
||||
_ => d - a.face.advance(a.gid) * a.scale,
|
||||
};
|
||||
Some((d - (*pb - *pa).dot(dir), apart))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let extra: Vec<f64> = gaps.iter().map(|g| g.0).collect();
|
||||
// The spaces in each gap at a tracking of `tr` points: each space takes the tracking too,
|
||||
// and tracking tighter than a space's width gives it a negative advance. A gap reads as
|
||||
// spaces when they fit it better than the joined pair does.
|
||||
let spaces = |tr: f64| -> Vec<usize> {
|
||||
gaps.iter()
|
||||
.map(|(joined, apart)| {
|
||||
let step = space + tr;
|
||||
// Spaces with no advance: one space, which still breaks the pair's kerning.
|
||||
let s = if step.abs() > 1e-9 { (apart - tr) / step } else { 1.0 };
|
||||
if !s.is_finite() {
|
||||
return 0;
|
||||
}
|
||||
// At least one space: the space's own kerning can make it fit a narrower gap.
|
||||
let k = (s.round().max(1.0) as usize).clamp(1, 64);
|
||||
// Spaces only where they fit better by more than rounding (1/100,000 em).
|
||||
if (apart - tr - k as f64 * step).abs() + size * 1e-5 < (joined - tr).abs() { k } else { 0 }
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The tracking the gaps give when the word spaces are placed by `seed`.
|
||||
let measure = |seed: f64| -> Option<f64> {
|
||||
let per: Vec<f64> = gaps
|
||||
.iter()
|
||||
.zip(spaces(seed))
|
||||
.map(|((joined, apart), s)| if s == 0 { *joined } else { (apart - s as f64 * space) / (s + 1) as f64 })
|
||||
.collect();
|
||||
median(per, false).map(|g| g / size * 1000.0)
|
||||
};
|
||||
// The lower median of the extras places the word spaces first; the upper one second, for a
|
||||
// line whose word spaces are its tighter gaps (tracking tighter than a space).
|
||||
let lower = median(extra.clone(), false);
|
||||
// A line whose word gaps are most of its gaps has a space and two trackings in each extra
|
||||
// (tracking is added after the glyph and after the space): the seed then places the spaces
|
||||
// from the extra less one space, shared by the two. It goes last, so a reading that fits
|
||||
// without it is kept (an untracked "a b c" has no such tracking).
|
||||
// Where untracked type already draws the whole line, a space and a tracking of half its
|
||||
// advance less draw it too: that reading is not tried.
|
||||
let spaced_seed = lower.filter(|_| plain_miss.is_some()).map(|e| (e - space) / 2.0);
|
||||
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] {
|
||||
if !tries.contains(&t) {
|
||||
tries.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The spaces in each gap of the line as it is (the reading `plain_miss` checked).
|
||||
let mut plain_gaps = vec![];
|
||||
let mut run = 0usize;
|
||||
for (i, c) in self.text.chars().enumerate() {
|
||||
if c == ' ' {
|
||||
run += 1;
|
||||
} else {
|
||||
if i > 0 {
|
||||
plain_gaps.push(run);
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, Line)> = None;
|
||||
for t in tries {
|
||||
if t == 0.0 || !TRACKING.contains(&t) {
|
||||
continue;
|
||||
}
|
||||
if t < 0.0 && !paints_as_one(&self) {
|
||||
return self;
|
||||
}
|
||||
let mut tracked = self.clone();
|
||||
tracked.tracking = t;
|
||||
tracked.text = String::new();
|
||||
let gaps = spaces(t * size / 1000.0);
|
||||
for (k, (m, s)) in self.matches.iter().zip(std::iter::once(0).chain(gaps.iter().copied())).enumerate() {
|
||||
if k > 0 {
|
||||
tracked.text.extend(std::iter::repeat_n(' ', s));
|
||||
}
|
||||
tracked.text.push(m.ch);
|
||||
}
|
||||
// A reading the budget cannot lay out is skipped; the next may be shorter.
|
||||
if !take(&tracked.text) {
|
||||
continue;
|
||||
}
|
||||
// When both draw the whole line (gaps as wide as whole spaces), the tracked reading is
|
||||
// kept unless it drops a gap that untracked type reads as one space: such a gap is a
|
||||
// word space ("a b c"), and the line keeps its spaces.
|
||||
let drops_a_word_space = plain_gaps.iter().zip(&gaps).any(|(plain, tracked)| *plain == 1 && *tracked == 0);
|
||||
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, _) => return tracked,
|
||||
(Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
best.map_or(self, |(_, l)| l)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does line `l` paint the same as one object as glyph by glyph where its glyphs overlap: opaque,
|
||||
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
|
||||
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
|
||||
fn paints_as_one(l: &Line) -> bool {
|
||||
l.opacity == 1.0
|
||||
&& l.blend == vectorcraft_color::BlendMode::Normal
|
||||
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
|
||||
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
|
||||
}
|
||||
|
||||
/// The tracking Retype sets, in 1/1000 em.
|
||||
const TRACKING: std::ops::RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
|
||||
/// The lower median of the finite values of `v`, or the upper one when `upper`; None for fewer
|
||||
/// than two.
|
||||
fn median(mut v: Vec<f64>, upper: bool) -> Option<f64> {
|
||||
v.retain(|x| x.is_finite());
|
||||
if v.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(if upper { v.len() / 2 } else { (v.len() - 1) / 2 }).copied()
|
||||
}
|
||||
|
||||
/// Tracking `t` rounded to a whole number when it is within 0.05 of one.
|
||||
fn round_tracking(t: f64) -> f64 {
|
||||
if (t - t.round()).abs() < 0.05 { t.round() } else { t }
|
||||
}
|
||||
|
||||
/// `lines` checked against their own layout: a line splits where its type stops drawing the
|
||||
@@ -306,6 +601,15 @@ impl Line {
|
||||
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
|
||||
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
|
||||
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
|
||||
// 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.
|
||||
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);
|
||||
let mut todo: std::collections::VecDeque<Line> = lines.into();
|
||||
let mut out = vec![];
|
||||
while let Some(l) = todo.pop_front() {
|
||||
@@ -323,28 +627,58 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
break;
|
||||
};
|
||||
budget = left;
|
||||
match part.first_mismatch(&part.text_object(system_layout)) {
|
||||
match part.first_mismatch(&part.probe(system_layout)) {
|
||||
// The whole line is drawn as it was: one object.
|
||||
None if e == n => {
|
||||
out.push(part);
|
||||
break;
|
||||
}
|
||||
None => w = w.saturating_mul(2),
|
||||
// The first glyph on its own may still be drawn as it was (a contextual form
|
||||
// changed it in the line); else it stays an outline. Checked again either way.
|
||||
Some(0) if n > 1 => {
|
||||
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
|
||||
// Tracking that type does not set as the outlines are spaced: the line is
|
||||
// checked again without it.
|
||||
Some(k) if l.tracking != 0.0 && k < 2 => {
|
||||
match l.respaced(0, n, 0.0) {
|
||||
Some(p) => todo.push_front(p),
|
||||
None => unmatched.extend(l.pieces.iter().copied()),
|
||||
}
|
||||
break;
|
||||
}
|
||||
Some(0) => {
|
||||
// A single glyph its type cannot draw as it was stays an outline.
|
||||
Some(0) if n == 1 => {
|
||||
unmatched.extend(l.pieces.first().copied());
|
||||
break;
|
||||
}
|
||||
// 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).
|
||||
// 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.
|
||||
Some(k) => {
|
||||
todo.extend_front_parts(&l, [(0, k), (k, n)]);
|
||||
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)
|
||||
};
|
||||
match rest {
|
||||
Some(r) => todo.push_front(r),
|
||||
None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()),
|
||||
}
|
||||
todo.extend_front_parts(&l, [(0, k)]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -407,6 +741,7 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Line {
|
||||
pieces: vec![id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: l.first_cands.clone(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -428,6 +763,7 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Some(Line {
|
||||
pieces: vec![pc.id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: cands.to_vec(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -531,8 +867,14 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
|
||||
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
|
||||
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
|
||||
let lone_pieces: std::collections::HashSet<NodeId> =
|
||||
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
|
||||
let lone_pieces: std::collections::HashSet<NodeId> = lines.iter().flat_map(Line::lone_one_contour).collect();
|
||||
// Each line's tracking is measured with nine layouts at most: the line as read (its
|
||||
// characters), its glyphs without and with one space between them (three times its
|
||||
// glyphs) and six tracked readings of at most 64 spaces in each gap (390 times its
|
||||
// glyphs), so every line has what its measure can take.
|
||||
let mut budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
|
||||
let lines = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
|
||||
let mut lines = verified(lines, system_layout, &mut unmatched);
|
||||
if pieces.len() > 1 {
|
||||
lines.retain(|l| {
|
||||
@@ -611,7 +953,10 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
|
||||
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
|
||||
"fonts": lines
|
||||
.iter()
|
||||
.map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.size(), "tracking": l.tracking}))
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
}))
|
||||
|
||||
@@ -477,10 +477,10 @@ fn tracked_one_contour_letters_still_become_type() {
|
||||
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<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
|
||||
assert!(texts.len() > 1, "the tracking splits the line: {r}");
|
||||
assert_eq!(r["texts"], json!([text]), "evenly tracked, the line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
assert_eq!(text_of(&s, r["ids"][0].as_u64().unwrap()).first_style().tracking, 50.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,8 +521,8 @@ fn timing_with_hundreds_of_cjk_outlines() {
|
||||
|
||||
#[test]
|
||||
fn a_long_tracked_line_is_checked_in_time() {
|
||||
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
|
||||
// line again after each split.
|
||||
// Even tracking is kept on the line; the layout check of a long line must not lay out the rest
|
||||
// of the line again after each window.
|
||||
let text = "abe".repeat(150);
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -533,7 +533,379 @@ fn a_long_tracked_line_is_checked_in_time() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text);
|
||||
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
|
||||
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
|
||||
// line of two, which the layout check splits again. Each is still a lone one-contour glyph.
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 30}));
|
||||
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
|
||||
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
|
||||
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err();
|
||||
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
|
||||
}
|
||||
|
||||
/// Where type `t` draws each glyph that has ink, in document space.
|
||||
fn glyph_places(t: &TextObject) -> Vec<kurbo::Point> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * kurbo::Point::ORIGIN)).collect()
|
||||
}
|
||||
|
||||
/// Type made with `p` (and `setup` run on its id), outlined and retyped: the original type, and
|
||||
/// Retype's result.
|
||||
fn retyped(s: &mut Session, p: serde_json::Value, setup: &[serde_json::Value]) -> (TextObject, serde_json::Value) {
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
for q in setup {
|
||||
let mut q = q.clone();
|
||||
q["id"] = json!(id);
|
||||
s.execute("text.setRangeStyle", &q).unwrap();
|
||||
}
|
||||
let before = text_of(s, id);
|
||||
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();
|
||||
(before, s.execute("type.retype", &json!({})).unwrap())
|
||||
}
|
||||
|
||||
fn assert_same_places(a: &TextObject, b: &TextObject) {
|
||||
let (pa, pb) = (glyph_places(a), glyph_places(b));
|
||||
assert_eq!(pa.len(), pb.len());
|
||||
for (x, y) in pa.iter().zip(&pb) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unevenly_tracked_type_still_becomes_type() {
|
||||
let mut s = session();
|
||||
// Less than half a space more after e: no gap can be read as a word space.
|
||||
let text = "abcdefgh";
|
||||
let (before, r) = retyped(
|
||||
&mut s,
|
||||
json!({"x": 40, "y": 100, "text": text, "size": 30}),
|
||||
&[json!({"start": 0, "end": 4, "tracking": 50}), json!({"start": 4, "end": 8, "tracking": 120})],
|
||||
);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "{r}");
|
||||
assert!(texts.len() > 1, "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
// Each object's glyphs are where the outlines were.
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
// The second half keeps its own tracking.
|
||||
assert_eq!(r["fonts"].as_array().unwrap().last().unwrap()["tracking"], json!(120.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tracked_line_keeps_its_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_line_tracked_two_spaces_wide_keeps_its_tracking() {
|
||||
// Read as it is, the line holds two spaces in each gap, which the tracking measure lays out too.
|
||||
let mut s = session();
|
||||
let text = "M".repeat(400);
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_tightly_tracked_line_keeps_its_word_spaces() {
|
||||
// Read as it is, the line holds no spaces; the tracked reading holds eight in each word gap.
|
||||
let mut s = session();
|
||||
let text = vec!["MMM"; 100].join(" ");
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": -180})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-180.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaced_letters_keep_their_spaces_when_type_draws_them() {
|
||||
// Most gaps are word spaces: untracked type with the spaces draws every glyph in place.
|
||||
// Every gap one word space: tracking a space wide would draw them too, without the spaces.
|
||||
// L T J: without its spaces the pairs kern, which a measure of the gaps would read as more space.
|
||||
for text in ["a a a aa", "1 2 3", "a b c d", "x = y + 1", "L T J"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slight_tracking_without_spaces_is_kept() {
|
||||
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
|
||||
// A word space both readings keep does not cost the tracking either.
|
||||
for text in ["MMM", "M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": 3})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(3.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<super::Line> {
|
||||
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 mut lines: Vec<super::Line> = vec![];
|
||||
for pc in &pieces {
|
||||
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
|
||||
lines.extend(super::new_line(pc, &cands));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
|
||||
// Glyph `bad` of a tracked line read as another glyph of its font, as when the line's type
|
||||
// would draw another form there: the glyphs after it are still one tracked object.
|
||||
for bad in [0usize, 1] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = 1000;
|
||||
let mut l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
let other = l.matches[bad].gid + 1;
|
||||
l.matches[bad].gid = other;
|
||||
let bad_id = l.pieces[bad];
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched, vec![bad_id], "{bad}");
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
assert_eq!(last.tracking, 300.0, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_counts_the_spaces_it_lays_out() {
|
||||
// Three glyphs ten spaces apart: a budget of six times the glyphs, short of the first
|
||||
// layout's 23 characters, lays nothing out.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "a b c", "size": 30}));
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].text.chars().filter(|c| *c == ' ').count() >= 20, "{}", lines[0].text);
|
||||
let mut budget = 3 * 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (3 * 6, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_needs_only_the_layouts_it_runs() {
|
||||
// The line as read, without spaces, with one space per gap, then the tracked reading: a
|
||||
// budget of exactly those characters recovers the tracking.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = lines[0].text.chars().count() + 6 + 11 + 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
|
||||
// Tracking 40 spaces wide: read untracked, the rest after the split holds 40 spaces per gap,
|
||||
// and its measure still has the budget to lay them out.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(100), "size": 2})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 8000})).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.tracking, 8000.0);
|
||||
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_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
|
||||
// A long tracked line whose first five glyphs are read as other glyphs: the rest is still one
|
||||
// tracked object.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).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 = 1000;
|
||||
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
for m in l.matches.iter_mut().take(5) {
|
||||
m.gid += 1;
|
||||
}
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched.len(), 5);
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tightly_tracked_type_keeps_its_tracking() {
|
||||
// Tracking tighter than a space: the space moves the next glyph back.
|
||||
// M MM: of its two gaps, the word space is the tighter, and the lower median.
|
||||
// M M MM: most gaps hold a word space, so the tightest extras alone seed a tracking that
|
||||
// splits the last glyph.
|
||||
for text in ["MMMM", "MMMM MM", "M MM", "MM M", "M M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -300})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-300.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kerned_pairs_in_tight_tracking_are_not_read_as_spaces() {
|
||||
// Tracking -250 gives a space a negative advance; the pair kerning of T and a is no space.
|
||||
let mut s = session();
|
||||
let text = "MMMTaMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_space_between_kerned_letters_is_read_as_a_space() {
|
||||
// T and a kern when they touch; with a space between them they do not.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that cancels the space's advance: the space still stops the pair kerning.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -200})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-200.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that nearly cancels it: the space still moves the glyphs after it a little.
|
||||
let mut s = session();
|
||||
let text = "MMMM MM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -199.5})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), -199.5, 1e-3), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// A word space a little narrower than its tracking makes it (the word after it moved left by
|
||||
// less than the layout check notices): one space still fits better than the kerned pair.
|
||||
for (tracking, dx) in [(-190, -0.18), (-193, -0.24)] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMc aMMM", "size": 30})).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 kids = children_of(&s, g);
|
||||
assert_eq!(kids.len(), 8);
|
||||
s.execute("select.set", &json!({"ids": kids[4..]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["MMMc aMMM"]), "{tracking}: {r}");
|
||||
}
|
||||
// A space that kerns with the letter after it.
|
||||
let mut s = session();
|
||||
let text = "MMMd TMMM";
|
||||
let p = json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Serif 4", "style": "Regular"});
|
||||
let (before, r) = retyped(&mut s, p, &[json!({"tracking": -217})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-217.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untracked_word_is_not_read_as_spaced_letters_in_tight_tracking() {
|
||||
// Letters, each followed by a space, at tracking of minus half a space, sit where the word's
|
||||
// letters do.
|
||||
let mut s = session();
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "Third", "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!(["Third"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_barely_ahead_of_each_other_stay_one_line() {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "MMMM", "size": 30}), &[json!({"tracking": -700})]);
|
||||
assert_eq!(r["texts"], json!(["MMMM"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-700.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs() {
|
||||
let mut s = session();
|
||||
let text = "i".repeat(400);
|
||||
let (before, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 50.04})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), 50.04, 1e-3), "{}", r["fonts"]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": -300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
d.node_mut(NodeId(*k)).unwrap().opacity = 0.5;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// Each glyph composites on its own over the one it overlaps, as the outlines did.
|
||||
assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}");
|
||||
}
|
||||
|
||||
+21
@@ -12468,6 +12468,27 @@ on an open path that are not drawn because they fall before the path's start can
|
||||
{"name":"run_command","arguments":{"command":"text.touchType","params":{"id":7,"start":1,"dx":10,"dy":4}}}
|
||||
```
|
||||
|
||||
## Retype tracking
|
||||
|
||||
`type.retype {fonts?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app
|
||||
has. A line of three or more glyphs gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype
|
||||
tries the value rounded to a whole number first when it is within 0.05 of one, then the value as measured. The font's
|
||||
advances and pair kerning are left out of the measure, and word spaces are counted after the tracking. The tracking is
|
||||
kept when the tracked type draws the whole line in place, or more of it from its start than untracked type does. When
|
||||
untracked type also draws the whole line, for example when gaps are as wide as whole spaces, the line stays untracked
|
||||
if the tracking is under one unit or the tracked type would drop a gap one space wide, so `a b c` stays `a b c`.
|
||||
Otherwise the tracked type is kept, and only gaps wider than the tracking alone keep spaces (narrower gaps, when
|
||||
tracking tighter than a space gives each space a negative advance). Glyphs tracked tighter than a quarter em stay on
|
||||
one line as long as each one starts after the one before it. Negative tracking is set only on a line that is opaque,
|
||||
uses the Normal blend mode, has a solid fill or none and has no stroke; other tightly spaced lines split into one object
|
||||
per glyph. A line splits where its type stops drawing the outlines in place, and the glyphs after the split take the
|
||||
tracking their own gaps give. These rules are VectorCraft's own. Each entry of the result's `fonts` list has
|
||||
`tracking`.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"type.retype","params":{}}}
|
||||
```
|
||||
|
||||
## Retype panel
|
||||
|
||||
`type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -3061,6 +3061,10 @@ The public pages describe Retype finding the fonts that match selected outlined
|
||||
|
||||
The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches, installed fonts not yet loaded and images remain.
|
||||
|
||||
## Retype tracking (2026-11-19)
|
||||
|
||||
#4934 asks Retype to match the tracking of outlined text. `type.retype` now sets a line whose glyphs most gaps space evenly apart with that spacing as tracking, keeps gaps one space wide as word spaces when untracked type draws them, and sets negative tracking only on opaque, Normal lines with a solid fill or none and no stroke. These rules are VectorCraft's own. Each line is laid out and compared with the outlines before it is kept; a line its tracked type would move a glyph of is checked again untracked, and the glyphs after a split take the tracking their own gaps give. Tested by round trips through Create Outlines (a tracked line with a word space; uneven, tight and fractional tracking; kerned pairs in tight tracking; spaced letters that need no tracking; translucent overlapping glyphs) and by the measure's layout budget, in `crates/engine/src/cmd/retype_tests.rs`.
|
||||
|
||||
## Control bar: Paragraph section while type is selected (2026-11-06)
|
||||
|
||||
With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372).
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted.
|
||||
| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character |
|
||||
| Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner |
|
||||
| Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. |
|
||||
| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) |
|
||||
| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them; VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) |
|
||||
| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) |
|
||||
| Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web |
|
||||
| Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. |
|
||||
|
||||
Reference in New Issue
Block a user