mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:05:03 +00:00
Merge main into fix/flare-lone-x2-y2-error
This commit is contained in:
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -529,6 +529,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<Has
|
||||
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
|
||||
}
|
||||
|
||||
/// The faces and the edges of the Live Paint groups whose contents `p` targets (`target: "contents"`). A command that
|
||||
/// gives them a whole appearance gives a face only its fill rows and an edge only its stroke rows
|
||||
/// ([`keep_rows_of_kind`]). Both are empty without `target: "contents"`.
|
||||
pub(crate) fn contents_parts(s: &Session, p: &Value) -> Result<(HashSet<NodeId>, HashSet<NodeId>)> {
|
||||
if !targets_contents(p)? {
|
||||
return Ok((HashSet::new(), HashSet::new()));
|
||||
}
|
||||
let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?);
|
||||
Ok((faces, edges))
|
||||
}
|
||||
|
||||
/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes.
|
||||
pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) {
|
||||
if n.appearance.items.iter().any(|it| it.is_fill() != fill) {
|
||||
n.appearance.items.retain(|it| it.is_fill() == fill);
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
|
||||
|
||||
@@ -1044,12 +1062,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
|
||||
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_whole_targets(s, p, "appearance.clear")?;
|
||||
let (faces, edges) = contents_parts(s, p)?;
|
||||
// When every object is cleared already, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Clear Appearance", |d| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
// A Live Paint group's face keeps an empty fill and its edge an empty stroke.
|
||||
if faces.contains(id) || edges.contains(id) {
|
||||
keep_rows_of_kind(n, faces.contains(id));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
@@ -1284,6 +1307,7 @@ fn is_group(n: &Node) -> bool {
|
||||
|
||||
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
|
||||
let (faces, edges) = contents_parts(s, p)?;
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// The Appearance panel's active row (a row of the first selected object's stack, and in each
|
||||
@@ -1322,6 +1346,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.blend = BlendMode::Normal;
|
||||
n.appearance.items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
// A Live Paint group's face keeps only its fill and its edge only its stroke.
|
||||
if faces.contains(id) || edges.contains(id) {
|
||||
keep_rows_of_kind(n, faces.contains(id));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc
|
||||
use symbolism::symbol_set_density;
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
stored_natural_size,
|
||||
};
|
||||
use symbols::{
|
||||
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}",
|
||||
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}",
|
||||
has_doc,
|
||||
symbol_place
|
||||
),
|
||||
|
||||
@@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -
|
||||
Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF))
|
||||
}
|
||||
|
||||
/// Where a placed symbol instance goes in the active document, worked out before the edit from
|
||||
/// the drawing mode, the selection and the layer new art goes into.
|
||||
pub(crate) struct Placement {
|
||||
parent: Option<NodeId>,
|
||||
behind: bool,
|
||||
anchor: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Placement {
|
||||
/// On top of the layer new art goes into; in Draw Behind, directly below the bottommost
|
||||
/// selected object (beside the compound path that holds it), or at the bottom of that layer
|
||||
/// when nothing is selected. An error when that layer is locked or hidden.
|
||||
pub(crate) fn of(s: &Session) -> Result<Self> {
|
||||
let st = s.doc()?;
|
||||
let parent = st.target_parent()?;
|
||||
let behind = s.draw_mode == crate::DrawMode::Behind;
|
||||
let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id));
|
||||
Ok(Self { parent, behind, anchor })
|
||||
}
|
||||
|
||||
/// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the
|
||||
/// clipping path stays at the bottom.
|
||||
pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result<NodeId> {
|
||||
let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) {
|
||||
(false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?),
|
||||
(true, Some((par, i, _))) => (par, i),
|
||||
(true, None) => (self.parent, 0),
|
||||
};
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
Ok(d.insert(parent, index.max(floor), n)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn registration_param(p: &Value, cmd: &str) -> Result<Option<SymbolRegistration>> {
|
||||
match p.get("registration") {
|
||||
None => Ok(None),
|
||||
@@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?);
|
||||
let size = natural_size(d, &name);
|
||||
let reg = d.symbol_registration(&name);
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let spot = Placement::of(s)?;
|
||||
let id = s.edit("Place Symbol Instance", |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
|
||||
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -1611,13 +1611,18 @@ fn expanded_node(
|
||||
|
||||
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
|
||||
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does
|
||||
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
|
||||
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
|
||||
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
|
||||
let mut symbols = vec![];
|
||||
let mut drawn = vec![];
|
||||
let mut holds = false;
|
||||
n.walk(&mut |c| {
|
||||
if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() {
|
||||
drawn.push(c);
|
||||
}
|
||||
if !in_art && !expandable(c) {
|
||||
return;
|
||||
}
|
||||
@@ -1627,6 +1632,7 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col
|
||||
}
|
||||
});
|
||||
holds
|
||||
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|
||||
|| symbols.into_iter().any(|name| {
|
||||
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
|
||||
})
|
||||
|
||||
@@ -332,6 +332,36 @@ fn pasted_type_brings_its_kinsoku_sets() {
|
||||
assert_eq!(style_set(&s), Value::Null);
|
||||
}
|
||||
|
||||
/// Type pasted back after its set was edited breaks its lines by the set as it is now: with B in
|
||||
/// Cannot End Line the first line of `A B C` ends at A, and once the set holds nothing, it ends at B.
|
||||
#[test]
|
||||
fn pasted_type_relayouts_after_its_kinsoku_set_was_edited() {
|
||||
let mut s = session();
|
||||
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotEnd": "B"}]})).unwrap();
|
||||
let create = json!({"x": 10, "y": 10, "text": "A B C", "size": 20, "font": "JetBrains Mono", "area": {"width": 40, "height": 120}});
|
||||
let id = s.execute("text.create", &create).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap();
|
||||
let lines = |t: &vectorcraft_doc::TextObject| t.baselines().collect::<Vec<_>>();
|
||||
let first_width = |t: &vectorcraft_doc::TextObject| t.baselines().next().map(|(a, b)| b.x - a.x).unwrap_or_default();
|
||||
let copied = text(&s, id);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight"}]})).unwrap();
|
||||
// The set's edit lays the type in the document out anew, and its first line takes B.
|
||||
let edited = text(&s, id);
|
||||
assert_eq!(lines(&edited).len(), 2);
|
||||
assert!(first_width(&edited) > first_width(&copied), "{:?} against {:?}", lines(&edited), lines(&copied));
|
||||
|
||||
let v = s.execute("edit.paste", &json!({})).unwrap();
|
||||
let t = text(&s, v["ids"][0].as_u64().unwrap());
|
||||
let now = s.doc().unwrap().doc.kinsoku_sets[0].clone();
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now));
|
||||
let mut fresh = t.clone();
|
||||
crate::cmd::typecmd::refresh_bounds(&mut fresh);
|
||||
assert_eq!(lines(&t), lines(&fresh), "the pasted type is laid out with the edited set");
|
||||
assert_eq!(first_width(&t), first_width(&edited));
|
||||
}
|
||||
|
||||
/// A pasted set whose name, at the longest a name can be, the document's set with other
|
||||
/// characters already has comes in under a free name that fits: the number takes the place of the
|
||||
/// name's last characters, and a space left at the end of them is dropped. A second paste uses
|
||||
|
||||
+581
-75
@@ -13,8 +13,14 @@
|
||||
//! 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`]), and lines stacked at one leading
|
||||
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). 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.
|
||||
//! that match no font stay as they are and are reported.
|
||||
//!
|
||||
//! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another
|
||||
//! version of the font, or the outline simplified or built another way
|
||||
//! ([`RetypeIndex::near_matches`]); each line reports how closely its glyphs fit. A compound path
|
||||
//! holding several glyphs (a word outlined as one path) is split into its glyphs
|
||||
//! ([`vectorcraft_text::retype::clusters`]), and becomes type only when every one of them does.
|
||||
//! The tolerance, the score and the splitting rules are VectorCraft's own. Images are phase 2.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
@@ -22,6 +28,7 @@ use std::sync::Arc;
|
||||
use kurbo::{BezPath, Point, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::FillRule;
|
||||
use vectorcraft_text::FontDb;
|
||||
use vectorcraft_text::retype::{GlyphMatch, RetypeIndex};
|
||||
|
||||
@@ -41,7 +48,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 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 (exact matches only); 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 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); 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)}], 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…], 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, 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",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -60,6 +67,10 @@ struct Piece {
|
||||
/// art must stay painted after it: the line ends here.
|
||||
after_barrier: bool,
|
||||
path: BezPath,
|
||||
/// The shape is filled by the nonzero rule, not the even-odd rule.
|
||||
nonzero: bool,
|
||||
/// The shape has a visible fill: a shape that only has a stroke paints no area to compare.
|
||||
filled: bool,
|
||||
appearance: Appearance,
|
||||
/// The shape's own transparency, which the new type takes.
|
||||
opacity: f32,
|
||||
@@ -83,11 +94,13 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
|
||||
*barrier = true;
|
||||
return;
|
||||
}
|
||||
let piece = |path: BezPath, after_barrier: bool| Piece {
|
||||
let piece = |path: BezPath, after_barrier: bool, rule: FillRule| Piece {
|
||||
id: n.id,
|
||||
parent,
|
||||
after_barrier,
|
||||
path,
|
||||
nonzero: rule == FillRule::NonZero,
|
||||
filled: n.appearance.fill().is_some_and(|f| f.visible && !f.paint.is_none()),
|
||||
appearance: (*n.appearance).clone(),
|
||||
opacity: n.opacity,
|
||||
blend: n.blend,
|
||||
@@ -100,8 +113,10 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
|
||||
}
|
||||
}
|
||||
// Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one.
|
||||
NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
NodeKind::Path { path, rule, clipping: false, guide: false, .. } if path.is_closed() => {
|
||||
out.push(piece(path.to_bezpath(), std::mem::take(barrier), *rule))
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut path = BezPath::new();
|
||||
for c in children {
|
||||
match &c.kind {
|
||||
@@ -113,7 +128,7 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(piece(path, std::mem::take(barrier)));
|
||||
out.push(piece(path, std::mem::take(barrier), *rule));
|
||||
}
|
||||
// Live type, images, clip groups and the rest stay, and the type after them stays after them.
|
||||
_ => *barrier = true,
|
||||
@@ -185,6 +200,9 @@ struct Line {
|
||||
parent: Option<NodeId>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
/// The tolerance near matches were taken with (0: exact only): a near-matched glyph may differ
|
||||
/// that much in size, turn and place from the rest of its line ([`Self::slack_for`]).
|
||||
slack: f64,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
@@ -192,6 +210,12 @@ impl Line {
|
||||
Vec2::new(self.angle.cos(), self.angle.sin())
|
||||
}
|
||||
|
||||
/// The slack glyph `m` of this line is allowed: [`Self::slack`] when `m` or the line's first
|
||||
/// glyph, whose size and turn the line takes, is a near match, else 0.
|
||||
fn slack_for(&self, m: &GlyphMatch) -> f64 {
|
||||
if m.exact && self.matches.first().is_none_or(|f| f.exact) { 0.0 } else { self.slack }
|
||||
}
|
||||
|
||||
/// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same
|
||||
/// font, size and turn, on its baseline, after its end)?
|
||||
fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool {
|
||||
@@ -199,15 +223,16 @@ impl Line {
|
||||
let d = m.origin - self.origin;
|
||||
let dir = self.dir();
|
||||
let across = d.cross(dir).abs();
|
||||
let slack = self.slack_for(m);
|
||||
pc.parent == self.parent
|
||||
&& pc.appearance == self.appearance
|
||||
&& pc.opacity == self.opacity
|
||||
&& pc.blend == self.blend
|
||||
&& m.face.id() == self.face.id()
|
||||
// One size and turn for the whole line: the type sets every glyph at the first one's.
|
||||
&& (m.scale - self.scale).abs() <= self.scale * 1e-4
|
||||
&& (m.scale - self.scale).abs() <= self.scale * slack.max(1e-4)
|
||||
// Wrapped: type turned 180° has angles near +π and −π.
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < slack.max(1e-5)
|
||||
&& across < size * 0.05
|
||||
// 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.
|
||||
@@ -319,6 +344,7 @@ impl Line {
|
||||
parent: self.parent,
|
||||
opacity: self.opacity,
|
||||
blend: self.blend,
|
||||
slack: self.slack,
|
||||
};
|
||||
for (id, m) in ids.iter().zip(ms).skip(1) {
|
||||
l.push(*id, m);
|
||||
@@ -370,7 +396,7 @@ impl Line {
|
||||
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
|
||||
first_mismatch(t, &self.matches, self.size())
|
||||
first_mismatch(t, &self.matches, self.size(), self.slack)
|
||||
}
|
||||
|
||||
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
|
||||
@@ -395,14 +421,16 @@ impl Line {
|
||||
/// 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
|
||||
/// -1000..10000, when one of its glyphs is a near match, 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 {
|
||||
// A near-matched glyph sits within the tolerance of where the font draws it, so the gaps
|
||||
// of a line with one say nothing about spacing.
|
||||
if n < 3 || size <= 0.0 || self.matches.iter().any(|m| !m.exact) {
|
||||
return self;
|
||||
}
|
||||
// Each layout takes its characters, spaces included, from `budget` before it runs.
|
||||
@@ -568,10 +596,16 @@ impl Line {
|
||||
/// 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)
|
||||
paints_once(l.opacity, l.blend, &l.appearance)
|
||||
}
|
||||
|
||||
/// Does art with `opacity`, `blend` and `appearance` paint its overlaps the same as one object
|
||||
/// and as several ([`paints_as_one`])?
|
||||
fn paints_once(opacity: f32, blend: vectorcraft_color::BlendMode, appearance: &Appearance) -> bool {
|
||||
opacity == 1.0
|
||||
&& blend == vectorcraft_color::BlendMode::Normal
|
||||
&& matches!(appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
|
||||
&& matches!(appearance.stroke_paint(), vectorcraft_color::Paint::None)
|
||||
}
|
||||
|
||||
/// The tracking Retype sets, in 1/1000 em.
|
||||
@@ -596,21 +630,64 @@ fn round_tracking(t: f64) -> f64 {
|
||||
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
|
||||
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
// With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one,
|
||||
// may sit that much further (as a fraction of the size) from where the type draws it.
|
||||
let first_exact = matches.first().is_none_or(|f| f.exact);
|
||||
for (k, m) in matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let tol = (size * (0.01 + if m.exact && first_exact { 0.0 } else { slack })).max(0.01);
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
// The type sets the glyph at its line's size and turn, which may differ from the glyph's
|
||||
// own: the glyph drawn so must still lie within the tolerance of the shape (its center
|
||||
// within the same distance as its origin).
|
||||
if !(m.exact && first_exact) {
|
||||
let (shape, moved) = set_apart(t, g, m);
|
||||
// An exact match's own leftover is within the exact matcher's reach, not the tolerance.
|
||||
let own = if m.exact { 0.0 } else { m.pose_residual };
|
||||
if own.hypot(shape) > slack + 1e-9 || moved > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| matches.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// How glyph `g`, as type `t` draws it, differs from glyph `m` in the size, turn and place `m`
|
||||
/// was matched in. The first value bounds, whatever points the outline is sampled at, the root
|
||||
/// mean square distance between the two outlines' points about their center, relative to the
|
||||
/// root mean square distance of `m`'s points from that center (the measure of near matches'
|
||||
/// leftover distance): the largest stretch of the change from `m`'s size and turn to the drawn
|
||||
/// one, which for a change of size and turn alone is that distance exactly. The second is how far
|
||||
/// apart the two draw the center of the glyph's bounding box. Both are infinite when they cannot
|
||||
/// be measured.
|
||||
fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMatch) -> (f64, f64) {
|
||||
let (sin, cos) = m.angle.sin_cos();
|
||||
let matched = kurbo::Affine::new([m.scale * cos, m.scale * sin, -m.scale * sin, m.scale * cos, m.origin.x, m.origin.y]);
|
||||
let (gd, md) = (g.xf.determinant(), matched.determinant());
|
||||
if !gd.is_finite() || gd.abs() < 1e-12 || !md.is_finite() || md.abs() < 1e-12 {
|
||||
return (f64::INFINITY, f64::INFINITY);
|
||||
}
|
||||
let drawn = t.xf * g.xf;
|
||||
// The change from the matched glyph to the drawn one, less the identity, without the move.
|
||||
let [a, b, c, d, _, _] = (drawn * matched.inverse()).as_coeffs();
|
||||
let (a, d) = (a - 1.0, d - 1.0);
|
||||
// The largest singular value of [[a, c], [b, d]].
|
||||
let (p, q) = ((a * a + b * b + c * c + d * d) / 2.0, a * d - b * c);
|
||||
let shape = (p + (p * p - q * q).max(0.0).sqrt()).sqrt();
|
||||
// The center of the glyph's box, in font units.
|
||||
let center = g.xf.inverse() * kurbo::Shape::bounding_box(&g.outline).center();
|
||||
let moved = (drawn * center).distance(matched * center);
|
||||
let finite = |v: f64| if v.is_finite() { v } else { f64::INFINITY };
|
||||
(finite(shape), finite(moved))
|
||||
}
|
||||
|
||||
/// `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.
|
||||
@@ -739,6 +816,8 @@ struct Made {
|
||||
text: String,
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
size: f64,
|
||||
/// The tolerance near matches were taken with ([`Line::slack`]).
|
||||
slack: f64,
|
||||
tracking: f64,
|
||||
/// The leading set on the type: None for Auto or a single line.
|
||||
leading: Option<f64>,
|
||||
@@ -756,6 +835,7 @@ impl Made {
|
||||
text: l.text.clone(),
|
||||
face: l.face.clone(),
|
||||
size: l.size(),
|
||||
slack: l.slack,
|
||||
tracking: l.tracking,
|
||||
leading: None,
|
||||
opacity: l.opacity,
|
||||
@@ -888,7 +968,7 @@ impl Block {
|
||||
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
|
||||
}
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
if let Some(k) = first_mismatch(&t, &matches, size) {
|
||||
if let Some(k) = first_mismatch(&t, &matches, size, first.slack) {
|
||||
// The line that holds glyph `k`.
|
||||
let mut seen = 0usize;
|
||||
let at = self.lines.iter().position(|l| {
|
||||
@@ -917,7 +997,7 @@ impl Block {
|
||||
let mut area = t.clone();
|
||||
super::typemenu::point_to_area(&mut area);
|
||||
let mut point = None;
|
||||
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
|
||||
if in_range(&area) && first_mismatch(&area, &matches, size, first.slack).is_none() {
|
||||
point = Some(std::mem::replace(&mut t, area));
|
||||
}
|
||||
vec![Made {
|
||||
@@ -928,6 +1008,7 @@ impl Block {
|
||||
text: all.text,
|
||||
face: first.face.clone(),
|
||||
size,
|
||||
slack: first.slack,
|
||||
tracking: all.tracking,
|
||||
leading: set_leading,
|
||||
opacity: first.opacity,
|
||||
@@ -964,7 +1045,7 @@ fn share_tracking(lines: &mut [Line], system_layout: bool) {
|
||||
|
||||
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
|
||||
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
|
||||
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
|
||||
/// shape `a`, or is `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
|
||||
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let mut out = vec![];
|
||||
let mut block: Option<Block> = None;
|
||||
@@ -1054,11 +1135,13 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
|
||||
parent: l.parent,
|
||||
opacity: l.opacity,
|
||||
blend: l.blend,
|
||||
slack: l.slack,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`).
|
||||
fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<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`.
|
||||
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
|
||||
let m = cands.first()?;
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Some(Line {
|
||||
@@ -1076,18 +1159,344 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
|
||||
parent: pc.parent,
|
||||
opacity: pc.opacity,
|
||||
blend: pc.blend,
|
||||
slack,
|
||||
})
|
||||
}
|
||||
|
||||
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
|
||||
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
|
||||
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
|
||||
/// lines setting the other glyphs of the shapes it held.
|
||||
fn partial_lines(lines: &[Vec<NodeId>], glyphs_of: &std::collections::HashMap<NodeId, usize>) -> std::collections::HashSet<usize> {
|
||||
let mut dropped = std::collections::HashSet::new();
|
||||
loop {
|
||||
let mut set: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
|
||||
for (_, l) in lines.iter().enumerate().filter(|(i, _)| !dropped.contains(i)) {
|
||||
for id in l {
|
||||
*set.entry(*id).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let partial: std::collections::HashSet<NodeId> =
|
||||
set.iter().filter(|(id, n)| glyphs_of.get(*id).is_some_and(|want| *n < want)).map(|(id, _)| *id).collect();
|
||||
let before = dropped.len();
|
||||
for (i, l) in lines.iter().enumerate() {
|
||||
if l.iter().any(|id| partial.contains(id)) {
|
||||
dropped.insert(i);
|
||||
}
|
||||
}
|
||||
if dropped.len() == before {
|
||||
return dropped;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Glyph runs longer than this (in contour groups) are not tried when a shape is split.
|
||||
const MAX_RUN: usize = 3;
|
||||
|
||||
/// Complete splits of one shape that one [`split_parts`] search (exact or near) checks the paint
|
||||
/// of, at most. When none of them is accepted, that search leaves the shape whole.
|
||||
const MAX_SPLIT_TRIES: usize = 32;
|
||||
|
||||
/// A shape of more contour groups than this is not split: it is matched whole only.
|
||||
const MAX_SPLIT_GROUPS: usize = 256;
|
||||
|
||||
/// A shape of more contours than this is not split either, and its contours are not grouped.
|
||||
const MAX_SPLIT_CONTOURS: usize = 512;
|
||||
|
||||
/// Contours of all the selected shapes one command groups, at most: the shapes past them are
|
||||
/// matched whole only.
|
||||
const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384;
|
||||
|
||||
/// A shape of more path elements than this is not split, and its contours are not grouped: 16
|
||||
/// times the most a glyph may have ([`vectorcraft_text::retype::MAX_ELEMENTS`]).
|
||||
const MAX_SPLIT_ELEMENTS: usize = 16 * vectorcraft_text::retype::MAX_ELEMENTS;
|
||||
|
||||
/// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than
|
||||
/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours or [`MAX_SPLIT_ELEMENTS`]
|
||||
/// path elements, and for more contours than `budget` holds. A path of two or more contours takes
|
||||
/// them from `budget` when it is grouped.
|
||||
fn split_groups(path: &BezPath, budget: &mut usize) -> Vec<BezPath> {
|
||||
// Grouping copies the contours and compares every contour with every other: count first.
|
||||
let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count();
|
||||
if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget || path.elements().len() > MAX_SPLIT_ELEMENTS {
|
||||
return vec![];
|
||||
}
|
||||
*budget -= n;
|
||||
let groups = vectorcraft_text::retype::clusters(path);
|
||||
if (2..=MAX_SPLIT_GROUPS).contains(&groups.len()) { groups } else { vec![] }
|
||||
}
|
||||
|
||||
/// The parts of shape `path` to match: the whole shape, or, when it is no glyph and holds several
|
||||
/// contour `groups` ([`split_groups`]), runs of up to [`MAX_RUN`] groups in order, the longest that matches first (an i before a dotless i and a dot) among the runs after
|
||||
/// which the rest of the groups can still be matched. Each part with its candidates; empty when
|
||||
/// the shape matches nothing and its groups cannot all be matched. `find(path, part, near)` gives
|
||||
/// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make
|
||||
/// Compound Path may have turned the other way round, and its `near` flag allows near matches.
|
||||
/// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then
|
||||
/// its groups nearly. A split of several parts is kept only when `together(runs, near)` accepts the
|
||||
/// paths of its runs (the parts, set one beside another, paint what the shape paints); `near` is
|
||||
/// set when the parts were found by near matching.
|
||||
fn parts<M>(
|
||||
path: &BezPath,
|
||||
groups: &[BezPath],
|
||||
find: &dyn Fn(&BezPath, bool, bool) -> Vec<M>,
|
||||
together: &dyn Fn(&[BezPath], bool) -> bool,
|
||||
) -> Vec<Vec<M>> {
|
||||
let whole = find(path, false, false);
|
||||
if !whole.is_empty() {
|
||||
return vec![whole];
|
||||
}
|
||||
let exact = split_parts(groups, &|run| find(run, true, false), &|runs| together(runs, false));
|
||||
if !exact.is_empty() {
|
||||
return exact;
|
||||
}
|
||||
let whole = find(path, false, true);
|
||||
if !whole.is_empty() {
|
||||
return vec![whole];
|
||||
}
|
||||
split_parts(groups, &|run| find(run, true, true), &|runs| together(runs, true))
|
||||
}
|
||||
|
||||
/// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for
|
||||
/// no groups, when the groups cannot all be matched and when `together` rejects every split of
|
||||
/// several parts it is asked about. The complete splits are tried with the longest runs first,
|
||||
/// then with the shortest runs, then the others in order, a longer run at an earlier group first.
|
||||
/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only
|
||||
/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per
|
||||
/// group.
|
||||
fn split_parts<M>(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec<M>, together: &dyn Fn(&[BezPath]) -> bool) -> Vec<Vec<M>> {
|
||||
let g = groups.len();
|
||||
let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] };
|
||||
// A split is the runs it takes, each as (start, number of groups).
|
||||
let mut first = vec![];
|
||||
if g == 0 || !s.extend(&mut first, false) {
|
||||
return vec![];
|
||||
}
|
||||
let runs_of =
|
||||
|split: &[(usize, usize)]| -> Vec<BezPath> { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() };
|
||||
let accepted = 'search: {
|
||||
if first.len() == 1 {
|
||||
break 'search Some(first);
|
||||
}
|
||||
// The shortest runs are looked up only once the longest are rejected.
|
||||
let mut shortest = vec![];
|
||||
let mut shortest_next = true;
|
||||
let mut rest = first.clone();
|
||||
let mut candidate = Some(first.clone());
|
||||
let mut tried = 0;
|
||||
while let Some(split) = candidate.take() {
|
||||
if tried == MAX_SPLIT_TRIES {
|
||||
break;
|
||||
}
|
||||
tried += 1;
|
||||
if together(&runs_of(&split)) {
|
||||
break 'search Some(split);
|
||||
}
|
||||
if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first {
|
||||
candidate = Some(shortest.clone());
|
||||
continue;
|
||||
}
|
||||
candidate = loop {
|
||||
if !s.advance(&mut rest) {
|
||||
break None;
|
||||
}
|
||||
if rest != shortest {
|
||||
break Some(rest.clone());
|
||||
}
|
||||
};
|
||||
}
|
||||
None
|
||||
};
|
||||
let Some(split) = accepted else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for (at, n) in split {
|
||||
let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] };
|
||||
out.push(cands);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each
|
||||
/// start can all be matched, each found when the search first needs it.
|
||||
struct Splits<'a, M> {
|
||||
groups: &'a [BezPath],
|
||||
find: &'a dyn Fn(&BezPath) -> Vec<M>,
|
||||
/// By start and length less one: the run's candidates, once looked up.
|
||||
found: Vec<Vec<Option<Vec<M>>>>,
|
||||
/// By start: whether the groups from there on can all be matched, once known.
|
||||
whole: Vec<Option<bool>>,
|
||||
}
|
||||
|
||||
impl<M> Splits<'_, M> {
|
||||
/// Whether the run of `n` groups at `at` matches, looking it up the first time.
|
||||
fn matches(&mut self, at: usize, n: usize) -> bool {
|
||||
let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false };
|
||||
if slot.is_none() {
|
||||
let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default();
|
||||
*slot = Some(cands);
|
||||
}
|
||||
slot.as_ref().is_some_and(|c| !c.is_empty())
|
||||
}
|
||||
|
||||
/// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the
|
||||
/// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`]
|
||||
/// lookups and checks per group.
|
||||
fn completes(&mut self, at: usize) -> bool {
|
||||
let g = self.groups.len();
|
||||
if at >= g {
|
||||
return at == g;
|
||||
}
|
||||
if let Some(known) = self.whole.get(at).copied().flatten() {
|
||||
return known;
|
||||
}
|
||||
// From `at`: the starts still to settle, each with the run length to try next.
|
||||
let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))];
|
||||
while let Some(&(i, n)) = stack.last() {
|
||||
if self.whole.get(i).copied().flatten().is_some() {
|
||||
stack.pop();
|
||||
continue;
|
||||
}
|
||||
if n == 0 {
|
||||
if let Some(w) = self.whole.get_mut(i) {
|
||||
*w = Some(false);
|
||||
}
|
||||
stack.pop();
|
||||
continue;
|
||||
}
|
||||
if let Some(top) = stack.last_mut() {
|
||||
top.1 = n - 1;
|
||||
}
|
||||
if !self.matches(i, n) {
|
||||
continue;
|
||||
}
|
||||
let next = i + n;
|
||||
match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } {
|
||||
Some(true) => {
|
||||
if let Some(w) = self.whole.get_mut(i) {
|
||||
*w = Some(true);
|
||||
}
|
||||
stack.pop();
|
||||
}
|
||||
Some(false) => {}
|
||||
None => {
|
||||
// Settle `next` first, then try this run again.
|
||||
if let Some(top) = stack.last_mut() {
|
||||
top.1 = n;
|
||||
}
|
||||
stack.push((next, MAX_RUN.min(g - next)));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.whole.get(at).copied().flatten() == Some(true)
|
||||
}
|
||||
|
||||
/// Whether `n` groups at `at` are a run a complete split can take.
|
||||
fn fits(&mut self, at: usize, n: usize) -> bool {
|
||||
self.matches(at, n) && self.completes(at + n)
|
||||
}
|
||||
|
||||
/// Takes `split` on to the last group, with the longest run that fits at each start (or, with
|
||||
/// `shortest`, the shortest); false when no run fits.
|
||||
fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool {
|
||||
let g = self.groups.len();
|
||||
let mut i = split.last().map_or(0, |&(at, n)| at + n);
|
||||
while i < g {
|
||||
let most = MAX_RUN.min(g - i);
|
||||
let lens: Vec<usize> = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() };
|
||||
let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false };
|
||||
split.push((i, n));
|
||||
i += n;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Moves `split` on to the next complete split, in order: the runs before the last start where
|
||||
/// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last.
|
||||
fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool {
|
||||
while let Some((at, n)) = split.pop() {
|
||||
if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) {
|
||||
split.push((at, m));
|
||||
return self.extend(split, false);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Contour groups joined into one path.
|
||||
fn joined(run: &[BezPath]) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
for g in run {
|
||||
p.extend(g.iter());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Every run of contour `groups` ([`split_groups`]) [`parts`] may try.
|
||||
fn runs(groups: &[BezPath]) -> Vec<BezPath> {
|
||||
let mut out = vec![];
|
||||
for i in 0..groups.len() {
|
||||
for n in 1..=MAX_RUN.min(groups.len() - i) {
|
||||
if let Some(run) = groups.get(i..i + n) {
|
||||
out.push(joined(run));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The keys the index looks glyphs up by for the `shapes` (each with its contour groups) and
|
||||
/// every run of their groups: their exact [`shape_key`](vectorcraft_text::retype::shape_key)s and,
|
||||
/// with a `tolerance` above 0, at most [`MAX_NEAR_KEYS`](vectorcraft_text::retype::MAX_NEAR_KEYS)
|
||||
/// distinct [`near_key`](vectorcraft_text::retype::near_key)s: every whole shape's first, in the
|
||||
/// order the shapes come, then the runs of their groups. Paths past that many near keys are not
|
||||
/// looked up for near matches.
|
||||
fn lookup_keys<'a>(
|
||||
shapes: impl IntoIterator<Item = (&'a BezPath, &'a [BezPath])>,
|
||||
tolerance: f64,
|
||||
) -> (std::collections::BTreeSet<u64>, Vec<vectorcraft_text::retype::NearKey>) {
|
||||
use vectorcraft_text::retype::{MAX_NEAR_KEYS, near_key, shape_key};
|
||||
let mut wanted = std::collections::BTreeSet::new();
|
||||
let mut near_wanted = vec![];
|
||||
let mut add = |run: &BezPath| {
|
||||
wanted.extend(shape_key(run));
|
||||
if tolerance > 0.0
|
||||
&& near_wanted.len() < MAX_NEAR_KEYS
|
||||
&& let Some(k) = near_key(run)
|
||||
&& !near_wanted.contains(&k)
|
||||
{
|
||||
near_wanted.push(k);
|
||||
}
|
||||
};
|
||||
let shapes: Vec<(&BezPath, &[BezPath])> = shapes.into_iter().collect();
|
||||
// The whole shapes first, then the runs of their groups.
|
||||
for (path, _) in &shapes {
|
||||
add(path);
|
||||
}
|
||||
for (_, groups) in &shapes {
|
||||
for run in runs(groups) {
|
||||
add(&run);
|
||||
}
|
||||
}
|
||||
(wanted, near_wanted)
|
||||
}
|
||||
|
||||
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.retype";
|
||||
let fonts: Vec<String> = match p.get("fonts") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
None => vec![],
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
|
||||
};
|
||||
let tolerance = match p.get("tolerance") {
|
||||
None => 0.0,
|
||||
Some(v) => match v.as_f64() {
|
||||
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
|
||||
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
|
||||
},
|
||||
};
|
||||
let roots = selected_roots(s)?;
|
||||
let db = FontDb::global();
|
||||
let system_layout = s.doc()?.doc.setup.system_layout;
|
||||
@@ -1114,59 +1523,130 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
|
||||
}
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one: the others are
|
||||
// not sampled.
|
||||
let wanted: std::collections::BTreeSet<u64> =
|
||||
pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one exactly, and
|
||||
// only glyphs with as many contours and a close area-to-length ratio nearly: the others are
|
||||
// not sampled. A shape of several glyphs is looked up by the runs of its groups too.
|
||||
let mut budget = MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups: Vec<Vec<BezPath>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { split_groups(&pc.path, &mut budget) }).collect();
|
||||
let (wanted, near_wanted) =
|
||||
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
|
||||
// Nothing to match (every shape stays an outline): no font is read.
|
||||
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) };
|
||||
let found: Vec<Vec<GlyphMatch>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect();
|
||||
let index = if wanted.is_empty() && near_wanted.is_empty() {
|
||||
RetypeIndex::default()
|
||||
} else {
|
||||
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
|
||||
};
|
||||
// Exact matches first; near ones, when allowed, only for a path with none.
|
||||
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
|
||||
// the shape's fill rule (`fill` is `Some(nonzero)`).
|
||||
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
|
||||
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
|
||||
match fill {
|
||||
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
|
||||
None => ms,
|
||||
}
|
||||
};
|
||||
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
|
||||
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
|
||||
};
|
||||
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
|
||||
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
|
||||
.iter()
|
||||
.zip(&groups)
|
||||
.map(|(pc, g)| {
|
||||
if pc.keeps_outline {
|
||||
return vec![];
|
||||
}
|
||||
let fill = pc.filled.then_some(pc.nonzero);
|
||||
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
|
||||
// the exact one; only a part that matches nearly brings the tolerance in.
|
||||
// The glyphs of a split may become separate objects: when the shape does not paint
|
||||
// its overlaps as several objects would (translucent, another blend, a gradient or
|
||||
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
|
||||
// even-odd rule against them all joined show.
|
||||
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
|
||||
let together = |runs: &[BezPath], near: bool| {
|
||||
if fill.is_none() && once {
|
||||
return true;
|
||||
}
|
||||
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
|
||||
let tol = if nearly { tolerance } else { 0.0 };
|
||||
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
|
||||
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
|
||||
};
|
||||
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
|
||||
})
|
||||
.collect();
|
||||
// The face most shapes match, so a glyph several fonts share is set in the same font as
|
||||
// the glyphs around it.
|
||||
let mut votes: Vec<(u32, usize)> = vec![];
|
||||
for ms in &found {
|
||||
// Each shape votes once for each face it fits.
|
||||
let mut faces: Vec<u32> = ms.iter().map(|m| m.face.id()).collect();
|
||||
faces.sort_unstable();
|
||||
faces.dedup();
|
||||
for f in faces {
|
||||
match votes.iter_mut().find(|(v, _)| *v == f) {
|
||||
Some(v) => v.1 += 1,
|
||||
None => votes.push((f, 1)),
|
||||
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
|
||||
// them closest in all (the least leftover distance summed over those shapes), so every
|
||||
// part that fits it takes the same face, exact matches as near ones. Simplified outlines
|
||||
// of one font can nearly fit another font's look-alike glyphs, some of them more closely.
|
||||
// A part's matches are all exact or all near, so the distances a face sums compare alike.
|
||||
let mut votes: Vec<(u32, usize, f64)> = vec![];
|
||||
for ms in found.iter().flatten() {
|
||||
// Each shape votes once for each face it fits, with the leftover distance of its
|
||||
// closest glyph in that face.
|
||||
let mut faces: Vec<(u32, f64)> = vec![];
|
||||
for m in ms {
|
||||
let residual = if m.residual.is_finite() { m.residual } else { f64::INFINITY };
|
||||
match faces.iter_mut().find(|(f, _)| *f == m.face.id()) {
|
||||
Some(f) => f.1 = f.1.min(residual),
|
||||
None => faces.push((m.face.id(), residual)),
|
||||
}
|
||||
}
|
||||
for (f, residual) in faces {
|
||||
match votes.iter_mut().find(|(v, ..)| *v == f) {
|
||||
Some(v) => {
|
||||
v.1 += 1;
|
||||
v.2 += residual;
|
||||
}
|
||||
None => votes.push((f, 1, residual)),
|
||||
}
|
||||
}
|
||||
}
|
||||
let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1);
|
||||
let rank = |face: u32| votes.iter().find(|(f, ..)| *f == face).map_or((0, f64::INFINITY), |v| (v.1, v.2));
|
||||
// Most votes, then the least summed distance, then the first (the matches come upright and
|
||||
// closest first).
|
||||
let ranked = |(i, a): &(usize, &GlyphMatch), (j, b): &(usize, &GlyphMatch)| {
|
||||
let ((va, da), (vb, db)) = (rank(a.face.id()), rank(b.face.id()));
|
||||
va.cmp(&vb).then(db.total_cmp(&da)).then(j.cmp(i))
|
||||
};
|
||||
let mut lines: Vec<Line> = vec![];
|
||||
let mut unmatched = vec![];
|
||||
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
|
||||
let mut open = false;
|
||||
for (pc, ms) in pieces.iter().zip(&found) {
|
||||
// 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<NodeId, usize> = std::collections::HashMap::new();
|
||||
for (pc, parts) in pieces.iter().zip(&found) {
|
||||
if pc.after_barrier {
|
||||
open = false;
|
||||
}
|
||||
// The shape's candidates in the face most shapes fit (the first such face, as the
|
||||
// matches come upright and closest first).
|
||||
let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id());
|
||||
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
|
||||
if cands.is_empty() {
|
||||
if parts.is_empty() {
|
||||
unmatched.push(pc.id);
|
||||
open = false;
|
||||
continue;
|
||||
}
|
||||
let joined = match lines.last_mut() {
|
||||
Some(l) if open => join(l, pc, &cands),
|
||||
_ => false,
|
||||
};
|
||||
if !joined {
|
||||
lines.extend(new_line(pc, &cands));
|
||||
glyphs_of.insert(pc.id, parts.len());
|
||||
for ms in parts {
|
||||
// The part's candidates in the face most shapes fit (see `ranked`).
|
||||
let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id());
|
||||
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
|
||||
let joined = match lines.last_mut() {
|
||||
Some(l) if open => join(l, pc, &cands),
|
||||
_ => false,
|
||||
};
|
||||
if !joined {
|
||||
lines.extend(new_line(pc, &cands, tolerance));
|
||||
}
|
||||
open = true;
|
||||
}
|
||||
open = true;
|
||||
}
|
||||
// A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn
|
||||
// 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).
|
||||
// art (a dot, a bar): beside other shapes, the other glyphs of a split compound path
|
||||
// included, 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().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
|
||||
@@ -1177,7 +1657,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut lines: Vec<Line> = 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);
|
||||
if pieces.len() > 1 {
|
||||
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));
|
||||
if lone {
|
||||
@@ -1186,9 +1666,24 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
!lone
|
||||
});
|
||||
}
|
||||
let dropped = partial_lines(&lines.iter().map(|l| l.pieces.clone()).collect::<Vec<_>>(), &glyphs_of);
|
||||
let mut k = 0;
|
||||
lines.retain(|l| {
|
||||
let keep = !dropped.contains(&k);
|
||||
k += 1;
|
||||
if !keep {
|
||||
unmatched.extend(l.pieces.iter().copied());
|
||||
}
|
||||
keep
|
||||
});
|
||||
// A shape of several glyphs is reported once, and not when it became type.
|
||||
let kept: std::collections::HashSet<NodeId> = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
unmatched.retain(|id| !kept.contains(id) && seen.insert(*id));
|
||||
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
|
||||
// Lines split from one compound path share its shape, with nothing between them.
|
||||
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
|
||||
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
|
||||
(Some(i), Some(j)) => *j == *i || (*j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier)),
|
||||
_ => false,
|
||||
};
|
||||
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
|
||||
@@ -1204,6 +1699,9 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
|
||||
let mut ids = vec![];
|
||||
let mut emptied = vec![];
|
||||
// Every line's type goes in before the shapes go: a shape of several glyphs is the first
|
||||
// shape of more than one line. Each goes just before its first shape, so lines from one
|
||||
// shape keep their order.
|
||||
for l in &lines {
|
||||
let Some(first) = l.pieces.first() else { continue };
|
||||
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
|
||||
@@ -1213,14 +1711,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
node.opacity = l.opacity;
|
||||
node.blend = l.blend;
|
||||
d.insert(par, idx, node)?;
|
||||
for pc in &l.pieces {
|
||||
if let Some((Some(parent), _, _)) = d.position(*pc) {
|
||||
emptied.push(parent);
|
||||
}
|
||||
d.remove(*pc)?;
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
let mut removed = std::collections::HashSet::new();
|
||||
for pc in lines.iter().flat_map(|l| l.pieces.iter()) {
|
||||
if !removed.insert(*pc) {
|
||||
continue;
|
||||
}
|
||||
if let Some((Some(parent), _, _)) = d.position(*pc) {
|
||||
emptied.push(parent);
|
||||
}
|
||||
d.remove(*pc)?;
|
||||
}
|
||||
// A group left holding only the new type (Create Outlines' group) gives way to it, unless
|
||||
// the group has transparency, effects, a mask or a name of its own, which then keep
|
||||
// applying to the type inside it. A group left empty goes.
|
||||
@@ -1284,7 +1786,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
|
||||
let Some(point) = &l.point else { continue };
|
||||
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
|
||||
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
|
||||
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size, l.slack).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
@@ -1306,14 +1808,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"fonts": lines
|
||||
.iter()
|
||||
.zip(&made)
|
||||
.map(|(l, id)| json!({
|
||||
"family": l.face.family,
|
||||
"style": l.face.style,
|
||||
"size": l.size,
|
||||
"tracking": l.tracking,
|
||||
"leading": l.leading,
|
||||
"area": area(id),
|
||||
}))
|
||||
.map(|(l, id)| {
|
||||
let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min);
|
||||
json!({
|
||||
"family": l.face.family,
|
||||
"style": l.face.style,
|
||||
"size": l.size,
|
||||
"tracking": l.tracking,
|
||||
"leading": l.leading,
|
||||
"area": area(id),
|
||||
"score": (score * 1000.0).round() / 1000.0,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
|
||||
@@ -10,7 +10,13 @@ fn session() -> Session {
|
||||
}
|
||||
|
||||
/// Point text, outlined: the id of the outlines' group.
|
||||
fn outlined(s: &mut Session, p: serde_json::Value) -> u64 {
|
||||
fn outlined(s: &mut Session, mut p: serde_json::Value) -> u64 {
|
||||
// A text without a font is set in the system's default face, which differs from machine to
|
||||
// machine and decides which glyphs a near match can tell apart.
|
||||
if p.get("font").is_none() {
|
||||
p["font"] = json!("Source Sans 3");
|
||||
p["style"] = json!("Regular");
|
||||
}
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap()
|
||||
@@ -84,7 +90,7 @@ fn a_drawn_shape_is_reported_and_left_alone() {
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] {
|
||||
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"}), json!(null)] {
|
||||
let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("fonts must be a list of family names"), "{e}");
|
||||
}
|
||||
@@ -539,6 +545,118 @@ fn a_long_tracked_line_is_checked_in_time() {
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
}
|
||||
|
||||
/// Every path in the document flattened into lines `tol` from its curves, each contour started at
|
||||
/// its second point and run backwards: outlines simplified and built nothing like the font's.
|
||||
fn simplify_every_path(s: &mut Session, tol: f64) {
|
||||
let mut ids = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
simplify_paths(s, &ids, tol);
|
||||
}
|
||||
|
||||
/// [`simplify_every_path`] for the paths `ids` only.
|
||||
fn simplify_paths(s: &mut Session, ids: &[NodeId], tol: f64) {
|
||||
s.edit("test", |d, _| {
|
||||
for id in ids {
|
||||
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
|
||||
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
|
||||
kurbo::flatten(data.to_bezpath().iter(), tol, |el| match el {
|
||||
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
|
||||
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
|
||||
_ => {}
|
||||
});
|
||||
let mut out = kurbo::BezPath::new();
|
||||
for mut c in contours {
|
||||
if c.len() > 1 && c.first() == c.last() {
|
||||
c.pop();
|
||||
}
|
||||
c.rotate_left(1);
|
||||
c.reverse();
|
||||
out.move_to(c[0]);
|
||||
for q in &c[1..] {
|
||||
out.line_to(*q);
|
||||
}
|
||||
out.close_path();
|
||||
}
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&out);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
simplify_every_path(&mut s, 0.05);
|
||||
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"), "no exact match: {e}");
|
||||
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
|
||||
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["style"].as_str()), (Some("Source Sans 3"), Some("Regular")));
|
||||
let score = r["fonts"][0]["score"].as_f64().unwrap();
|
||||
assert!(score > 0.5 && score < 1.0, "a near match scores below an exact one: {score}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(near(t.first_style().size, 40.0, 0.4), "size {}", t.first_style().size);
|
||||
let o = t.xf.translation();
|
||||
assert!(near(o.x, 40.0, 0.4) && near(o.y, 100.0, 0.4), "baseline start {o:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_matches_score_one() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["score"], json!(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_matches_with_a_small_leftover_still_score_one() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
|
||||
// Each glyph stretched 0.1% across its own centre: still within the exact matcher's reach, with
|
||||
// a leftover distance above 0.
|
||||
let mut ids = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
s.edit("test", |d, _| {
|
||||
for id in &ids {
|
||||
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
|
||||
let p = data.to_bezpath();
|
||||
let c = kurbo::Shape::bounding_box(&p).center();
|
||||
let xf = kurbo::Affine::translate(c.to_vec2()) * kurbo::Affine::scale_non_uniform(1.001, 1.0) * kurbo::Affine::translate(-c.to_vec2());
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * p));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// Each glyph's size now differs a little, so each is its own line.
|
||||
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
|
||||
assert_eq!(texts.concat(), "Rag", "{r}");
|
||||
for f in r["fonts"].as_array().unwrap() {
|
||||
assert_eq!(f["score"], json!(1.0), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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
|
||||
@@ -583,6 +701,55 @@ fn assert_same_places(a: &TextObject, b: &TextObject) {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_glyphs_of_another_size_are_another_line_even_with_a_tolerance() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tia", "size": 40}));
|
||||
// The a (two contours, so not a lone one-contour glyph) made 4% larger about where it starts
|
||||
// on the baseline: still exactly the glyph.
|
||||
let a = *children_of(&s, g).last().unwrap();
|
||||
// The a's paths (a compound path's, or its own).
|
||||
let paths: Vec<u64> = match s.doc().unwrap().doc.node(NodeId(a)).unwrap().children() {
|
||||
Some(c) => c.iter().map(|c| c.id.0).collect(),
|
||||
None => vec![a],
|
||||
};
|
||||
s.edit("test", |d, _| {
|
||||
let x0 = paths
|
||||
.iter()
|
||||
.map(|id| kurbo::Shape::bounding_box(&d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap().to_bezpath()).x0)
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
let at = kurbo::Vec2::new(x0, 100.0);
|
||||
let xf = kurbo::Affine::translate(at) * kurbo::Affine::scale(1.04) * kurbo::Affine::translate(-at);
|
||||
for id in &paths {
|
||||
let data = d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap();
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Ti", "a"]), "{r}");
|
||||
let sizes: Vec<f64> = r["fonts"].as_array().unwrap().iter().map(|f| f["size"].as_f64().unwrap()).collect();
|
||||
assert!(near(sizes[0], 40.0, 0.01) && near(sizes[1], 41.6, 0.01), "{sizes:?}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["score"] == json!(1.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_near_matched_round_glyphs_keep_the_line_turn() {
|
||||
// Round glyphs (o, O, the period) and glyphs that look alike half round (N, x, z) fit
|
||||
// simplified outlines at more than one turn: each takes the turn of its line.
|
||||
for (text, rotation) in [("no.", 90), ("no.", 180), ("zoo", 135), ("NOON", 180), ("xoxo", 200), ("on", 120)] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": text, "size": 40, "rotation": rotation}));
|
||||
simplify_every_path(&mut s, 0.05);
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "turned {rotation}: {r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_lines_become_one_area_type_object() {
|
||||
let mut s = session();
|
||||
@@ -870,6 +1037,660 @@ fn spaced_letters_keep_their_spaces_when_type_draws_them() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() {
|
||||
// The m (one path) of simplified outlines moved along the baseline by `shift` of the font
|
||||
// size (40), retyped with a tolerance of 0.03: it may sit 1% + 3% of the size from where the
|
||||
// type draws it.
|
||||
let run = |shift: f64| {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
|
||||
simplify_every_path(&mut s, 0.05);
|
||||
let m = *children_of(&s, g).last().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * shift, 0.0)) * data.to_bezpath()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.03})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), "Tim", "{r}");
|
||||
texts.len()
|
||||
};
|
||||
assert_eq!(run(0.02), 1, "within the tolerance: one line");
|
||||
assert!(run(0.06) > 1, "past it: the line splits where the m was moved");
|
||||
}
|
||||
|
||||
/// The bounding box of shape `id` (a path, or a compound path's paths), in document space.
|
||||
fn shape_box(s: &Session, id: u64) -> kurbo::Rect {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(NodeId(id)).unwrap();
|
||||
let paths: Vec<&vectorcraft_doc::Node> = match n.children() {
|
||||
Some(c) => c.iter().map(|c| &**c).collect(),
|
||||
None => vec![n],
|
||||
};
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(|p| match &p.kind {
|
||||
NodeKind::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path.to_bezpath())),
|
||||
_ => None,
|
||||
})
|
||||
.reduce(|a, b| a.union(b))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The bounding box of each glyph with ink that type `t` draws, in document space.
|
||||
fn drawn_boxes(t: &TextObject) -> Vec<kurbo::Rect> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| kurbo::Shape::bounding_box(&(t.xf * g.outline.clone()))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_glyph_whose_size_and_turn_differ_past_the_tolerance_ends_the_line() {
|
||||
// The m of simplified outlines made 4% larger, and turned 0.04 radians as well, about where it
|
||||
// starts on the baseline, retyped with a tolerance of 0.05. Each change alone is within the
|
||||
// size and turn a near-matched line allows, but drawn at the line's size and turn the m would
|
||||
// lie further than 0.05 of its spread from its outline: it becomes type of its own. Larger
|
||||
// alone, it is still within the tolerance and stays on the line.
|
||||
for (scale, turn, lines) in [(1.04, 0.0, 1), (1.04, 0.04, 2)] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
|
||||
simplify_every_path(&mut s, 0.05);
|
||||
let kids = children_of(&s, g);
|
||||
let m = *kids.last().unwrap();
|
||||
let x0 = shape_box(&s, m).x0;
|
||||
s.edit("test", |d, _| {
|
||||
let at = kurbo::Vec2::new(x0, 100.0);
|
||||
let xf = kurbo::Affine::translate(at) * kurbo::Affine::rotate(turn) * kurbo::Affine::scale(scale) * kurbo::Affine::translate(-at);
|
||||
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before: Vec<kurbo::Rect> = kids.iter().map(|k| shape_box(&s, *k)).collect();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
|
||||
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
|
||||
assert_eq!(texts.concat(), "Tim", "{r}");
|
||||
assert_eq!(texts.len(), lines, "scale {scale}, turn {turn}: {r}");
|
||||
if lines == 1 {
|
||||
continue;
|
||||
}
|
||||
let drawn: Vec<kurbo::Rect> = r["ids"].as_array().unwrap().iter().flat_map(|id| drawn_boxes(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
assert_eq!(drawn.len(), before.len(), "{r}");
|
||||
for b in &before {
|
||||
// The glyph drawn nearest where the outline was.
|
||||
let d = drawn.iter().min_by(|p, q| p.center().distance(b.center()).total_cmp(&q.center().distance(b.center()))).unwrap();
|
||||
let size = b.width().hypot(b.height());
|
||||
assert!(
|
||||
(d.width() - b.width()).abs() < size * 0.01 && (d.height() - b.height()).abs() < size * 0.01,
|
||||
"scale {scale}, turn {turn}: the outline's box {b:?}, the type's {d:?}: {r}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
|
||||
let m = *children_of(&s, g).last().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Ti", "m"]), "exact glyphs keep the exact limits: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exact_glyph_after_a_near_one_keeps_the_exact_limits() {
|
||||
// T exact, o simplified (a near match), m exact moved by 3% of the size along the baseline.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tom", "size": 40}));
|
||||
let kids = children_of(&s, g);
|
||||
let o: Vec<NodeId> = match s.doc().unwrap().doc.node(NodeId(kids[1])).unwrap().children() {
|
||||
Some(c) => c.iter().map(|c| c.id).collect(),
|
||||
None => vec![NodeId(kids[1])],
|
||||
};
|
||||
simplify_paths(&mut s, &o, 0.05);
|
||||
let m = kids[2];
|
||||
s.edit("test", |d, _| {
|
||||
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["To", "m"]), "the near o does not loosen the m's limits: {r}");
|
||||
}
|
||||
|
||||
/// The outlines of `text` made into one compound path: the compound's id.
|
||||
fn one_compound(s: &mut Session, text: &str) -> u64 {
|
||||
let g = outlined(s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
|
||||
let glyphs = children_of(s, g);
|
||||
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_outlined_as_one_compound_path_splits_into_its_glyphs() {
|
||||
let mut s = session();
|
||||
let c = one_compound(&mut s, "Tim");
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Tim"]), "the i's stem and dot are one glyph: {r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
|
||||
let mut s = session();
|
||||
// An A and, far below it, a period, made into one compound path and selected alone: the
|
||||
// period, alone on its baseline beside the A, is a dot as much as a period, so it stays an
|
||||
// outline, and so does the A in the same compound.
|
||||
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
|
||||
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
|
||||
let mut ids = children_of(&s, t);
|
||||
ids.extend(children_of(&s, dot));
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
Ok(r) => panic!("the period became type: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains("(1 checked)"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_from_one_compound_path_keep_their_order() {
|
||||
let mut s = session();
|
||||
// Two lines of outlines made into one compound path, farther apart than the lines of one
|
||||
// paragraph, so each stays an object of its own.
|
||||
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
|
||||
let low = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Ham", "size": 40}));
|
||||
let mut glyphs = children_of(&s, top);
|
||||
glyphs.extend(children_of(&s, low));
|
||||
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 2, "{r}");
|
||||
let texts: Vec<String> = ids.iter().map(|id| text_of(&s, *id).plain_text()).collect();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let at: Vec<usize> = ids.iter().map(|id| d.position(NodeId(*id)).unwrap().1).collect();
|
||||
// The lines stack in the order of the compound's contours: the first line behind the second.
|
||||
let first = texts.iter().position(|t| t == "Tim").unwrap();
|
||||
let second = texts.iter().position(|t| t == "Ham").unwrap();
|
||||
assert!(at[first] < at[second], "{texts:?} at {at:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_lines_from_one_compound_path_become_one_object() {
|
||||
let mut s = session();
|
||||
// Two lines of one paragraph, outlined and made into one compound path: they join as the
|
||||
// lines of separate outlines do.
|
||||
let text = "Tim\nHam";
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
|
||||
let glyphs = children_of(&s, g);
|
||||
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ti", "size": 40}));
|
||||
let mut ids = children_of(&s, g);
|
||||
// A shape no glyph is, beside the letters, in the same compound.
|
||||
ids.push(s.execute("shape.star", &json!({"cx": 140, "cy": 85, "radius1": 12, "radius2": 5, "points": 7})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("(1 checked)"), "reported once: {e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
|
||||
let mut s = session();
|
||||
// Two o's moved onto each other and made into one compound path: the even-odd rule leaves
|
||||
// the overlap unpainted, and two glyphs set side by side would paint it.
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
|
||||
let kids = children_of(&s, g);
|
||||
s.execute("object.move", &json!({"ids": [kids[1]], "dx": -9, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": kids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
Ok(r) => panic!("the overlapping o's became type: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains("(1 checked)"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
|
||||
// Two i's, the second moved half onto the first and down off its baseline, made into one
|
||||
// compound path filled by the nonzero rule with every contour running one way: the parts paint
|
||||
// the shape's area, but on two lines they become two objects, and at 50% opacity their
|
||||
// overlap would be painted twice.
|
||||
for opacity in [1.0f32, 0.5] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ii", "size": 40}));
|
||||
let kids = children_of(&s, g);
|
||||
let dx = shape_box(&s, kids[0]).x0 - shape_box(&s, kids[1]).x0 + 2.0;
|
||||
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 6})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": kids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let paths = children_of(&s, c);
|
||||
s.edit("test", |d, _| {
|
||||
// Make Compound Path turns the second glyph's contours the other way round.
|
||||
for p in &paths {
|
||||
let data = d.node_mut(NodeId(*p)).unwrap().path_data_mut().unwrap();
|
||||
let b = data.to_bezpath();
|
||||
if kurbo::Shape::area(&b) < 0.0 {
|
||||
*data = vectorcraft_geom::PathData::from_bezpath(&b.reverse_subpaths());
|
||||
}
|
||||
}
|
||||
let n = d.node_mut(NodeId(c)).unwrap();
|
||||
n.opacity = opacity;
|
||||
if let NodeKind::Compound { rule, .. } = &mut n.kind {
|
||||
*rule = vectorcraft_geom::FillRule::NonZero;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({}));
|
||||
if opacity == 1.0 {
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
|
||||
} else {
|
||||
assert!(r.is_err(), "translucent, the compound stays an outline: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
|
||||
// Exact parts the even-odd rule rejects stay rejected when the near phase finds them again.
|
||||
for dx in [-9.0, -11.0, -12.0, -13.0, -14.0] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
|
||||
let kids = children_of(&s, g);
|
||||
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": kids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
for tolerance in [0.0, 0.05] {
|
||||
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
|
||||
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_parts_of_a_compound_are_checked_at_tolerance_zero() {
|
||||
let mut s = session();
|
||||
// A T and an o whose boxes overlap by 4 units, one painted area apart (the o sits under the
|
||||
// bar's arm): a strip that the probes of tolerance 0.05 cannot see into but those of an exact
|
||||
// match can. Both parts match exactly, so asking for near matches does not change the result.
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "To", "size": 40}));
|
||||
let kids = children_of(&s, g);
|
||||
let (t, o) = (kids[0], kids[1]);
|
||||
let bounds = |s: &Session, id: u64| s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
|
||||
let dx = bounds(&s, t).x1 - 4.0 - bounds(&s, o).x0;
|
||||
s.execute("object.move", &json!({"ids": [o], "dx": dx, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": kids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
for params in [json!({}), json!({"tolerance": 0.05})] {
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("type.retype", ¶ms).unwrap();
|
||||
assert_eq!(r["unmatched"], json!([]), "{params}: {r}");
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "{params}: the compound becomes type");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before, "{params}: undo restores it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
|
||||
let mut s = session();
|
||||
let c = one_compound(&mut s, "oo");
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["oo"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
|
||||
let mut s = session();
|
||||
// An A (two contours), and far below it a period: a lone one-contour glyph beside other
|
||||
// shapes stays an outline, so the A, in the same compound, must stay too.
|
||||
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
|
||||
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
|
||||
let paths = |s: &Session, id: u64| match s.doc().unwrap().doc.node(NodeId(id)).unwrap().children() {
|
||||
Some(c) => c.iter().map(|c| c.id.0).collect(),
|
||||
None => vec![id],
|
||||
};
|
||||
let mut ids: Vec<u64> = paths(&s, t);
|
||||
ids.extend(paths(&s, dot));
|
||||
assert_eq!(ids.len(), 2, "one path each");
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
Ok(r) => panic!("the A became type without its period: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains("(2 checked)"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() {
|
||||
use kurbo::Shape;
|
||||
// Three groups A, B and C side by side. A and B together are a glyph, but then C alone is
|
||||
// none; A alone and B and C together are glyphs, so the split is A, BC.
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for x in [0.0, 100.0, 200.0] {
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
}
|
||||
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(true, 0, 140) => vec!["AB"],
|
||||
(true, 0, 40) => vec!["A"],
|
||||
(true, 100, 240) => vec!["BC"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let groups = all_groups(&p);
|
||||
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["A"], vec!["BC"]]);
|
||||
// A split the parts' paint does not allow is dropped.
|
||||
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
|
||||
// With no way to match every group, nothing.
|
||||
let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] }
|
||||
};
|
||||
assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() {
|
||||
use kurbo::Shape;
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for x in [0.0, 100.0, 200.0] {
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
}
|
||||
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(true, 0, 140) => vec!["AB"],
|
||||
(true, 0, 40) => vec!["A"],
|
||||
(true, 100, 140) => vec!["B"],
|
||||
(true, 200, 240) => vec!["C"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let groups = all_groups(&p);
|
||||
// The longest runs first (AB, C) are rejected; the three single glyphs are kept.
|
||||
let singles = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 3;
|
||||
assert_eq!(super::parts(&p, &groups, &find, &singles), vec![vec!["A"], vec!["B"], vec!["C"]]);
|
||||
// When no complete split is accepted, nothing.
|
||||
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_between_the_longest_and_the_shortest_runs_is_tried() {
|
||||
use kurbo::Shape;
|
||||
// Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs
|
||||
// (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts.
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for x in [0.0, 100.0, 200.0, 300.0] {
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
}
|
||||
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(true, 0, 240) => vec!["ABC"],
|
||||
(true, 0, 140) => vec!["AB"],
|
||||
(true, 200, 340) => vec!["CD"],
|
||||
(true, 0, 40) => vec!["A"],
|
||||
(true, 100, 140) => vec!["B"],
|
||||
(true, 200, 240) => vec!["C"],
|
||||
(true, 300, 340) => vec!["D"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let groups = all_groups(&p);
|
||||
let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140);
|
||||
assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_most_max_split_tries_complete_splits_are_checked() {
|
||||
use kurbo::Shape;
|
||||
// Twelve groups, every run of up to three of them a glyph: far more complete splits than the
|
||||
// cap. The paint check is asked about the cap's number of them and no more, and each run is
|
||||
// looked up at most once.
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for i in 0..12 {
|
||||
let x = f64::from(i) * 100.0;
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
}
|
||||
let groups = all_groups(&p);
|
||||
assert_eq!(groups.len(), 12);
|
||||
let looked_up = std::cell::Cell::new(0usize);
|
||||
let find = |_: &kurbo::BezPath| -> Vec<&'static str> {
|
||||
looked_up.set(looked_up.get() + 1);
|
||||
vec!["glyph"]
|
||||
};
|
||||
let asked = &std::cell::Cell::new(0usize);
|
||||
let accept_at = |n: usize| {
|
||||
move |_: &[kurbo::BezPath]| {
|
||||
asked.set(asked.get() + 1);
|
||||
asked.get() == n
|
||||
}
|
||||
};
|
||||
// Rejected every time: the search stops at the cap.
|
||||
assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty());
|
||||
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
|
||||
assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get());
|
||||
// A first split that is accepted looks up its own runs only: four runs of three groups.
|
||||
asked.set(0);
|
||||
looked_up.set(0);
|
||||
assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4);
|
||||
assert_eq!(looked_up.get(), 4);
|
||||
// The last split tried is still taken; the one past the cap is not tried.
|
||||
asked.set(0);
|
||||
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1);
|
||||
asked.set(0);
|
||||
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty());
|
||||
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
|
||||
}
|
||||
|
||||
/// `path`'s contour groups, with no limit on the contours grouped.
|
||||
fn all_groups(path: &kurbo::BezPath) -> Vec<kurbo::BezPath> {
|
||||
let mut budget = usize::MAX;
|
||||
super::split_groups(path, &mut budget)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() {
|
||||
use kurbo::Shape;
|
||||
// Two groups side by side, each exactly a glyph (two periods), and the whole only nearly one
|
||||
// (a dieresis): the parts win.
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for x in [0.0, 100.0] {
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
}
|
||||
let find = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(false, true, 0, 140) => vec!["dieresis"],
|
||||
(true, _, 0, 40) | (true, _, 100, 140) => vec!["period"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let groups = all_groups(&p);
|
||||
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["period"], vec!["period"]]);
|
||||
// When the parts match only nearly too, the whole near match comes first.
|
||||
let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(false, true, 0, 140) => vec!["dieresis"],
|
||||
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
assert_eq!(super::parts(&p, &groups, &near_only, &|_, _| true), vec![vec!["dieresis"]]);
|
||||
// The split's paint check is told whether the parts were found nearly: exact parts are
|
||||
// checked at tolerance 0 whatever tolerance the command was given.
|
||||
let seen = std::cell::RefCell::new(vec![]);
|
||||
let record = |_: &[kurbo::BezPath], near: bool| {
|
||||
seen.borrow_mut().push(near);
|
||||
true
|
||||
};
|
||||
assert_eq!(super::parts(&p, &groups, &find, &record), vec![vec!["period"], vec!["period"]]);
|
||||
assert_eq!(*seen.borrow(), vec![false]);
|
||||
seen.borrow_mut().clear();
|
||||
let split_near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
|
||||
let b = path.bounding_box();
|
||||
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
|
||||
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
assert_eq!(super::parts(&p, &groups, &split_near_only, &record), vec![vec!["period"], vec!["period"]]);
|
||||
assert_eq!(*seen.borrow(), vec![true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() {
|
||||
use std::collections::HashMap;
|
||||
// Shapes 1 and 2 are two glyphs each, shape 3 one. Line 0 sets one glyph of 1 and one of 2;
|
||||
// line 1 sets the other glyph of 2 and shape 3. Shape 1's other glyph is set nowhere.
|
||||
let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3));
|
||||
let glyphs_of: HashMap<NodeId, usize> = [(a, 2), (b, 2), (c, 1)].into();
|
||||
let lines = vec![vec![a, b], vec![b, c]];
|
||||
let dropped = super::partial_lines(&lines, &glyphs_of);
|
||||
assert!(dropped.contains(&0), "shape 1 is set only in part: {dropped:?}");
|
||||
assert!(dropped.contains(&1), "then shape 2 is too: {dropped:?}");
|
||||
// Every glyph set: nothing goes.
|
||||
let whole = vec![vec![a, b], vec![a, b, c]];
|
||||
assert!(super::partial_lines(&whole, &glyphs_of).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_of_too_many_path_elements_is_not_grouped() {
|
||||
// Two contours side by side, each a polygon of `k` corners.
|
||||
let two = |k: usize| {
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for x in [0.0, 300.0] {
|
||||
for i in 0..k {
|
||||
let a = i as f64 / k as f64 * std::f64::consts::TAU;
|
||||
let q = kurbo::Point::new(x + 100.0 + 100.0 * a.cos(), 100.0 + 100.0 * a.sin());
|
||||
if i == 0 { p.move_to(q) } else { p.line_to(q) }
|
||||
}
|
||||
p.close_path();
|
||||
}
|
||||
p
|
||||
};
|
||||
let mut budget = usize::MAX;
|
||||
assert_eq!(super::split_groups(&two(100), &mut budget).len(), 2, "a small compound is grouped");
|
||||
let big = two(super::MAX_SPLIT_ELEMENTS / 2);
|
||||
assert!(big.elements().len() > super::MAX_SPLIT_ELEMENTS);
|
||||
let mut budget = usize::MAX;
|
||||
assert!(super::split_groups(&big, &mut budget).is_empty(), "past the element limit it is matched whole only");
|
||||
assert_eq!(budget, usize::MAX, "and takes no contours from the budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() {
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_text::retype::MAX_NEAR_KEYS;
|
||||
// A compound path of `n` rectangles side by side, each of another width: every run of up to
|
||||
// three of them has its own near key.
|
||||
let row = |n: usize| {
|
||||
let mut p = kurbo::BezPath::new();
|
||||
for i in 0..n {
|
||||
let x = i as f64 * 100.0;
|
||||
p.extend(kurbo::Rect::new(x, 0.0, x + 10.0 + i as f64 * 0.37, 40.0).path_elements(0.1));
|
||||
}
|
||||
p
|
||||
};
|
||||
// Each shape with its contour groups, as the command looks them up.
|
||||
let with_groups = |shapes: &[kurbo::BezPath]| -> Vec<(kurbo::BezPath, Vec<kurbo::BezPath>)> {
|
||||
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
shapes.iter().map(|p| (p.clone(), super::split_groups(p, &mut budget))).collect()
|
||||
};
|
||||
let keys_of = |shapes: &[(kurbo::BezPath, Vec<kurbo::BezPath>)], tolerance: f64| {
|
||||
super::lookup_keys(shapes.iter().map(|(p, g)| (p, g.as_slice())), tolerance)
|
||||
};
|
||||
let few = with_groups(&[row(20)]);
|
||||
assert_eq!(super::runs(&few[0].1).len(), 20 + 19 + 18, "every run of 1 to 3 groups");
|
||||
let (_, keys) = keys_of(&few, 0.01);
|
||||
assert!(keys.len() > 20, "{}", keys.len());
|
||||
assert!(keys_of(&few, 0.0).1.is_empty(), "no near keys without a tolerance");
|
||||
// Past 256 groups the shape is matched whole only, and past 512 contours its contours are not
|
||||
// grouped at all.
|
||||
assert!(all_groups(&row(300)).is_empty());
|
||||
assert_eq!(all_groups(&row(256)).len(), 256);
|
||||
let mut nested = kurbo::BezPath::new();
|
||||
for i in 0..200 {
|
||||
// Each square with two squares inside it: 200 groups of 3 contours.
|
||||
let x = i as f64 * 100.0;
|
||||
nested.extend(kurbo::Rect::new(x, 0.0, x + 90.0, 90.0).path_elements(0.1));
|
||||
nested.extend(kurbo::Rect::new(x + 10.0, 10.0, x + 40.0, 40.0).path_elements(0.1));
|
||||
nested.extend(kurbo::Rect::new(x + 50.0, 50.0, x + 80.0, 80.0).path_elements(0.1));
|
||||
}
|
||||
assert!(all_groups(&nested).is_empty(), "600 contours");
|
||||
assert_eq!(vectorcraft_text::retype::clusters(&nested).len(), 200, "which would make 200 groups");
|
||||
// Many shapes with many runs each: the near keys stop at the cap.
|
||||
let mut shapes: Vec<kurbo::BezPath> = (0..8).map(|k| kurbo::Affine::scale_non_uniform(1.0, 1.0 + k as f64 * 0.5) * row(200)).collect();
|
||||
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
|
||||
assert_eq!(keys.len(), MAX_NEAR_KEYS);
|
||||
// A plain shape selected after them still gets its own near key: whole shapes come first.
|
||||
let plain = kurbo::Circle::new((0.0, 0.0), 30.0).to_path(0.1);
|
||||
let key = vectorcraft_text::retype::near_key(&plain).unwrap();
|
||||
shapes.push(plain);
|
||||
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
|
||||
assert!(keys.contains(&key));
|
||||
// One command groups at most MAX_SPLIT_TOTAL_CONTOURS contours: the shapes after them are
|
||||
// matched whole only.
|
||||
let full = vec![row(256); super::MAX_SPLIT_TOTAL_CONTOURS / 256 + 1];
|
||||
let split: Vec<usize> = with_groups(&full).iter().map(|(_, g)| g.len()).collect();
|
||||
assert!(split[..split.len() - 1].iter().all(|n| *n == 256), "{split:?}");
|
||||
assert_eq!(split.last(), Some(&0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slight_tracking_without_spaces_is_kept() {
|
||||
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
|
||||
@@ -897,7 +1718,7 @@ fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
|
||||
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.extend(super::new_line(pc, &cands, 0.0));
|
||||
}
|
||||
}
|
||||
lines
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -351,6 +351,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
|
||||
// and a style added on top unlinks them.
|
||||
let groups = super::appearance::stood_for(&own, &ids);
|
||||
// In the contents of a Live Paint group, a face takes the style's fills and an edge its strokes.
|
||||
let (faces, edges) = super::appearance::contents_parts(s, p)?;
|
||||
let part = |id: &NodeId| (faces.contains(id) || edges.contains(id)).then(|| faces.contains(id));
|
||||
if ids.is_empty() {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() {
|
||||
return Err(bad("graphicStyle.apply", "no such objects"));
|
||||
@@ -361,13 +364,20 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "newArt": true }));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit("Apply Graphic Style", |d, _| {
|
||||
// An apply that changes nothing (a fill-only style added to edges only) records no undo step.
|
||||
super::overprint::edit_counted(s, "Apply Graphic Style", |d| {
|
||||
if add {
|
||||
let g = d.graphic_styles[i].clone();
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let ap = g.appearance_on(n).into_owned();
|
||||
n.appearance.items.extend(ap.items);
|
||||
let kind = part(id);
|
||||
let rows: Vec<_> = ap.items.into_iter().filter(|it| kind.is_none_or(|fill| it.is_fill() == fill)).collect();
|
||||
// A face or edge the style adds nothing to keeps its appearance and its link.
|
||||
if kind.is_some() && rows.is_empty() && ap.effects.is_empty() {
|
||||
continue;
|
||||
}
|
||||
n.appearance.items.extend(rows);
|
||||
n.appearance.effects.extend(ap.effects);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
@@ -387,13 +397,18 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut shared = None;
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, &mut shared, chars);
|
||||
// A face or edge that keeps only the rows of its kind no longer has the style's look, so it is not linked.
|
||||
if let (Some(fill), Some(n)) = (part(id), d.node_mut(*id)) {
|
||||
super::appearance::keep_rows_of_kind(n, fill);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
// A label or graph line keeps its new rows for its kind.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
}
|
||||
Ok(())
|
||||
Ok(usize::from(*d != *before))
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
|
||||
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
|
||||
use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size};
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatch::str_list;
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Symbols",
|
||||
["Window", "Symbol Libraries"],
|
||||
None,
|
||||
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
|
||||
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
|
||||
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
|
||||
has_doc,
|
||||
place_from_document
|
||||
),
|
||||
@@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
let parent = if place { st.target_parent()? } else { None };
|
||||
let spot = if place { Some(Placement::of(s)?) } else { None };
|
||||
let mut out = json!({ "library": shown_library_id(s, &info.id) });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
@@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let Some(first) = doc_names.first() else { return Ok(None) };
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(first));
|
||||
let Some(at) = at else { return Ok(None) };
|
||||
let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) };
|
||||
let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first));
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
|
||||
sel.set([id]);
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
@@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
|
||||
let parent = st.target_parent()?;
|
||||
let spot = Placement::of(s)?;
|
||||
let same = uid == st.uid;
|
||||
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
|
||||
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
|
||||
@@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
|
||||
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
|
||||
sel.set([id]);
|
||||
Ok((id, placed))
|
||||
})?;
|
||||
|
||||
Reference in New Issue
Block a user