diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 29ead30e52..8a68798aed 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: 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; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched 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); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: 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; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched 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); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -777,10 +777,24 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat /// The most glyphs [`verified`] measures the tracking of after a split. const MEASURE_SPAN: usize = 32; +/// One part of shape `id`, by the glyph it matched (face, glyph, origin, turn and scale): the parts +/// of a compound path share its id. +type PartKey = (NodeId, u32, u32, [u64; 4]); + +fn part_key(id: NodeId, m: &GlyphMatch) -> PartKey { + (id, m.face.id(), m.gid, [m.origin.x.to_bits(), m.origin.y.to_bits(), m.angle.to_bits(), m.scale.to_bits()]) +} + /// `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. -fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { +/// `spacing` holds, for a part of a shape read as a combining mark, the other character that part +/// is. The glyphs laid out are bounded by a multiple of the number of glyphs. +fn verified( + lines: Vec, + system_layout: bool, + spacing: &std::collections::HashMap, + unmatched: &mut Vec, +) -> Vec { // 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::().saturating_mul(16).saturating_add(256); // Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot @@ -796,6 +810,44 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) let mut out = vec![]; while let Some(l) = todo.pop_front() { let n = l.pieces.len(); + // A combining mark goes with the character before it: a mark that a split left first on + // a line becomes the other character its shape is (`spacing`), alone on a line, or else + // stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no + // line with one). + if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + let first = l.pieces.first().copied(); + let alone = first.zip(l.matches.first()).and_then(|(id, mark)| spacing.get(&part_key(id, mark)).map(|m| reposed(&l, id, m))); + if alone.is_none() { + unmatched.extend(first); + } + if n > 1 { + // The tracking was measured with the mark's gap in it: the rest is measured again + // without it, from the same budgets as the rest after a split. A rest that starts + // with a mark too is not measured here: its own pass leaves that mark out and + // measures the glyphs after it. + let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6); + let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + l.part(1, n) + } else if measurable { + remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6)); + track_budget = track_budget.saturating_sub(n - 1); + l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) + } else if l.tracking == 0.0 { + l.part(1, n) + } else { + l.respaced(1, n, 0.0) + }; + match rest { + Some(rest) => todo.push_front(rest), + None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()), + } + } + // Checked before the rest, so the lines keep the outlines' order. + if let Some(alone) = alone { + todo.push_front(alone); + } + continue; + } // The line's type is laid out over a window from its start that doubles while the type // draws the window's glyphs as the outlines do, so finding where it stops costs about // twice the glyphs before that point, not the whole rest of the line each time. @@ -1244,6 +1296,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { .iter() .flat_map(|c| c.poses()) .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + // No line starts with a combining mark (see [`new_line`]). + .filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch)) .collect(); for fp in others { let mut turned = reposed(l, id, &fp); @@ -1278,10 +1332,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { } } -/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`), -/// with near matches taken at tolerance `slack`. +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a +/// combining mark (none: `None`), with near matches taken at tolerance `slack`. No line starts +/// with a mark: a mark combines with the character before it. fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { - let m = cands.first()?; + let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?; let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { pieces: vec![pc.id], @@ -1755,6 +1810,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; + let mut spacing: std::collections::HashMap = std::collections::HashMap::new(); // How many glyphs each shape is: a shape of several becomes type only when all of them do. let mut glyphs_of: std::collections::HashMap = std::collections::HashMap::new(); for (pc, parts) in pieces.iter().zip(&found) { @@ -1775,8 +1831,40 @@ fn retype(s: &mut Session, p: &Value) -> Result { Some(l) if open => join(l, pc, &cands), _ => false, }; + // A part that joined a line, perhaps as a mark, that is also another character, in + // that face or else in the face most shapes fit of those it is a character in: the + // character, should a split leave the part first on a line ([`verified`]). Kept by + // the glyph the part joined as, since the parts of a compound path share its id. + let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch); + if joined + && cands.iter().any(is_mark) + && let Some(m) = cands + .iter() + .find(|m| !is_mark(m)) + .or_else(|| ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m)) + && let Some(at) = lines.last().and_then(|l| l.matches.last()) + { + spacing.insert(part_key(pc.id, at), m.clone()); + } if !joined { - lines.extend(new_line(pc, &cands, tolerance)); + // A part that is only marks in that face may be another character in a face + // fewer shapes fit: it starts its line in the one of those most shapes fit. + let started = new_line(pc, &cands, tolerance).or_else(|| { + let face = ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + new_line(pc, &cands, tolerance) + }); + match started { + Some(l) => lines.push(l), + // Only combining marks: no line starts with one, so the shape stays an + // outline (a shape of several glyphs then is not whole type, see + // `partial_lines`) and the glyph after it starts the next line. + None => { + unmatched.push(pc.id); + open = false; + continue; + } + } } open = true; } @@ -1795,7 +1883,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); share_tracking(&mut lines, system_layout); - let mut lines = verified(lines, system_layout, &mut unmatched); + let mut lines = verified(lines, system_layout, &spacing, &mut unmatched); if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) { lines.retain(|l| { let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dc9a413d5f..a901ac7e12 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", has_selected_path, retype_fonts )] @@ -44,6 +44,8 @@ struct Ranked { matched: usize, /// The sum of those matches' leftover distances. residual: f64, + /// Whether some shape matched a glyph of it that is not a combining mark. + character: bool, } impl Ranked { @@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { for pc in &pieces { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64)> = vec![]; + let mut best: Vec<(Arc, f64, bool)> = vec![]; for m in index.all_matches(&pc.path) { - match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) { - Some(b) => b.1 = b.1.min(m.residual), - None => best.push((m.face, m.residual)), + let character = !vectorcraft_text::retype::is_combining_mark(m.ch); + match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { + Some(b) => { + b.1 = b.1.min(m.residual); + b.2 |= character; + } + None => best.push((m.face, m.residual, character)), } } - for (face, residual) in best { + for (face, residual, character) in best { match ranked.iter_mut().find(|r| r.face.id() == face.id()) { Some(r) => { r.matched += 1; r.residual += residual; + r.character |= character; } - None => ranked.push(Ranked { face, matched: 1, residual }), + None => ranked.push(Ranked { face, matched: 1, residual, character }), } } } + // A font whose glyphs match the shapes only as combining marks would retype none of them, as + // type.retype starts no line with a mark: it is not listed. + ranked.retain(|r| r.character); ranked.sort_by(|a, b| { b.matched .cmp(&a.matched) diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index d7e675f503..ac7723d82a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() { assert!(s.execute("type.retypeFonts", &json!({})).is_err()); } +#[test] +fn a_font_that_matches_only_combining_marks_is_not_listed() { + let mut s = session(); + // A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + // After a base, the mark counts with it. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}"); +} + #[test] fn shapes_past_the_limits_are_reported_as_left_out() { let mut s = session(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 59afb45487..5e000d52ab 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -97,6 +97,165 @@ fn a_drawn_shape_is_reported_and_left_alone() { assert!(s.doc().unwrap().doc == before); } +#[test] +fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { + use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font}; + // The comma below of Source Sans 3 is only marks there, and a modifier letter in this face. + vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap()); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); + // After a base, it joins the line as the mark; moved off its base, the split leaves it first, + // and it becomes the other face's character there. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}"); + assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); +} + +#[test] +fn a_combining_mark_starts_no_line() { + // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as + // the character. + let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}"); + // A glyph after it does not turn it back into the mark (diaeresis below, diaeresis). + let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}"); + // First on a line, the mark stays an outline and the glyphs after it are retyped. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + assert_eq!(r["unmatched"], json!([mark])); + // After a base, the mark is retyped with it. + let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}"); + // Moved off its base, the mark is where the line splits, and the part after the split does + // not start with it either. + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); + // A mark that is also another character (dot below, dot above) becomes that character there. + let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}"); + // Tracked, the part after the mark keeps the tracking its own glyphs are spaced by. + let id = s + .execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); + assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); + // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and + // beside other shapes it stays an outline too. + let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mut pair: Vec = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect(); + pair.sort_unstable(); + let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + assert_eq!(left, pair, "{r}"); +} + +#[test] +fn marks_of_one_compound_path_each_become_their_own_character() { + // Two marks that are also other characters (dot below, dot above; tilde, small tilde), moved + // off their base and made one compound path: each becomes the character its own shape is. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "x\u{323}\u{303}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let kids: Vec = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(kids.len(), 5); + s.execute("select.set", &json!({"ids": [kids[1], kids[2]]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["unmatched"], json!([]), "{r}"); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + let mut marks = texts.get(1..3).unwrap_or_default().to_vec(); + marks.sort_unstable(); + assert_eq!((texts.first(), texts.get(3), texts.len()), (Some(&"x"), Some(&"yz"), 4), "{r}"); + assert_eq!(marks, ["\u{2d9}", "\u{2dc}"], "{r}"); +} + +#[test] +fn marks_first_after_a_split_leave_other_lines_their_tracking() { + // Twenty marks moved off their base, each one first on its line in turn, do not use up the + // measures of the other lines: the tracked line retyped with them keeps its tracking. + let mut s = session(); + let marks = outlined( + &mut s, + json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}), + ); + let mut moved: Vec = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(moved.len(), 22); + moved = moved[1..21].to_vec(); + let id = s + .execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0; + moved.push(mark); + s.execute("select.set", &json!({"ids": moved})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts = r["texts"].as_array().unwrap(); + let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); + assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + moved.sort_unstable(); + assert_eq!(left, moved, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); @@ -1777,7 +1936,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() { l.matches[bad].gid = other; let bad_id = l.pieces[bad]; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &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::>()); @@ -1829,7 +1988,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() { assert_eq!(l.tracking, 8000.0); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &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::>()); @@ -1851,7 +2010,7 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { m.gid += 1; } let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &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::>()); @@ -1944,7 +2103,7 @@ fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { 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); + let out = super::verified(vec![l], false, &Default::default(), &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::>()); @@ -1974,7 +2133,7 @@ fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after 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); + let out = super::verified(vec![l], false, &Default::default(), &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}"); @@ -2011,7 +2170,7 @@ fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_ 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); + let out = super::verified(vec![l], false, &Default::default(), &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)]); @@ -2131,7 +2290,7 @@ fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { 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); + let out = super::verified(vec![l], false, &Default::default(), &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)]); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index aed9d29679..d7cf48e025 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1079,6 +1079,13 @@ fn is_shape_symbol(c: char) -> bool { ) } +/// Whether `c` is a combining mark (general category Mn, Mc or Me). A mark combines with the +/// character before it, so no retyped line starts with one. +pub fn is_combining_mark(c: char) -> bool { + use unicode_general_category::{GeneralCategory, get_general_category}; + matches!(get_general_category(c), GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark) +} + /// Complex multiply: `z` (a scaled turn) applied to `p`. fn mul(z: (f64, f64), p: Point) -> Point { Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) @@ -1722,6 +1729,18 @@ mod tests { } } + #[test] + fn combining_marks_are_told_from_spacing_characters() { + // Nonspacing (Mn), spacing (Mc) and enclosing (Me) marks. + for c in ['\u{0312}', '\u{05BD}', '\u{0903}', '\u{20DD}'] { + assert!(is_combining_mark(c), "{c:?}"); + } + // Spacing forms of the same accents are characters of their own. + for c in ['a', '\u{00A8}', '\u{02DC}', '\u{00AF}', '-'] { + assert!(!is_combining_mark(c), "{c:?}"); + } + } + #[test] fn degenerate_and_hostile_shapes_give_none() { assert!(signature(&BezPath::new()).is_none()); diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index cc7b26baa2..c9e2b8a65b 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1702,6 +1702,15 @@ pub fn private_use_font() -> Option> { remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) } +/// The family of [`spacing_comma_font`]. +pub const SPACING_COMMA_FAMILY: &str = "Spacingcomma Sans"; + +/// A face that maps only U+02BB (a modifier letter) to the bundled Source Sans 3 outline of U+0326 +/// (a combining mark), for tests of a shape that is a mark in one face and a character in another. +pub fn spacing_comma_font() -> Option> { + remapped_source_sans(SPACING_COMMA_FAMILY, "SpacingcommaSans-Regular", &[('\u{2BB}', '\u{326}')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/docs/mcp.md b/docs/mcp.md index 931315e1e3..e31046cb40 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12774,6 +12774,13 @@ per glyph. A line splits where its type stops drawing the outlines in place, and tracking their own gaps give. These rules are VectorCraft's own. Each entry of the result's `fonts` list has `tracking`. +No retyped line starts with a combining mark (Unicode general category Mn, Mc or Me). When a shape would start a line +and the first 16 glyphs it matches include another character's glyph, it starts the line as that character. When they +are all marks, the shape stays an outline and is listed in `unmatched`, and the glyph after it starts the line. The +same holds for a mark at the start of a part that a split leaves: it becomes that other character on a line of its +own, or stays an outline. A mark that follows another glyph on its line is retyped with +that glyph. This rule is VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` @@ -12810,7 +12817,8 @@ name. `count` is a whole number from 1 to 96 (default 10); any other value is an `{fonts: [{family, style, matched}], shapes, more, truncated}`: `matched` is the number of shapes the font matches, `shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and `truncated` is true when shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as outlines because of -their paint still count. The command does not change the document and records no undo step. With no path or compound +their paint still count. A font whose glyphs match the shapes only as combining marks is not listed. The +command does not change the document and records no undo step. With no path or compound path selected it is an error. Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to