From 426ea942687c8005305ffaf2fd3defc7c1e97bdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:32:07 -0800 Subject: [PATCH 001/145] Live Paint: bucket paint commands replay from the journal with any tool While the Live Paint Bucket is active, a paint or stroke command that names no objects changes only the colors the bucket paints with. The journal recorded the params as given, and the active tool is not journaled, so a replay with the Selection tool active painted the selection instead. The paint and stroke commands now take defaultsOnly: true, which keeps a command without ids, id or item to the defaults with any tool active. When the bucket routed a command, its journal entry notes defaultsOnly: true, also when the params gave false. library.use (a color, gradient or pattern) and swatch.library.add with apply note it too and pass it to the commands they run. - defaultsOnly is a bool. It is refused with ids, id or item, and in stroke.setAdvanced with brush. - With New Art Has Basic Appearance off, new-art inheritance does not replace the defaults after such a command, unless a later step of a batch selects another first object or changes its appearance. - A preview with defaultsOnly: true, and the one after it, starts from the defaults the interaction began with, and a cancel puts them back. - paint.sampleColor with a stop and defaultsOnly reads the default's gradient. Test: live_paint_bucket_commands_replay_from_the_journal_with_another_tool (engine). Docs: docs/mcp.md, the Live Paint Bucket paragraph; params text of each command. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/gradient.rs | 2 +- crates/engine/src/cmd/gradpresets.rs | 2 +- crates/engine/src/cmd/library.rs | 26 +++-- crates/engine/src/cmd/newart.rs | 43 +++++++- crates/engine/src/cmd/paint.rs | 95 ++++++++++++---- crates/engine/src/cmd/stroke.rs | 13 ++- crates/engine/src/cmd/swatchlib.rs | 6 +- crates/engine/src/cmd/xform.rs | 11 +- crates/engine/src/lib.rs | 5 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/edit.rs | 14 ++- crates/engine/src/session/execute.rs | 11 +- crates/engine/src/tests/build.rs | 145 +++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 8 +- 35 files changed, 367 insertions(+), 57 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..86b73ee159 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -853,7 +853,7 @@ pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. pub use object::{reflect_axis, scale_factors, shear_tangent}; -pub(crate) use paint::LIVE_PAINT_BUCKET; +pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8cf1091492..2b14fdba2d 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index c8eaa07135..89deda43ad 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Apply Gradient Preset", [], None, - "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", + "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", has_doc, apply ), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4d562a76e7..3da204e3ad 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -713,7 +713,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), defaultsOnly?: bool (colors, gradients, patterns: paint only the defaults, as with paint.setFill's; the journal records it for an item used while the Live Paint Bucket is the active tool), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -1186,6 +1186,7 @@ fn item_param<'a>(s: &Session, p: &'a Value, cmd: &str) -> Result<(String, Kind, fn use_item(s: &mut Session, p: &Value) -> Result { const C: &str = "library.use"; + super::switch_or(p, "defaultsOnly", false, C)?; // A replay (the journal) carries what the item was, so it doesn't depend on the library. let recorded = p.get("recorded").cloned(); let (kind, data) = match recorded { @@ -1247,18 +1248,20 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillColor | Kind::StrokeColor => { let stroke = to_stroke(p, kind)?; + let only = super::paint::defaults_only(s, p, C)?; let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?; let set = if stroke { "paint.setStroke" } else { "paint.setFill" }; match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) { - Some(ink) => use_spot(s, set, ink, &color, &data)?, + Some(ink) => use_spot(s, set, ink, &color, &data, only)?, None => { - s.execute(set, &json!({ "color": color }))?; + s.execute(set, &super::paint::with_defaults_only(json!({ "color": color }), only))?; } } Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } })) } Kind::FillGradient | Kind::StrokeGradient => { let stroke = to_stroke(p, kind)?; + let only = super::paint::defaults_only(s, p, C)?; let damaged = || bad(C, "the library item is damaged"); let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?; if !clean_gradient(&mut g) { @@ -1268,12 +1271,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result { for st in &mut g.gradient.stops { st.color = super::paint::new_color(s, &json!({}), st.color); } - super::paint::apply_paint(s, &json!({}), Paint::Gradient(Box::new(g)), !stroke)?; + super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({}), only), Paint::Gradient(Box::new(g)), !stroke)?; Ok(json!({ "kind": if stroke { "strokeGradient" } else { "fillGradient" } })) } Kind::FillPattern | Kind::StrokePattern => { let stroke = to_stroke(p, kind)?; - let pattern = use_pattern(s, &data, stroke)?; + let only = super::paint::defaults_only(s, p, C)?; + let pattern = use_pattern(s, &data, stroke, only)?; Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern })) } Kind::CharStyle | Kind::ParaStyle => { @@ -1304,8 +1308,8 @@ fn use_item(s: &mut Session, p: &Value) -> Result { /// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its /// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of /// that name: the one it has when it is the same colour, else a new one (a name taken by another -/// colour gets a number), one undo step (#5812). -fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> { +/// colour gets a number), one undo step (#5812). With `only`, only the default takes it. +fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value, only: bool) -> Result<()> { const C: &str = "library.use"; let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?; let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0)); @@ -1322,7 +1326,7 @@ fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) if tint < 1.0 { p["tint"] = json!(tint * 100.0); } - s.execute(set, &p)?; + s.execute(set, &super::paint::with_defaults_only(p, only))?; Ok(()) }) } @@ -1340,8 +1344,8 @@ fn to_stroke(p: &Value, kind: Kind) -> Result { /// Add library pattern `data` (`{pattern, data}`) to the document, with its swatch and the /// resources its art uses (the same pattern there already is reused; a name the document gives /// another one gets a number), and paint the selection's fill (`stroke`: stroke) and the default -/// with it, one undo step → the pattern's name in the document. -fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { +/// with it (with `only`, only the default), one undo step → the pattern's name in the document. +fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Result { const C: &str = "library.use"; let damaged = || bad(C, "the library item is damaged"); let bytes = data.get("data").and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or_else(damaged)?; @@ -1378,7 +1382,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { } // The pattern itself, not a swatch of its name (a color swatch can share it); `swatch` keeps // the placement of a pattern the targets already have, as picking its swatch does. - super::paint::apply_paint(s, &json!({ "swatch": target }), paint.clone(), !stroke) + super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({ "swatch": target }), only), paint.clone(), !stroke) })?; Ok(target) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index a42088e7e3..88e025ea41 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -19,6 +19,18 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; +/// The object new art takes its appearance from, with that appearance +/// ([`Session::new_art_source`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct NewArtSource { + doc: u64, + id: vectorcraft_doc::NodeId, + appearance: Appearance, + opacity: f32, + blend: BlendMode, + style: Option, +} + use super::gradient::unplaced; use super::{CommandSpec, Result, Session, always, cmd, switch_or}; @@ -207,16 +219,35 @@ impl Session { /// After each command: with New Art Has Basic Appearance off, new art takes the appearance of /// the first selected object (so the last selection's once nothing is selected). Not while the - /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. + /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor + /// after a command that changed only them (`defaultsOnly`), unless a later step of a batch + /// changed what new art would take ([`Session::new_art_source`]). pub(crate) fn inherit_new_art(&mut self) { if self.prefs.new_art_basic || self.bucket_paints() { return; } - let Some(st) = self.active() else { return }; - let Some(n) = st.selection.subjects().first().and_then(|id| st.doc.node(*id)) else { return }; - let style = super::style::linked_style(&st.doc, n).map(|g| g.name.clone()); - let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend); - self.take_new_art(ap, opacity, blend, style, true); + let Some(source) = self.new_art_source() else { return }; + if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) { + return; + } + let NewArtSource { appearance, opacity, blend, style, .. } = source; + self.take_new_art(appearance, opacity, blend, style, true); + } + + /// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's + /// first selected object, if any. + pub(crate) fn new_art_source(&self) -> Option { + let st = self.active()?; + let id = *st.selection.subjects().first()?; + let n = st.doc.node(id)?; + Some(NewArtSource { + doc: st.uid, + id, + appearance: super::style::captured(n), + opacity: n.opacity, + blend: n.blend, + style: super::style::linked_style(&st.doc, n).map(|g| g.name.clone()), + }) } /// After a command changed the selection, with New Art Has Basic Appearance on: the fill and diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b94a45e4f5..e96ae7ed05 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", has_doc, swap ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", has_doc, default_paint ), @@ -75,11 +75,12 @@ pub fn specs() -> Vec { "None", [], Some("/"), - "{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}", + "{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}", has_doc, - |s, _| { + |s, p| { let f = s.fill_active; - set_paint(s, &json!({"none": true}), f) + let only = switch_or(p, "defaultsOnly", false, "paint.none")?; + set_paint(s, &with_defaults_only(json!({"none": true}), only), f) } ), cmd!( @@ -102,7 +103,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -111,7 +112,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -120,7 +121,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Color", [], Some(","), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -132,7 +133,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Gradient", [], Some("."), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -750,28 +751,84 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) Ok(json!({"objects": ids.iter().collect::>().len()})) } -/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`, -/// `id` or `item`? A fill, -/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults -/// and the selection keeps its paint. -pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { +/// Does `p` name no `ids`, `id` or `item`? +fn names_no_target(p: &Value) -> bool { // A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row. - s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() + ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() } -/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise. -/// A bad `target` or `aligned` is refused first, as it is without the bucket. -pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result> { +/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give +/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight +/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps +/// its paint. +pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { + names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p)) +} + +/// Does `p` give `defaultsOnly: true`? +pub(crate) fn asks_defaults_only(p: &Value) -> bool { + p.get("defaultsOnly") == Some(&Value::Bool(true)) +} + +/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the +/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without +/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`. +/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying +/// it with another tool active changes the defaults only as well. +pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result> { + let only = switch_or(p, "defaultsOnly", false, cmd)?; + if only && !names_no_target(p) { + return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); + } if !for_bucket(s, p) { return Ok(None); } super::appearance::aligned(p, cmd)?; super::appearance::targets_contents(p)?; + if !only { + s.note_journal("defaultsOnly", json!(true)); + } + s.note_defaults_only(); let mut v = p.as_object().cloned().unwrap_or_default(); + v.remove("defaultsOnly"); v.insert("ids".into(), json!([])); Ok(Some(Value::Object(v))) } +/// Whether the paint commands that `cmd` runs with params of its own change only the defaults: +/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]), +/// which the journal entry of `cmd` notes for a replay. +pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result { + if switch_or(p, "defaultsOnly", false, cmd)? { + s.note_defaults_only(); + return Ok(true); + } + let bucket = s.bucket_paints(); + if bucket { + s.note_journal("defaultsOnly", json!(true)); + s.note_defaults_only(); + } + Ok(bucket) +} + +impl Session { + /// Note that the running command changed only the paint defaults, with the appearance new art + /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured + /// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting). + fn note_defaults_only(&mut self) { + let inherits = !self.prefs.new_art_basic && !self.bucket_paints(); + self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); + } +} + +/// `q` with `defaultsOnly: true` when `only` ([`defaults_only`]). +pub(crate) fn with_defaults_only(mut q: Value, only: bool) -> Value { + if only && let Some(o) = q.as_object_mut() { + o.insert("defaultsOnly".into(), json!(true)); + } + q +} + /// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of /// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command /// changes: a given or selected object other than a group or layer (a blend, say) and a compound diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index cb5d1fd374..16be04723a 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Stroke Weight Down", [], Some("Cmd+Alt+,"), - "{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", has_doc, |s, p| stroke_step(s, p, false) ), @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Stroke Options", [], None, - "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", + "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, defaultsOnly?: bool (as stroke.set; refused with brush), target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", has_doc, stroke_advanced ), @@ -618,7 +618,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "nothing to change")); } // As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own. - // A brush still goes to the selection. + // A brush still goes to the selection, and new art has no brush for `defaultsOnly` to set. + if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? { + return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`")); + } let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e4d89b9c13..c36fb6413b 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", has_doc, add ), @@ -1021,6 +1021,7 @@ fn add(s: &mut Session, p: &Value) -> Result { Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))), }; let focus = switch_or(p, "focus", true, C)?; + switch_or(p, "defaultsOnly", false, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the // same pattern) are reused, not added again. The patterns are in a built-in pattern library's @@ -1144,7 +1145,8 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); - s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; + let only = super::paint::defaults_only(s, p, C)?; + s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?; // Adding and applying undo together. squash(s, undo_before, "Add to Swatches"); out["applied"] = json!(name); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index ba8f7e94ab..2ef9edbeb5 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), @@ -523,13 +523,19 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) { return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`")); } + let only = super::switch_or(p, "defaultsOnly", false, C)?; + if only && p.get("ids").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); + } let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?; let (id, mut q) = match p.get("stop") { None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })), Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?; let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?); - let (fill, stroke_paint) = s.proxy_paints(); + // The default's gradient with `defaultsOnly`, as the proxies show it while the Live + // Paint Bucket paints. + let (fill, stroke_paint) = if only { (s.paint.fill.clone(), s.paint.stroke.clone()) } else { s.proxy_paints() }; let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else { return Err(bad(C, "the paint behind the proxy is not a gradient")); }; @@ -542,6 +548,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if let Some(ids) = p.get("ids") { q["ids"] = ids.clone(); } + let q = super::paint::with_defaults_only(q, only); let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; let result = super::run_checked(s, spec, &q)?; if clear_stroke { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..0283829552 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -234,6 +234,11 @@ pub struct Session { /// The running top-level query command changed the selection and is journaled like any other /// command ([`Session::journal_query`]). journal_query: bool, + /// The running top-level command changed only the paint defaults, as the Live Paint Bucket + /// or `defaultsOnly: true` has a paint command do, when new art would have taken this + /// appearance (none: nothing selected): unless a later batch step changes it, the selection's + /// appearance does not replace the defaults afterwards ([`Session::inherit_new_art`]). + pub(crate) defaults_only_ran: Option>, /// From `edit.undoGroup.begin` to `edit.undoGroup.end`: the name of the undo step (`None`: after /// its first edit). Each document opened or created meanwhile opens an undo group of its own /// ([`Session::add_document`]). `None` otherwise. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..7627635797 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -114,6 +114,7 @@ impl Session { journal_note: Default::default(), note_depth: 1, journal_query: false, + defaults_only_ran: None, explicit_undo_group: None, batch_stash: None, batch_steps: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..a6af80f6a7 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -322,7 +322,8 @@ impl Session { return Err(EngineError::Busy); } // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so - // each preview starts from the colors the interaction began with. + // each preview starts from the colors the interaction began with; so does a preview with + // `defaultsOnly: true`, and one after it. let bucket = self.bucket_paints(); let (paint, restore_paint) = { let menu = self.menu.clone(); @@ -339,7 +340,8 @@ impl Session { // the paints the interaction began with. let restore_paint = bucket || cmd == "command.batch" - || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") + || cmd::asks_defaults_only(params) + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; @@ -484,12 +486,16 @@ impl Session { self.decoded_images.empty(); self.pending_paint = None; // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the - // cancel puts back as well. + // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. let bucket = self.bucket_paints(); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) + .filter(|it| { + bucket + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) + || it.color_mode_paints.is_some() + }) .map(|it| it.paint.clone()) { self.paint = paint; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..f2c9c62f42 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -161,6 +161,7 @@ impl Session { self.journal_note.clear(); self.note_depth = 1; self.journal_query = false; + self.defaults_only_ran = None; self.batch_stash = None; self.batch_steps = None; } @@ -263,8 +264,9 @@ impl Session { } /// Record `key: value` in the running top-level command's journal entry (or its interaction's - /// preview, or its step in a batch) unless its params give `key` (a null gives nothing): a value - /// it resolved from the preferences or the clock. + /// preview, or its step in a batch) unless its params give `key` (a null gives nothing, and a + /// noted `defaultsOnly` replaces the params' own): a value it resolved from the preferences or + /// the clock. pub fn note_journal(&mut self, key: &str, value: Value) { if self.depth == self.note_depth { self.journal_note.insert(key.to_string(), value); @@ -359,10 +361,11 @@ impl Session { let mut note = std::mem::take(&mut self.journal_note); match params { // The params' own values win, except a null: it reads as a key left out, so the - // noted value is the one the command resolved. + // noted value is the one the command resolved. A noted `defaultsOnly` wins too: the + // Live Paint Bucket kept the command to the defaults although the params gave `false`. Value::Object(m) if !note.is_empty() => { for (k, v) in m { - if !v.is_null() || !note.contains_key(k) { + if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 316e9b8ffc..dfe61cdd9e 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3331,6 +3331,151 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { assert!(failed.is_empty(), "{failed:#?}"); } +/// A paint or stroke command that the Live Paint Bucket kept to its own colors is journaled with +/// `defaultsOnly: true`, also when its params gave `false`. Replaying the entry with the Selection +/// tool active changes the same defaults and leaves the selection's paint as it was, also with New +/// Art Has Basic Appearance off. Every command that fails is listed. +#[test] +fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { + let blue = Color::from_hex("#0000ff").unwrap(); + // A Live Paint group and a rectangle, both selected, a library with a fill color, a radial + // gradient as the default fill and a 2 pt default weight. + let setup = |s: &mut Session, basic: bool| { + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + let g = live(s); + let art = rect(s, 300.0, 300.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [art.0]})).unwrap(); + let lib = s.execute("library.create", &json!({})).unwrap()["id"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let item = s.execute("library.add", &json!({"library": lib, "kind": "fillColor"})).unwrap()["name"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [g.0, art.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}, "defaultsOnly": true})).unwrap(); + s.paint.stroke_width = 2.0; + s.last_solid = blue; + (g, art, lib, item) + }; + let cases: Vec<(&str, Value)> = vec![ + ("paint.setFill", json!({"color": "#00ffff"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": false})), + ("paint.setStroke", json!({"color": "#00ffff"})), + ("paint.none", json!({})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.lastColor", json!({"stroke": false})), + ("paint.lastGradient", json!({"stroke": true})), + ("paint.invert", json!({"stroke": false})), + ("paint.complement", json!({"stroke": false})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": true})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": false, "stop": 0})), + ("paint.editGradient", json!({"stroke": false, "angle": 45})), + ("gradient.presets.apply", json!({"name": "vignette"})), + ("stroke.set", json!({"weight": 5})), + ("stroke.weightUp", json!({})), + ("stroke.weightDown", json!({})), + ("stroke.setAdvanced", json!({"arrowScale": [150, 200]})), + ("swatch.library.add", json!({"library": "web-safe-216", "names": ["#FF6600"], "apply": "fill"})), + ("library.use", json!({"kind": "fillColor"})), + ]; + let mut failed = vec![]; + for basic in [true, false] { + for (cmd, params) in &cases { + let mut params = params.clone(); + let mut a = session(); + let (_, _, lib, item) = setup(&mut a, basic); + if *cmd == "library.use" { + params["library"] = json!(lib); + params["item"] = json!(item); + } + a.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let start = a.journal.len(); + if let Err(e) = a.execute(cmd, ¶ms) { + failed.push(format!("{cmd} {params} (basic {basic}): {e}")); + continue; + } + let Some((id, recorded)) = a.journal.since(start).last().cloned() else { + failed.push(format!("{cmd} {params} (basic {basic}): not journaled")); + continue; + }; + if recorded.get("defaultsOnly") != Some(&json!(true)) { + failed.push(format!("{cmd} {params} (basic {basic}): the journal entry {recorded} does not keep the change to the defaults")); + } + let mut b = session(); + let (g, art, _, _) = setup(&mut b, basic); + let (group, painted) = (node(&b, g), node(&b, art)); + if let Err(e) = b.replay(&id, &recorded) { + failed.push(format!("{cmd} {params} (basic {basic}): the replay failed: {e}")); + continue; + } + if node(&b, g) != group || node(&b, art) != painted { + failed.push(format!("{cmd} {params} (basic {basic}): the replay painted the selection")); + } + if (&b.paint.fill, &b.paint.stroke, b.paint.stroke_width, b.new_art_stroke()) + != (&a.paint.fill, &a.paint.stroke, a.paint.stroke_width, a.new_art_stroke()) + { + failed.push(format!("{cmd} {params} (basic {basic}): the replay left other defaults")); + } + } + } + assert!(failed.is_empty(), "{failed:#?}"); + // In a batch with New Art Has Basic Appearance off, a selection change after a `defaultsOnly` + // step still gives new art the new selection's appearance; without one, the defaults stay. + let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap()); + let set_cyan = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("command.batch", &json!({"commands": [set_cyan.clone()]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "the defaults keep the batch's fill"); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.key", "params": {"id": art.0}}]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "a new key object leaves the objects new art takes its appearance from"); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.set", "params": {"ids": [art.0]}}]})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "new art takes the newly selected fill"); + // A later step that changes the selected object's appearance gives new art that appearance. + s.execute("command.batch", &json!({"commands": [set_cyan, {"command": "transparency.set", "params": {"opacity": 40, "ids": [art.0]}}]})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert_eq!((&s.paint.fill, s.paint.opacity), (&green, 0.4), "new art takes the selection's new opacity, and its fill"); + // `defaultsOnly: true` with the Selection tool: a canceled preview puts the defaults back, and + // each preview starts from the defaults the interaction began with. + let mut s = session(); + let (g, art, ..) = setup(&mut s, true); + let (group, painted, fill) = (node(&s, g), node(&s, art), s.paint.fill.clone()); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap())); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, fill, "the canceled color is not kept"); + s.begin_interaction("Stroke Weight").unwrap(); + for _ in 0..3 { + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + } + assert_eq!(s.paint.stroke_width, 3.0, "each preview starts from 2 pt"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0); + // A preview with `defaultsOnly: true` after one that set the defaults with the selection + // starts from the defaults the interaction began with too. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(s.paint.stroke_width, 7.0); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the discarded preview's weight is not kept"); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0)); + assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint"); + // `defaultsOnly` is a bool, and names no objects or brush. + let (g, ..) = setup(&mut s, true); + for (cmd, params) in [ + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": 1})), + ("stroke.setAdvanced", json!({"brush": null, "defaultsOnly": true})), + ("stroke.setAdvanced", json!({"brush": "3 pt. Round", "defaultsOnly": true})), + ] { + assert!(s.execute(cmd, ¶ms).is_err(), "{cmd} {params}"); + } +} + /// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, /// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient /// fitted to each object has no aspect of its own. Named objects still take the aspect. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9ef6f066e6..2a2cd7273e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9022,6 +9022,8 @@ breakText Glyphs Glyfy @msg `dataBase64` is larger than the module limit `dataBase64` je větší než limit modulu @msg `dataBase64` is not valid base64 `dataBase64` není platný base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` nelze kombinovat s `ids`, `reverse` ani `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` nelze kombinovat s `ids`, `id` ani `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` nelze kombinovat s `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` a `childLimit` omezují souhrn: předejte `summary: true` @msg `design` is a design name, or null for plain columns `design` je název návrhu, nebo null pro obyčejné sloupce @msg `design` is a design name, or null for the default marker `design` je název návrhu, nebo null pro výchozí značku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0d8b14dba4..39ffd4b602 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1136,6 +1136,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `dataBase64` is larger than the module limit `dataBase64` er større end modulgrænsen @msg `dataBase64` is not valid base64 `dataBase64` er ikke gyldig base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan ikke kombineres med `ids`, `reverse` eller `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan ikke kombineres med `ids`, `id` eller `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan ikke kombineres med `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` og `childLimit` opdeler oversigten: angiv `summary: true` @msg `design` is a design name, or null for plain columns `design` er et designnavn eller null for almindelige søjler @msg `design` is a design name, or null for the default marker `design` er et designnavn eller null for standardmarkøren diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bd04b8cc19..59b4ec7966 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8868,6 +8868,8 @@ breakText Glyphs Glyphen @msg `dataBase64` is larger than the module limit `dataBase64` ist größer als die Modulgrenze @msg `dataBase64` is not valid base64 `dataBase64` ist kein gültiges Base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kann nicht mit `ids`, `reverse` oder `append` kombiniert werden +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kann nicht mit `ids`, `id` oder `item` kombiniert werden +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kann nicht mit `brush` kombiniert werden @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` und `childLimit` begrenzen die Zusammenfassung: Übergeben Sie `summary: true` @msg `design` is a design name, or null for plain columns `design` ist ein Designname oder null für einfache Säulen @msg `design` is a design name, or null for the default marker `design` ist ein Designname oder null für die Standardmarkierung diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 016f297b3b..d6f3c2226d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -9311,6 +9311,8 @@ breakText Glyphs Glifos @msg `dataBase64` is larger than the module limit `dataBase64` supera el límite de módulos @msg `dataBase64` is not valid base64 `dataBase64` no es base64 válido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` no se puede combinar con `ids`, `reverse` ni `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` no se puede combinar con `ids`, `id` ni `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` no se puede combinar con `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` y `childLimit` recortan el resumen: pasa `summary: true` @msg `design` is a design name, or null for plain columns `design` es el nombre de un diseño, o null para columnas simples @msg `design` is a design name, or null for the default marker `design` es el nombre de un diseño, o null para el marcador predeterminado diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ce31cfc06..48b1e5b5c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8888,6 +8888,8 @@ breakText Glyphs Glyphes @msg `dataBase64` is larger than the module limit `dataBase64` dépasse la limite des modules @msg `dataBase64` is not valid base64 `dataBase64` n’est pas du base64 valide @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` ne peut pas être combiné avec `ids`, `reverse` ou `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` ne peut pas être combiné avec `ids`, `id` ou `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` ne peut pas être combiné avec `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` et `childLimit` découpent le résumé : passez `summary: true` @msg `design` is a design name, or null for plain columns `design` est un nom de motif, ou null pour des colonnes simples @msg `design` is a design name, or null for the default marker `design` est un nom de motif, ou null pour le repère par défaut diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c8852f1ddd..bbd26b9ca4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7008,6 +7008,8 @@ arrowhead Feather पंख @msg `dataBase64` is not valid base64 `dataBase64` मान्य नहीं है base64 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` होना चाहिए `fileNumber`, `fileDataSetName` या `dataSetName` @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` को `ids`, `reverse` या `append` के साथ उपयोग नहीं कर सकते +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` को `ids`, `id` या `item` के साथ उपयोग नहीं कर सकते +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` को `brush` के साथ उपयोग नहीं कर सकते @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` और `childLimit` सारांश के हिस्से चुनते हैं: `summary: true` दें @msg `design` is a design name, or null for plain columns `design` एक डिजाइन नाम है, या सादे स्तंभों के लिए null है @msg `design` is a design name, or null for the default marker `design` एक डिजाइन नाम है, या डिफ़ॉल्ट मार्कर के लिए null है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 54ff192eed..e3dae2312f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8893,6 +8893,8 @@ breakText Glyphs Glifák @msg `dataBase64` is larger than the module limit `dataBase64`: nagyobb a modulok méretkorlátjánál @msg `dataBase64` is not valid base64 `dataBase64`: nem érvényes base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`: nem használható együtt ezekkel: `ids`, `reverse`, `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`: nem használható együtt ezekkel: `ids`, `id`, `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`: nem használható együtt ezzel: `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` és `childLimit`: az összegzést szűkítik; add meg ezt: `summary: true` @msg `design` is a design name, or null for plain columns `design`: diagramminta neve, vagy null az egyszerű oszlopokhoz @msg `design` is a design name, or null for the default marker `design`: diagramminta neve, vagy null az alapértelmezett jelölőhöz diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 190b136a06..c26a6120b8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8921,6 +8921,8 @@ breakText Glyphs Glifi @msg `dataBase64` is larger than the module limit `dataBase64` supera il limite del modulo @msg `dataBase64` is not valid base64 `dataBase64` non è un base64 valido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` non può essere combinato con `ids`, `reverse` o `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` non può essere combinato con `ids`, `id` o `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` non può essere combinato con `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` e `childLimit` riducono il riepilogo: passa `summary: true` @msg `design` is a design name, or null for plain columns `design` è il nome di un design, o null per colonne semplici @msg `design` is a design name, or null for the default marker `design` è il nome di un design, o null per il marcatore predefinito diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 665e74c319..7a8823f851 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7738,6 +7738,8 @@ axis Y Axis Y 軸 @msg `dataBase64` is larger than the module limit `dataBase64` がモジュールの上限を超えています @msg `dataBase64` is not valid base64 `dataBase64` が有効な base64 ではありません @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` は `ids`、`reverse`、`append` と同時に使用できません +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` は `ids`、`id`、`item` と同時に使用できません +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` は `brush` と同時に使用できません @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` と `childLimit` はサマリーを絞り込みます: `summary: true` を指定してください @msg `design` is a design name, or null for plain columns `design` にはデザイン名を指定します。通常の棒にするには null を指定します @msg `design` is a design name, or null for the default marker `design` にはデザイン名を指定します。初期設定のマーカーにするには null を指定します diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d3ea2160c1..38eea76371 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -217,6 +217,8 @@ @msg `dataBase64` is larger than the module limit `dataBase64` მოდულის ლიმიტზე დიდია @msg `dataBase64` is not valid base64 `dataBase64` სწორი base64 არ არის @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` ვერ გამოიყენება `ids`-თან, `reverse`-თან ან `append`-თან ერთად +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` ვერ გამოიყენება `ids`-თან, `id`-თან ან `item`-თან ერთად +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` ვერ გამოიყენება `brush`-თან ერთად @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` და `childLimit` შეჯამებას ზღუდავს: გადაეცით `summary: true` @msg `design` is a design name, or null for plain columns `design` არის დიზაინის სახელი, ან null — ჩვეულებრივი სვეტებისთვის @msg `design` is a design name, or null for the default marker `design` არის დიზაინის სახელი, ან null — ნაგულისხმევი მარკერისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0c2642f758..15597a0192 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8661,6 +8661,8 @@ breakText Glyphs 글리프 @msg `dataBase64` is larger than the module limit `dataBase64`이(가) 모듈 한도보다 큽니다 @msg `dataBase64` is not valid base64 `dataBase64`이(가) 올바른 base64가 아닙니다 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`은(는) `ids`, `reverse` 또는 `append`와 함께 쓸 수 없습니다 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`은(는) `ids`, `id` 또는 `item`과 함께 쓸 수 없습니다 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`은(는) `brush`와 함께 쓸 수 없습니다 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth`와 `childLimit`은 요약을 잘라 냅니다: `summary: true`를 전달하세요 @msg `design` is a design name, or null for plain columns `design`은(는) 디자인 이름이며, 일반 막대에는 null입니다 @msg `design` is a design name, or null for the default marker `design`은(는) 디자인 이름이며, 기본 마커에는 null입니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c1f7e36426..2492a94d48 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6531,6 +6531,8 @@ imageTrace Outline Contour @msg `dataBase64` is larger than the module limit `dataBase64` is groter dan de modulelimiet @msg `dataBase64` is not valid base64 `dataBase64` is geen geldige base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan niet worden gecombineerd met `ids`, `reverse` of `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan niet worden gecombineerd met `ids`, `id` of `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan niet worden gecombineerd met `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` en `childLimit` beperken de samenvatting: geef `summary: true` op @msg `design` is a design name, or null for plain columns `design` is de naam van een ontwerp, of null voor gewone kolommen @msg `design` is a design name, or null for the default marker `design` is de naam van een ontwerp, of null voor de standaardmarkering diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5808ddb8c2..2258f53359 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9129,6 +9129,8 @@ breakText Glyphs Glify @msg `dataBase64` is larger than the module limit `dataBase64` przekracza limit rozmiaru modułu @msg `dataBase64` is not valid base64 `dataBase64` nie jest prawidłowym kodem base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` nie można łączyć z `ids`, `reverse` ani `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` nie można łączyć z `ids`, `id` ani `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` nie można łączyć z `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` i `childLimit` ograniczają podsumowanie: przekaż `summary: true` @msg `design` is a design name, or null for plain columns `design` to nazwa wzoru albo null dla zwykłych kolumn @msg `design` is a design name, or null for the default marker `design` to nazwa wzoru albo null dla domyślnego znacznika diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2204a2bdc1..2a9c0b1d75 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9084,6 +9084,8 @@ swatch Yellow Green Verde-amarelado @msg `dataBase64` is larger than the module limit `dataBase64` excede o limite do módulo @msg `dataBase64` is not valid base64 `dataBase64` não é base64 válido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` não pode ser combinado com `ids`, `reverse` ou `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` não pode ser combinado com `ids`, `id` ou `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` não pode ser combinado com `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` e `childLimit` recortam o resumo: passe `summary: true` @msg `design` is a design name, or null for plain columns `design` é o nome de um projeto, ou null para colunas simples @msg `design` is a design name, or null for the default marker `design` é o nome de um projeto, ou null para o marcador padrão diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b3ca5d5d93..dbd54f0746 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9007,6 +9007,8 @@ shape Open Открытый @msg `dataBase64` is larger than the module limit `dataBase64` больше ограничения для модуля @msg `dataBase64` is not valid base64 `dataBase64` не является допустимым base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` нельзя сочетать с `ids`, `reverse` или `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` нельзя сочетать с `ids`, `id` или `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` нельзя сочетать с `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` и `childLimit` ограничивают сводку: передайте `summary: true` @msg `design` is a design name, or null for plain columns `design` — имя дизайна или null для обычных столбцов @msg `design` is a design name, or null for the default marker `design` — имя дизайна или null для маркера по умолчанию diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 94a83ef975..bdab8aa5fe 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8864,6 +8864,8 @@ digits Hindi Hindi @msg `dataBase64` is larger than the module limit `dataBase64` är större än modulgränsen @msg `dataBase64` is not valid base64 `dataBase64` är inte giltig base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan inte kombineras med `ids`, `reverse` eller `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan inte kombineras med `ids`, `id` eller `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan inte kombineras med `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` och `childLimit` begränsar sammanfattningen: ange `summary: true` @msg `design` is a design name, or null for plain columns `design` är ett designnamn, eller null för vanliga kolumner @msg `design` is a design name, or null for the default marker `design` är ett designnamn, eller null för standardmarkören diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2fcd6d3b54..25f69773e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8119,6 +8119,8 @@ axis Y Axis Y ekseni @msg `dataBase64` is larger than the module limit `dataBase64` modül sınırından büyük @msg `dataBase64` is not valid base64 `dataBase64` geçerli bir base64 değil @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`; `ids`, `reverse` veya `append` ile birleştirilemez +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`; `ids`, `id` veya `item` ile birleştirilemez +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`; `brush` ile birleştirilemez @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` ve `childLimit` özeti dilimler: `summary: true` verin @msg `design` is a design name, or null for plain columns `design` bir tasarım adıdır veya düz sütunlar için null olur @msg `design` is a design name, or null for the default marker `design` bir tasarım adıdır veya varsayılan işaretçi için null olur diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 49f8383268..464b9773f1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8670,6 +8670,8 @@ breakText Glyphs Гліфи @msg `dataBase64` is larger than the module limit `dataBase64` перевищує обмеження модуля @msg `dataBase64` is not valid base64 `dataBase64` не є припустимим base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` не можна поєднувати з `ids`, `reverse` або `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` не можна поєднувати з `ids`, `id` або `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` не можна поєднувати з `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` і `childLimit` обмежують зведення: передайте `summary: true` @msg `design` is a design name, or null for plain columns `design` — це назва дизайну або null для звичайних стовпців @msg `design` is a design name, or null for the default marker `design` — це назва дизайну або null для стандартного маркера diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f51baaa7e7..1979424953 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9140,6 +9140,8 @@ breakText Glyphs 字形 @msg `dataBase64` is larger than the module limit `dataBase64` 超过了模块大小上限 @msg `dataBase64` is not valid base64 `dataBase64` 不是有效的 base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` 不能与 `ids`、`reverse` 或 `append` 同时使用 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` 不能与 `ids`、`id` 或 `item` 同时使用 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` 不能与 `brush` 同时使用 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` 和 `childLimit` 用于截取摘要:请传入 `summary: true` @msg `design` is a design name, or null for plain columns `design` 是设计名称,或用 null 表示普通柱形 @msg `design` is a design name, or null for the default marker `design` 是设计名称,或用 null 表示默认标记 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d794ea15d9..8be1458d9b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9076,6 +9076,8 @@ breakText Glyphs 字符 @msg `dataBase64` is larger than the module limit `dataBase64` 大於模組上限 @msg `dataBase64` is not valid base64 `dataBase64` 不是有效的 base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` 不能與 `ids`、`reverse` 或 `append` 一起使用 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` 不能與 `ids`、`id` 或 `item` 一起使用 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` 不能與 `brush` 一起使用 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` 和 `childLimit` 用於裁切摘要:請傳入 `summary: true` @msg `design` is a design name, or null for plain columns `design` 是設計名稱,或以 null 表示一般直條 @msg `design` is a design name, or null for the default marker `design` 是設計名稱,或以 null 表示預設標記 diff --git a/docs/mcp.md b/docs/mcp.md index ae119cc4b1..afea44461b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4839,7 +4839,13 @@ already walks Image Trace. Short agent entry points: `paint.invert`, `paint.complement`, `paint.sampleColor`, `gradient.presets.apply`, a swatch or the Color Picker), and `paint.swap` or `paint.default` without `ids` or `id`, becomes the color the bucket paints with, and a stroke weight (`stroke.set`, `stroke.weightUp`, `stroke.weightDown`) becomes the weight it paints with. The selection keeps its - paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The Stroke panel's other options + paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The journal records each of these + commands with `defaultsOnly: true`, and it records `library.use` with a color, gradient or pattern and + `swatch.library.add` with `apply` the same way. A replay of the entry, or the same params sent with any tool active, changes + only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or `item`, and in + `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is + journaled as `true`. A preview with `defaultsOnly: true` starts from the defaults the interaction began with, and + canceling the interaction puts them back. The Stroke panel's other options (`stroke.set`, `stroke.setAdvanced` without `brush`) change the stroke for new art and leave the selection as it is; the bucket takes only the color and weight of that stroke. A stop selected on the bucket's gradient (`gradient.selectStop`) is deselected when another tool is chosen, when the first selected object changes, when an From c609eb49af15e2116176982d3221474f89034dc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:59:44 -0800 Subject: [PATCH 002/145] Live Paint: canceling restores the defaults after a later ordinary preview An interaction that previewed a command with defaultsOnly: true keeps putting the defaults it began with back on every later preview and on cancel, also when the latest preview gives no defaultsOnly. docs/mcp.md says that library.use keeps item as the library item. --- crates/engine/src/interaction.rs | 3 +++ crates/engine/src/session/edit.rs | 5 ++++- crates/engine/src/tests/build.rs | 12 ++++++++++++ docs/mcp.md | 6 +++--- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..efadf86ec3 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,9 @@ pub struct Interaction { pub preview: Option<(String, Value)>, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put + /// `paint` back, whichever preview is the latest. + pub(crate) used_defaults_only: bool, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index a6af80f6a7..4a7b9bc1c2 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -301,6 +301,7 @@ impl Session { selection: Arc::new(st.selection.clone()), preview: None, paint, + used_defaults_only: false, preview_paint: None, color_mode_paints: None, deferred_color_mode: None, @@ -338,9 +339,10 @@ impl Session { st.doc = it.doc.clone(); // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. + it.used_defaults_only |= cmd::asks_defaults_only(params); let restore_paint = bucket || cmd == "command.batch" - || cmd::asks_defaults_only(params) + || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); @@ -493,6 +495,7 @@ impl Session { .and_then(|st| st.interaction.as_ref()) .filter(|it| { bucket + || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() }) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index dfe61cdd9e..39618bf201 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3461,9 +3461,21 @@ fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { s.cancel_interaction().unwrap(); assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0)); assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint"); + // A later preview without `defaultsOnly` leaves the interaction one that changed the defaults: + // canceling puts them back. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept"); // `defaultsOnly` is a bool, and names no objects or brush. let (g, ..) = setup(&mut s, true); for (cmd, params) in [ + ("paint.none", json!({"defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": true, "id": g.0})), + ("paint.none", json!({"defaultsOnly": true, "item": null})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "id": g.0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "item": null})), ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})), ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), ("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})), diff --git a/docs/mcp.md b/docs/mcp.md index afea44461b..51edbf0d2a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4842,10 +4842,10 @@ already walks Image Trace. Short agent entry points: paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The journal records each of these commands with `defaultsOnly: true`, and it records `library.use` with a color, gradient or pattern and `swatch.library.add` with `apply` the same way. A replay of the entry, or the same params sent with any tool active, changes - only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or `item`, and in - `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is + only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or an appearance `item` (`library.use` takes + `item` as the library item to apply, which stays valid), and in `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is journaled as `true`. A preview with `defaultsOnly: true` starts from the defaults the interaction began with, and - canceling the interaction puts them back. The Stroke panel's other options + canceling the interaction puts them back, also after a later preview without `defaultsOnly`. The Stroke panel's other options (`stroke.set`, `stroke.setAdvanced` without `brush`) change the stroke for new art and leave the selection as it is; the bucket takes only the color and weight of that stroke. A stop selected on the bucket's gradient (`gradient.selectStop`) is deselected when another tool is chosen, when the first selected object changes, when an From e0629ad03a3bd999e61c12042a4d2f78f9d404ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:44:45 -0800 Subject: [PATCH 003/145] Live Paint: canceling keeps the defaults a defaultsOnly preview began with With New Art Has Basic Appearance off and an object selected, canceling an interaction that had previewed a command with defaultsOnly: true replaced the restored defaults with the selection's appearance. Cancel now skips the new-art inheritance for such an interaction. --- crates/engine/src/session/edit.rs | 11 +++++++++-- crates/engine/src/tests/build.rs | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4a7b9bc1c2..7c52f211ff 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -373,6 +373,8 @@ impl Session { let outer = std::mem::replace(&mut self.previewing, true); let r = self.execute(cmd, params); self.previewing = outer; + // A step inside a batch that changed only the defaults counts as well. + let ran_defaults_only = self.defaults_only_ran.is_some(); if let Some(paint) = color_mode_paint { self.paint = paint; } @@ -380,6 +382,7 @@ impl Session { let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); @@ -490,6 +493,7 @@ impl Session { // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. let bucket = self.bucket_paints(); + let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -511,8 +515,11 @@ impl Session { // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as - // the document has it again, not as a preview left it. - self.inherit_new_art(); + // the document has it again, not as a preview left it. An interaction that changed only the + // defaults (`defaultsOnly: true`) leaves the defaults it began with. + if !used_defaults_only { + self.inherit_new_art(); + } Ok(()) } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 39618bf201..8a214f5522 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3468,6 +3468,25 @@ fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { s.preview("stroke.set", &json!({"weight": 7})).unwrap(); s.cancel_interaction().unwrap(); assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept"); + // With New Art Has Basic Appearance off and an object selected, canceling such an interaction + // keeps the defaults it began with, not the selection's appearance. + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + let (red, selected) = (s.paint.fill.clone(), node(&s, art)); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#00ffff", "defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 2.0), "the defaults the interaction began with stay"); + assert_eq!(node(&s, art), selected, "the selection keeps its paint"); + // The same when the defaults-only step was inside a batch that a later preview replaced. + s.begin_interaction("Fill Color").unwrap(); + let step = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + s.preview("command.batch", &json!({"commands": [step]})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#ff0000").unwrap()), "a batch's defaults-only step is put back"); // `defaultsOnly` is a bool, and names no objects or brush. let (g, ..) = setup(&mut s, true); for (cmd, params) in [ From 8b304e232a50a928844a6c9f02b71ed6213fcbb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:51:18 -0800 Subject: [PATCH 004/145] Retype: no retyped line starts with a combining mark A drawn bar, dot or ring can be the same shape as a combining mark in one of the loaded fonts, and Retype turned it into point text that held only that mark. On Linux, once other tests had loaded the system fonts, the 80x40 rectangle in a_drawn_shape_is_reported_and_left_alone matched U+05BD in DejaVu Sans Bold, so that test failed in full runs of the engine's tests. - When a shape would start a line and its first 16 matched glyphs include another character's glyph, in its own font or another loaded one, it starts the line as that character. A line's first shape is not turned into a mark to take the glyph after it. - When all of them are marks, the shape stays an outline and is listed in unmatched, and the glyph after it starts the line. A lone one-contour glyph after it (a dot after a bar) is judged alone, as on its own. - A mark left at the start of a part split off where type stops drawing the outlines in place becomes the other character its shape matches, on a line of its own, or else stays an outline. The glyphs after it are measured for tracking again without the mark's gap. - A mark that follows another glyph on its line is retyped with it, as before. - type.retypeFonts does not list a font whose glyphs match the shapes only as combining marks. Docs: docs/mcp.md and the params text of type.retype and type.retypeFonts. --- crates/engine/src/cmd/retype.rs | 90 ++++++++++++++-- crates/engine/src/cmd/retype_fonts.rs | 24 +++-- crates/engine/src/cmd/retype_fonts_tests.rs | 15 +++ crates/engine/src/cmd/retype_tests.rs | 109 +++++++++++++++++++- crates/text/src/retype.rs | 19 ++++ crates/text/src/test_fonts.rs | 9 ++ docs/mcp.md | 10 +- 7 files changed, 259 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 0e31d5632a..51d9398870 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "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…]} 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, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", has_selected_path, retype )] @@ -613,8 +613,14 @@ fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option, system_layout: bool, unmatched: &mut Vec) -> Vec { +fn verified( + lines: Vec, + system_layout: bool, + spacing: &std::collections::HashMap, + unmatched: &mut Vec, +) -> Vec { // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); // Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot @@ -630,6 +636,40 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) let mut out = vec![]; while let Some(l) = todo.pop_front() { let n = l.pieces.len(); + // A combining mark goes with the character before it: a mark that a split left first on + // a line becomes the other character its shape is (`spacing`), alone on a line, or else + // stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no + // line with one). + if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + let first = l.pieces.first().copied(); + let alone = first.and_then(|id| spacing.get(&id).map(|m| reposed(&l, id, m))); + if alone.is_none() { + unmatched.extend(first); + } + if n > 1 { + // The tracking was measured with the mark's gap in it: the rest is measured again + // without it, from the same budgets as the rest after a split. + let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6); + let rest = if measurable { + remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6)); + track_budget = track_budget.saturating_sub(n - 1); + l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) + } else if l.tracking == 0.0 { + l.part(1, n) + } else { + l.respaced(1, n, 0.0) + }; + match rest { + Some(rest) => todo.push_front(rest), + None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()), + } + } + // Checked before the rest, so the lines keep the outlines' order. + if let Some(alone) = alone { + todo.push_front(alone); + } + continue; + } // The line's type is laid out over a window from its start that doubles while the type // draws the window's glyphs as the outlines do, so finding where it stops costs about // twice the glyphs before that point, not the whole rest of the line each time. @@ -1024,6 +1064,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { .iter() .flat_map(|c| c.poses()) .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + // No line starts with a combining mark (see [`new_line`]). + .filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch)) .collect(); for fp in others { let mut turned = reposed(l, id, &fp); @@ -1057,9 +1099,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { } } -/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a +/// combining mark (none: `None`). No line starts with a mark: a mark combines with the character +/// before it. fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { - let m = cands.first()?; + let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?; let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { pieces: vec![pc.id], @@ -1141,6 +1185,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; + let mut spacing: std::collections::HashMap = std::collections::HashMap::new(); for (pc, ms) in pieces.iter().zip(&found) { if pc.after_barrier { open = false; @@ -1158,8 +1203,41 @@ fn retype(s: &mut Session, p: &Value) -> Result { Some(l) if open => join(l, pc, &cands), _ => false, }; + // A shape that joined a line, perhaps as a mark, that is also another character, in that + // face or else in the face most shapes fit of those it is a character in: the character, + // should a split leave the shape first on a line ([`verified`]). + let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch); + if joined + && cands.iter().any(is_mark) + && let Some(m) = cands.iter().find(|m| !is_mark(m)).or_else(|| { + ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m) + }) + { + spacing.insert(pc.id, m.clone()); + } if !joined { - lines.extend(new_line(pc, &cands)); + // A shape that is only marks in that face may be another character in a face + // fewer shapes fit: it starts its line in the one of those most shapes fit. + let started = new_line(pc, &cands).or_else(|| { + let face = ms + .iter() + .enumerate() + .filter(|(_, m)| !vectorcraft_text::retype::is_combining_mark(m.ch)) + .max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))) + .map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + new_line(pc, &cands) + }); + match started { + Some(l) => lines.push(l), + // Only combining marks: no line starts with one, so the shape stays an outline + // and the glyph after it starts the next line. + None => { + unmatched.push(pc.id); + open = false; + continue; + } + } } open = true; } @@ -1176,7 +1254,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); share_tracking(&mut lines, system_layout); - let mut lines = verified(lines, system_layout, &mut unmatched); + let mut lines = verified(lines, system_layout, &spacing, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dc9a413d5f..a901ac7e12 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", has_selected_path, retype_fonts )] @@ -44,6 +44,8 @@ struct Ranked { matched: usize, /// The sum of those matches' leftover distances. residual: f64, + /// Whether some shape matched a glyph of it that is not a combining mark. + character: bool, } impl Ranked { @@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { for pc in &pieces { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64)> = vec![]; + let mut best: Vec<(Arc, f64, bool)> = vec![]; for m in index.all_matches(&pc.path) { - match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) { - Some(b) => b.1 = b.1.min(m.residual), - None => best.push((m.face, m.residual)), + let character = !vectorcraft_text::retype::is_combining_mark(m.ch); + match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { + Some(b) => { + b.1 = b.1.min(m.residual); + b.2 |= character; + } + None => best.push((m.face, m.residual, character)), } } - for (face, residual) in best { + for (face, residual, character) in best { match ranked.iter_mut().find(|r| r.face.id() == face.id()) { Some(r) => { r.matched += 1; r.residual += residual; + r.character |= character; } - None => ranked.push(Ranked { face, matched: 1, residual }), + None => ranked.push(Ranked { face, matched: 1, residual, character }), } } } + // A font whose glyphs match the shapes only as combining marks would retype none of them, as + // type.retype starts no line with a mark: it is not listed. + ranked.retain(|r| r.character); ranked.sort_by(|a, b| { b.matched .cmp(&a.matched) diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index d7e675f503..ac7723d82a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() { assert!(s.execute("type.retypeFonts", &json!({})).is_err()); } +#[test] +fn a_font_that_matches_only_combining_marks_is_not_listed() { + let mut s = session(); + // A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + // After a base, the mark counts with it. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}"); +} + #[test] fn shapes_past_the_limits_are_reported_as_left_out() { let mut s = session(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 80361f1e0a..d77fe00774 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -91,6 +91,109 @@ fn a_drawn_shape_is_reported_and_left_alone() { assert!(s.doc().unwrap().doc == before); } +#[test] +fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { + use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font}; + // The comma below of Source Sans 3 is only marks there, and a modifier letter in this face. + vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap()); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); + // After a base, it joins the line as the mark; moved off its base, the split leaves it first, + // and it becomes the other face's character there. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}"); + assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); +} + +#[test] +fn a_combining_mark_starts_no_line() { + // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as + // the character. + let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}"); + // A glyph after it does not turn it back into the mark (diaeresis below, diaeresis). + let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}"); + // First on a line, the mark stays an outline and the glyphs after it are retyped. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + assert_eq!(r["unmatched"], json!([mark])); + // After a base, the mark is retyped with it. + let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}"); + // Moved off its base, the mark is where the line splits, and the part after the split does + // not start with it either. + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); + // A mark that is also another character (dot below, dot above) becomes that character there. + let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}"); + // Tracked, the part after the mark keeps the tracking its own glyphs are spaced by. + let id = s + .execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); + assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); + // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and + // beside other shapes it stays an outline too. + let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mut pair: Vec = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect(); + pair.sort_unstable(); + let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + assert_eq!(left, pair, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); @@ -922,7 +1025,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() { l.matches[bad].gid = other; let bad_id = l.pieces[bad]; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched, vec![bad_id], "{bad}"); let last = out.last().unwrap(); assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -974,7 +1077,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() { assert_eq!(l.tracking, 8000.0); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -996,7 +1099,7 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { m.gid += 1; } let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 5); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7c7be71d6..083aef7d48 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -332,6 +332,13 @@ fn is_shape_symbol(c: char) -> bool { ) } +/// Whether `c` is a combining mark (general category Mn, Mc or Me). A mark combines with the +/// character before it, so no retyped line starts with one. +pub fn is_combining_mark(c: char) -> bool { + use unicode_general_category::{GeneralCategory, get_general_category}; + matches!(get_general_category(c), GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark) +} + /// Complex multiply: `z` (a scaled turn) applied to `p`. fn mul(z: (f64, f64), p: Point) -> Point { Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) @@ -780,6 +787,18 @@ mod tests { } } + #[test] + fn combining_marks_are_told_from_spacing_characters() { + // Nonspacing (Mn), spacing (Mc) and enclosing (Me) marks. + for c in ['\u{0312}', '\u{05BD}', '\u{0903}', '\u{20DD}'] { + assert!(is_combining_mark(c), "{c:?}"); + } + // Spacing forms of the same accents are characters of their own. + for c in ['a', '\u{00A8}', '\u{02DC}', '\u{00AF}', '-'] { + assert!(!is_combining_mark(c), "{c:?}"); + } + } + #[test] fn degenerate_and_hostile_shapes_give_none() { assert!(signature(&BezPath::new()).is_none()); diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..1cbc4b6e77 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1518,6 +1518,15 @@ pub fn private_use_font() -> Option> { remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) } +/// The family of [`spacing_comma_font`]. +pub const SPACING_COMMA_FAMILY: &str = "Spacingcomma Sans"; + +/// A face that maps only U+02BB (a modifier letter) to the bundled Source Sans 3 outline of U+0326 +/// (a combining mark), for tests of a shape that is a mark in one face and a character in another. +pub fn spacing_comma_font() -> Option> { + remapped_source_sans(SPACING_COMMA_FAMILY, "SpacingcommaSans-Regular", &[('\u{2BB}', '\u{326}')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..9cc1c68b43 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12592,6 +12592,13 @@ per glyph. A line splits where its type stops drawing the outlines in place, and tracking their own gaps give. These rules are VectorCraft's own. Each entry of the result's `fonts` list has `tracking`. +No retyped line starts with a combining mark (Unicode general category Mn, Mc or Me). When a shape would start a line +and the first 16 glyphs it matches include another character's glyph, it starts the line as that character. When they +are all marks, the shape stays an outline and is listed in `unmatched`, and the glyph after it starts the line. The +same holds for a mark at the start of a part that a split leaves: it becomes that other character on a line of its +own, or stays an outline. A mark that follows another glyph on its line is retyped with +that glyph. This rule is VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` @@ -12627,7 +12634,8 @@ name. `count` is a whole number from 1 to 96 (default 10); any other value is an `{fonts: [{family, style, matched}], shapes, more, truncated}`: `matched` is the number of shapes the font matches, `shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and `truncated` is true when shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as outlines because of -their paint still count. The command does not change the document and records no undo step. With no path or compound +their paint still count. A font whose glyphs match the shapes only as combining marks is not listed. The +command does not change the document and records no undo step. With no path or compound path selected it is an error. Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to From fd33180c84423597002fb801b44ff4ed5b7d5040 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:50:34 -0800 Subject: [PATCH 005/145] Live Corners: a Selection tool double-click on a corner widget shows the Transform panel With the Selection tool, a double-click on a visible corner widget of a selected live rectangle or polygon now shows and selects the Transform panel, where the shape's corner radius fields are, as the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools already do. It used to open the Corners dialog. The tool, the selection, the document and the undo history stay as they were. Direct Selection's double-click still opens Corners. Docs: docs/mcp.md (Live Corners), the ui.corners params text, docs/ui-parity.md and docs/target-app-parity.md. Part of #1232 --- crates/engine/src/tests/livecorners.rs | 33 +++++++++++++++++++++++++ crates/mcp/src/tests/shapewidgets.rs | 9 +++++-- crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/corners.rs | 6 +++-- crates/tools/src/corners/tests.rs | 15 +++++++++-- crates/tools/src/select.rs | 9 +++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 8 ++++-- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 10 files changed, 74 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 288f0236d1..96a2aedff8 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -1002,3 +1002,36 @@ fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_pa assert!(st.interaction.is_none()); assert_eq!(s.tool_id(), "rectangle"); } + +/// A double-click on a corner widget of a selected live rectangle with the Selection tool asks +/// the frontend for the Transform panel, and leaves the document, its undo history, the +/// selection and the tool as they were; with Direct Selection it still opens Corners. +#[test] +fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transform_panel() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let v = ViewInfo::default(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len()); + let double_click = |s: &mut Session, tool: &str| { + s.select_tool(tool, v).unwrap(); + let mut asked = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap()); + } + asked + }; + assert_eq!(double_click(&mut s, "selection"), vec![UiRequest::Panel("transform".into())]); + let st = s.doc().unwrap(); + assert!(*st.doc == *doc, "the document is unchanged"); + assert_eq!(st.selection, selection); + assert_eq!(st.history.undo.len(), steps, "no undo step"); + assert!(st.interaction.is_none()); + assert_eq!(s.tool_id(), "selection"); + // Direct Selection opens Corners for the corner it picked with the first click. + let asked = double_click(&mut s, "directSelection"); + assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}"); +} diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs index bce666d484..06bb550219 100644 --- a/crates/mcp/src/tests/shapewidgets.rs +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -1,5 +1,6 @@ -//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner -//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's +//! Live shape widgets through MCP: a shape tool's or the Selection tool's double-click on a +//! selected live shape's corner widget, whose gesture's `requests` carry the Transform panel, and a +//! drag on a live polygon's //! side widget. use serde_json::{Value, json}; @@ -28,6 +29,10 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() // Off the widgets, the double-click asks for nothing. let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); assert_eq!(off["requests"], json!([]), "{off}"); + // The Selection tool's double-click on the widget asks for the panel too. + let sel = ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [{"kind": "doubleclick", "x": at.x, "y": at.y}]})); + assert_eq!(sel["requests"], json!([{"panel": "transform"}]), "{sel}"); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps, "no undo step"); } /// The selected live polygon's sides, radius and transform. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 359f41676b..68f43889f7 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape", ), ( "ui.simplifyAuto", diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index ab234cf507..00f72f6f4d 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -4,7 +4,8 @@ //! sharpens) the corners whose widgets show together, on every selected path (#938): every corner //! of a path selected whole, those with a selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner //! kind (round, inverted round, chamfer), as the Up and Down arrows do while one is dragged -//! (#2898); double-clicking one opens the Corners dialog. The +//! (#2898); double-clicking one opens the Corners dialog with Direct Selection and shows the +//! Transform panel with the Selection tool. The //! Selection and Direct Selection tools share this, and the canvas draws the widgets from the same //! geometry. @@ -212,7 +213,8 @@ pub fn over_widget(cx: &ToolContext, p: Point, any_path: bool) -> bool { CornerWidgets::for_tool(cx, any_path).and_then(|w| w.hit(p, cx.tol(5.0))).is_some() } -/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path. +/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path +/// (Direct Selection; the Selection tool shows the Transform panel instead). pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option { let w = CornerWidgets::for_tool(cx, any_path)?; let (i, _) = w.hit(p, cx.tol(5.0))?; diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 21b240b453..e9235b33e9 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -355,13 +355,24 @@ fn alt_click_cycles_the_kind_and_double_click_opens_the_dialog() { assert_eq!(a, vec![Action::Exec("object.setLiveShape".into(), want.clone())], "{tool}"); } } - // A double-click on a widget opens Corners for the shown corners; elsewhere it doesn't. + // With Direct Selection, a double-click on a widget opens Corners for the shown corners; + // elsewhere it doesn't. let cx1 = cx(&d, &part, &p); let a = crate::create("directSelection").pointer(&cx1, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0)); assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0]}))]); let cx2 = cx(&d, &whole, &p); - let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); + let a = crate::create("directSelection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0, 1, 2, 3]}))]); + // With the Selection tool, it shows the Transform panel instead, on any of the widgets. + for at in [(110.0, 110.0), (190.0, 110.0), (190.0, 190.0), (110.0, 190.0)] { + let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, at.0, at.1)); + assert_eq!(a, vec![Action::Panel("transform".into())], "{at:?}"); + } + // With the shape widgets hidden, the same double-click isolates the shape, as off the widgets. + let mut hidden = cx(&d, &whole, &p); + hidden.shape_widgets = false; + let a = crate::create("selection").pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); + assert_eq!(a, vec![Action::Exec("object.isolate".into(), json!({"id": id.0}))]); // Off the widgets, the Selection tool's double-click isolates the shape (Double Click To // Isolate) instead. let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0)); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fc18a978e6..faa2d2cd8d 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -4,7 +4,7 @@ //! bounding-box scale (Shift proportional, Alt from center; Snap to Grid, Snap to Pixel, Smart //! Guides and Snap to Point snap what the handle moves) and rotate (outside corners, Shift 45°), //! drag a live rectangle's or polygon's corner widget to round its corners (Alt-click cycles their kind, -//! double-click opens the Corners dialog), drag a live ellipse's pie widgets to set its pie angles +//! double-click shows the Transform panel), drag a live ellipse's pie widgets to set its pie angles //! (double-click makes it whole again: [`crate::pie`]), double-click a group or an object to enter isolation //! mode (Double Click To Isolate), Cmd/Ctrl-click to select the object behind (Command Click to Select Objects Behind), //! click or drag a ruler guide ([`crate::rulerguide`]), Cmd/Ctrl+Shift-double-click a ruler guide or @@ -1789,7 +1789,12 @@ impl SelectionTool { } return vec![]; } - if let Some(a) = corners::double_click(cx, p, false).or_else(|| pie::double_click(cx, p)).or_else(|| typewidget::double_click(cx, p)) { + // A corner widget of a selected live shape shows the Transform panel, as with the shape + // tools; the tool and the selection stay as they are. Direct Selection opens Corners. + if corners::over_widget(cx, p, false) { + return vec![Action::Panel("transform".into())]; + } + if let Some(a) = pie::double_click(cx, p).or_else(|| typewidget::double_click(cx, p)) { return vec![a]; } // The Shaper Group's mode widget answers each click of a double-click on it. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4602e12072..c356bc207e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1533,7 +1533,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape", ), ( "ui.simplifyAuto", diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..9431c342d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7693,8 +7693,12 @@ outlining in red those that reach their limit; the Selection tool shows the widg the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on the live rectangles among the targets alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: -`items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, -dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). +`items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind. Double-clicking one with Direct Selection opens Corners (`ui.corners {id?, corners?}`, +dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). Double-clicking a selected live shape's corner +widget with the Selection tool shows and selects the Transform panel, as the Rectangle, Rounded Rectangle, Ellipse, +Polygon and Star tools do. With the headless backend, the `pointer_gesture` reply carries `{"panel": "transform"}` in its +`requests`; the desktop app runs `window.panel.activate {"panel": "transform"}` instead, and its reply has no `requests`. The tool, the selection and the document stay as they are, and +no undo step is added. `view.shapeWidgets {on?}` (desktop app, the Hide Shape Widgets and Show Shape Widgets button in the Control bar of the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools) hides or shows the corner widgets of selected live rectangles and polygons, the pie widgets of live ellipses and the side widget of a live polygon, for the Selection tool diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..5f6f4ae48d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1479,7 +1479,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). + - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..1187ea9844 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -267,7 +267,7 @@ tools, never checked side by side) isn't captured row by row. | Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | | Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | +| Live Corners widgets (radius readout, Alt-click cycles kind, Direct Selection double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | From f355716ffe5079d0223bc1c0bc920e3b904e37ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 22:26:27 -0800 Subject: [PATCH 006/145] Retype: a mark first after a split leaves the shared measures alone When the rest of a line after a mark that a split left first starts with another mark, that rest is no longer measured for tracking. Its own pass leaves the mark out and measures the glyphs after it, so the earlier measure was thrown away but still took from the measures shared by every line in the call. A run of marks could use them up, and a tracked line retyped with them then lost its tracking and split glyph by glyph. --- crates/engine/src/cmd/retype.rs | 8 ++++-- crates/engine/src/cmd/retype_tests.rs | 35 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 51d9398870..ad222dd5d3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -648,9 +648,13 @@ fn verified( } if n > 1 { // The tracking was measured with the mark's gap in it: the rest is measured again - // without it, from the same budgets as the rest after a split. + // without it, from the same budgets as the rest after a split. A rest that starts + // with a mark too is not measured here: its own pass leaves that mark out and + // measures the glyphs after it. let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6); - let rest = if measurable { + let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + l.part(1, n) + } else if measurable { remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6)); track_budget = track_budget.saturating_sub(n - 1); l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d77fe00774..a862a3f1b5 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -194,6 +194,41 @@ fn a_combining_mark_starts_no_line() { assert_eq!(left, pair, "{r}"); } +#[test] +fn marks_first_after_a_split_leave_other_lines_their_tracking() { + // Twenty marks moved off their base, each one first on its line in turn, do not use up the + // measures of the other lines: the tracked line retyped with them keeps its tracking. + let mut s = session(); + let marks = outlined( + &mut s, + json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}), + ); + let mut moved: Vec = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(moved.len(), 22); + moved = moved[1..21].to_vec(); + let id = s + .execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0; + moved.push(mark); + s.execute("select.set", &json!({"ids": moved})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts = r["texts"].as_array().unwrap(); + let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); + assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + moved.sort_unstable(); + assert_eq!(left, moved, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); From cbe31304f10c9e01bd469f4c5a3713727c76bffa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 22:38:14 -0800 Subject: [PATCH 007/145] Docs: the Selection tool's corner widget double-click shows the Transform panel in the shape tools entry --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1187ea9844..7ae6226a81 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -271,7 +271,7 @@ tools, never checked side by side) isn't captured row by row. | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing; the Selection tool's double-click on a corner widget shows the Transform panel too, and a Direct Selection double-click opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | From c4e360fec288cd4f57c87e225efc2ac41ad66119 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:57:41 -0800 Subject: [PATCH 008/145] Align: align.toSelection returns "artboard" only for one object with no anchor points selected The align.toSelection params text and docs/mcp.md said the command returns "artboard" while one object is selected. With anchor points selected (Direct Selection) it returns "selection", because the points align to each other, and with the Artboard tool chosen it returns the stored choice, Selection. The texts now name both cases, and crates/mcp/src/ui_catalog.rs is regenerated with cargo xtask ui-commands. A test covers two anchor points of one path selected while Artboard is the stored choice. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/align/tests.rs | 14 ++++++++++++++ docs/mcp.md | 4 +++- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..1a8e3730b4 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -395,7 +395,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..cc6466fa94 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -396,7 +396,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index ffdc0b10a3..77194f7623 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -679,6 +679,20 @@ fn object_align_lists_the_align_to_choices() { assert_eq!(app.ui.align_to, AlignTo::Selection); } +/// With anchor points of one path selected (Direct Selection), Align to Selection returns +/// `"selection"`: the points align to each other, so the lone path does not make it Artboard. +#[test] +fn align_to_selection_with_anchor_points_returns_selection() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("path.create", json!({"d": "M100 40 L200 60 L150 160 Z"})).unwrap()["id"].as_u64().unwrap(); + app.ui.align_to = AlignTo::Artboard; + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + assert_eq!(app.run("align.toSelection", json!({})).unwrap(), json!({"alignTo": "selection"})); + assert_eq!(app.ui.align_to, AlignTo::Selection); + assert_eq!(align_to_checks(&app), [Some(true), Some(false), Some(false)]); +} + /// With the Artboard tool chosen, Align to Key Object is off and fails, and Align to Artboard and /// Align to Selection store the choice while the selected objects keep their key. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..0ad023455a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7827,7 +7827,9 @@ and each item runs its command. The Align panel's Align To choices are UI commands too, with no params: `align.toSelection`, `align.toKeyObject` and `align.toArtboard`. Each chooses what a click on its Align To button chooses and returns `{alignTo}`, the choice the -panel then shows (`align.toSelection` returns `"artboard"` while one object is selected, which aligns to the artboard). +panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected, +which aligns to the artboard; it returns `"selection"` while anchor points are selected with Direct Selection, which +align to each other, and with the Artboard tool chosen). `align.toSelection` and `align.toArtboard` store the choice (`ui.inspect` › `ui.align_to`) and let the key go; with the Artboard tool chosen they store it and the selected objects keep their key. With no key, `align.toKeyObject` makes the topmost of two or more selected objects the key object, or a ruler guide selected with one object the key guide, and From d3985afb348a749d909bb22546ea0671f9ebaddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:21:13 -0800 Subject: [PATCH 009/145] i18n: the message scan reads string escapes the way Rust does The untranslated-strings scan kept only the letter after a backslash for every escape other than \n, \t and a line continuation, so a message with \r, \0, \x41 or \u{e9} was checked against text the program never shows. It now decodes every character escape the Rust Reference lists (https://doc.rust-lang.org/reference/tokens.html#character-escapes), and leaves out a literal whose escape Rust rejects, such as \q, \x80 or \u{D800}, instead of building a key from it. The interface-string and message dumps are byte-identical before and after the change, so no catalog row matches differently. --- crates/ui-egui/src/i18n/tests.rs | 86 ++++++++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..25e378a43a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4653,6 +4653,55 @@ fn message_scan_joins_a_literal_continued_on_the_next_line() { } } +/// The scan reads each of Rust's character escapes in a message as the character Rust gives it +/// (https://doc.rust-lang.org/reference/tokens.html#character-escapes), and stops at the literal's +/// own closing quote, not at an escaped one. +#[test] +fn message_scan_decodes_rust_character_escapes() { + let cases = [ + (r#"a\rb" tail"#, "a\rb"), + (r#"a\0b""#, "a\0b"), + (r#"\x41\x7f\x7F""#, "A\x7f\x7f"), + (r#"caf\u{e9}""#, "café"), + (r#"caf\u{E_9}""#, "café"), + (r#"\u{1F600}\u{10_FFFF}\u{0}""#, "\u{1F600}\u{10FFFF}\0"), + (r#"a\\b""#, "a\\b"), + (r#"say \"hi\"" tail"#, "say \"hi\""), + (r#"it\'s""#, "it's"), + (r#"\n\t""#, "\n\t"), + ]; + let wrong: Vec<_> = cases.iter().filter(|(body, text)| string_literal(body).as_deref() != Some(*text)).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); + let found = source_messages(r#"fn run() { let _ = Err("bad \x41 value \u{e9}"); }"#, &[], &Default::default()); + assert_eq!(found, ["bad A value é"]); +} + +/// A literal with an escape Rust does not accept is not read as a message: an unknown letter, `\x` +/// with fewer than two hex digits or above `7F`, and `\u` without braces, without digits, with a +/// leading underscore, with more than six digits, or naming a surrogate or a value above `10FFFF`. +#[test] +fn message_scan_rejects_invalid_rust_escapes() { + let bodies = [ + r#"bad \q""#, + r#"bad \x4""#, + r#"bad \x4g""#, + r#"bad \x80""#, + r#"bad \x+1""#, + concat!(r"bad \u", "00e9\""), + r#"bad \u{""#, + r#"bad \u{}""#, + r#"bad \u{_e9}""#, + r#"bad \u{e9""#, + r#"bad \u{D800}""#, + r#"bad \u{110000}""#, + r#"bad \u{1234567}""#, + ]; + let read: Vec<_> = bodies.iter().filter(|body| string_literal(body).is_some()).collect(); + assert!(read.is_empty(), "{read:?}"); + let code = r#"fn run() { let _ = Err("bad \q value"); let _ = Err("bad \u{D800} value"); let _ = Err("good value"); }"#; + assert_eq!(source_messages(code, &[], &Default::default()), ["good value"]); +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -7362,8 +7411,12 @@ fn without_test_module(text: &str) -> &str { text } -/// The text of a string literal whose opening quote was just read, escapes resolved. A `\` at the -/// end of a line drops the line break and the whitespace that starts the next line, as Rust does. +/// The text of a string literal whose opening quote was just read, escapes resolved as Rust resolves +/// them (https://doc.rust-lang.org/reference/tokens.html#character-escapes): `\n`, `\r`, `\t`, `\0`, +/// `\\`, `\'`, `\"`, `\x` with two hex digits up to `7F`, and `\u{…}` with one to six hex digits +/// (underscores allowed after the first) naming a Unicode scalar value. A `\` at the end of a line +/// drops the line break and the whitespace that starts the next line. A literal with any other +/// escape, or one left unclosed, is `None`. fn string_literal(s: &str) -> Option { let mut out = String::new(); let mut it = s.chars(); @@ -7372,9 +7425,36 @@ fn string_literal(s: &str) -> Option { '"' => return Some(out), '\\' => match it.next()? { 'n' => out.push('\n'), + 'r' => out.push('\r'), 't' => out.push('\t'), + '0' => out.push('\0'), + c @ ('\\' | '\'' | '"') => out.push(c), + 'x' => { + let (high, low) = (it.next()?.to_digit(16)?, it.next()?.to_digit(16)?); + out.push(char::from_u32(high * 16 + low).filter(char::is_ascii)?); + } + 'u' => { + if it.next()? != '{' { + return None; + } + let (mut value, mut digits) = (0u32, 0); + loop { + match it.next()? { + '}' if digits > 0 => break, + '_' if digits > 0 => {} + c => { + value = value * 16 + c.to_digit(16)?; + digits += 1; + if digits > 6 { + return None; + } + } + } + } + out.push(char::from_u32(value)?); + } '\n' | '\r' => it = it.as_str().trim_start_matches([' ', '\t', '\n', '\r']).chars(), - c => out.push(c), + _ => return None, }, c => out.push(c), } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..77b2531f39 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1151,6 +1151,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Polish labels and messages call drawn art and artwork *kompozycja*, the term the catalog's header sets, instead of *grafika* or *rysunek*. *Grafika* stays for what the English calls a graphic (graphic styles, library and 3D graphics, GPU graphics), and line art, the art brush and an artboard (*obszar kompozycji*) keep their own terms (`polish_rows_call_artwork_kompozycja`). - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). + - The untranslated-strings report reads the escapes in a message (`\r`, `\0`, `\x41`, `\u{e9}` and the others the Rust Reference lists at https://doc.rust-lang.org/reference/tokens.html#character-escapes) as the characters the program shows, and leaves out a literal with an escape Rust does not accept, such as `\q` or `\u{D800}` (`message_scan_decodes_rust_character_escapes`, `message_scan_rejects_invalid_rust_escapes`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). From a6c0557819487afa2b0926beffd5ee17810817a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:28:12 -0800 Subject: [PATCH 010/145] Align: align.toSelection returns "artboard" for one object only without the Artboard tool With one object selected, no anchor points selected and the Artboard tool chosen, align.toSelection returns "selection", the stored choice. The params text and docs/mcp.md now name that condition, and crates/mcp/src/ui_catalog.rs is regenerated. A test covers the case. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/align/tests.rs | 13 +++++++++++++ docs/mcp.md | 6 +++--- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1a8e3730b4..75ae121ece 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -395,7 +395,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected and the Artboard tool is not chosen, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index cc6466fa94..8cc699ea76 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -396,7 +396,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected and the Artboard tool is not chosen, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index 77194f7623..7bbcb1af18 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -713,6 +713,19 @@ fn align_to_commands_with_the_artboard_tool() { assert_eq!(app.session.active().unwrap().selection.key.map(|k| k.0), front.as_u64(), "the key stays"); } +/// With the Artboard tool chosen and one object selected with no anchor points, Align to Selection +/// returns `"selection"`, the stored choice, not `"artboard"`. +#[test] +fn align_to_selection_with_one_object_and_the_artboard_tool_returns_selection() { + let (mut app, back, _) = back_and_front(); + app.run("select.set", json!({"ids": [back]})).unwrap(); + app.ui.align_to = AlignTo::Artboard; + app.select_tool("artboard"); + assert_eq!(app.run("align.toSelection", json!({})).unwrap(), json!({"alignTo": "selection"})); + assert_eq!(app.ui.align_to, AlignTo::Selection); + assert_eq!(align_to_checks(&app), [Some(true), Some(false), Some(false)]); +} + /// Align to Key Object is off and fails when the topmost selected object can't be the key: a group /// selected with an object inside it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0ad023455a..4d1de4b1ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7827,9 +7827,9 @@ and each item runs its command. The Align panel's Align To choices are UI commands too, with no params: `align.toSelection`, `align.toKeyObject` and `align.toArtboard`. Each chooses what a click on its Align To button chooses and returns `{alignTo}`, the choice the -panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected, -which aligns to the artboard; it returns `"selection"` while anchor points are selected with Direct Selection, which -align to each other, and with the Artboard tool chosen). +panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected +and the Artboard tool is not chosen, which aligns to the artboard; it returns `"selection"` while anchor points are +selected with Direct Selection, which align to each other, and with the Artboard tool chosen). `align.toSelection` and `align.toArtboard` store the choice (`ui.inspect` › `ui.align_to`) and let the key go; with the Artboard tool chosen they store it and the selected objects keep their key. With no key, `align.toKeyObject` makes the topmost of two or more selected objects the key object, or a ruler guide selected with one object the key guide, and From 5132eaebfeb33043584dbbc92f734a1e9708f476 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:42:31 -0800 Subject: [PATCH 011/145] PDF: a distorted CMYK image with an image mask keeps the resolution its pieces need A distorted CMYK image whose opacity mask is a gray image with the same corners writes the mask as the image's /SMask, and every piece of its mesh draws that one image. The image was resampled for the size its transform places it at, before the pieces' shared size was known, so with downsampling on every piece stretched a smaller image across the corners. The masked image is now resampled for the size the pieces share, as the same image without a mask is, and the pieces are drawn from the same expansion they were measured on. --- crates/pdf/src/export/images.rs | 25 ++++++++++++++++ crates/pdf/src/export/nodes.rs | 6 ++-- crates/pdf/src/tests/cmykimages.rs | 46 ++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3da2079b9b..b43e758377 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -223,6 +223,31 @@ impl Exporter<'_> { img } + /// [`Self::masked_image`] of image `im` of node `n`. A distorted image's is resampled for the + /// size every piece of its mesh shares ([`Self::warp_image_size`]), since each piece draws this + /// one image; its expanded art, whose pieces were measured, is left in `expanded` for drawing. + pub(super) fn node_masked_image( + &mut self, + n: &Node, + im: &vectorcraft_doc::ImageObject, + m: &vectorcraft_doc::OpacityMask, + expanded: &mut Option, + ) -> Option { + let interpolate = !n.extras().pixelated; + if !n.is_distorted_image() { + return self.masked_image(im, m, interpolate); + } + let g = expanded.insert(vectorcraft_effects::expand_live_deep(Some(self.doc), n)); + let pieces = g.children().and_then(|c| c.first()).map_or(&[][..], |art| vectorcraft_doc::image_quad::distorted_pieces(art)); + let shared = self.warp_image_size(pieces).map(|s| SharedSize { key: im.key.clone(), width: im.width, height: im.height, size: s.size }); + let outer = shared.map(|w| self.warp_size.replace(w)); + let img = self.masked_image(im, m, interpolate); + if let Some(outer) = outer { + self.warp_size = outer; + } + img + } + /// Draw image `im`: `img` when given (its pixels already written), else as it is loaded; with /// `pixelated` ([`vectorcraft_doc::NodeExtras::pixelated`]) viewers are asked not to smooth it. pub(super) fn image(&mut self, s: &mut Surface, im: &vectorcraft_doc::ImageObject, img: Option, pixelated: bool) { diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 94b1c819c5..1d514a569d 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -373,9 +373,11 @@ impl Exporter<'_> { let enclosing = std::mem::replace(&mut self.knockout, knockout); let (mut pushes, isolated_children) = transparency(s, n, page, container, knockout); let mask = n.extras().mask.as_deref().filter(|m| !m.disabled); + // A distorted image's art, when its masked image needs the size its pieces share. + let mut expanded = None; let alpha = match (&n.kind, mask) { // The mask's image shares the pixel grid only when it has the same corners (or none). - (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated), + (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.node_masked_image(n, im, m, &mut expanded), _ => None, }; if let Some(m) = mask @@ -502,7 +504,7 @@ impl Exporter<'_> { | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } | NodeKind::Image(_) => { - let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + let g = expanded.unwrap_or_else(|| vectorcraft_effects::expand_live_deep(Some(self.doc), n)); // The pieces draw the image as it is shown, under its color mask's key. let piece = match (&n.kind, &alpha) { (NodeKind::Image(im), Some(img)) => Some((self.doc.shown_image(n, im).key.clone(), img.clone())), diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index b5f6185ea9..83f9340dc0 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1210,6 +1210,52 @@ fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_it } } +/// A distorted CMYK image masked on its pixel grid is resampled for the size its mesh's pieces +/// share, as it is without the mask, and not for the smaller size its transform places it at: +/// every piece draws the one image, so a smaller one would lower the resolution of every piece. +#[test] +fn a_distorted_cmyk_image_with_its_grid_mask_is_resampled_for_the_size_of_its_pieces() { + let side = 400u32; + let cmyk_widths = |masked: bool| { + let mut d = Document::new_with_mode(400.0, 400.0, ColorMode::Cmyk); + let inks = Inks::new(side, side, flat([0u8, 102, 255, 0], (side * side) as usize)).unwrap(); + d.images.insert("img".into(), ImageBlob::cmyk_tiff(&inks).unwrap()); + let alpha = image::GrayImage::from_fn(side, side, |x, y| image::Luma([((x + y) % 256) as u8])); + d.images.insert("alpha".into(), ImageBlob::new("image/png", png(alpha))); + let image = |key: &str| { + NodeKind::Image(Box::new(ImageObject { + key: key.into(), + width: side, + height: side, + // 50 pt: smaller than the corners below. + xf: Affine::scale(0.125), + link: None, + placement: Default::default(), + pixels: None, + })) + }; + let q = [(0.0, 0.0), (150.0, 0.0), (125.0, 150.0), (25.0, 150.0)].map(|(x, y)| Point::new(x, y)); + let mut n = Node::new(d.alloc_id(), image("img")); + if masked { + let mut art = Node::new(d.alloc_id(), image("alpha")); + art.set_image_corners(q).unwrap(); + n = n.with_mask(Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)))); + } + n.set_image_corners(q).unwrap(); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let s = json!({"compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); + let out = export_with_report(&d, &opts(s)).unwrap(); + let w = written(&out.bytes); + assert_eq!(w.iter().filter(|w| w.space == "DeviceCMYK" && w.smask).count(), usize::from(masked), "{w:?}"); + w.iter().filter(|w| w.space == "DeviceCMYK").map(|w| w.width).collect::>() + }; + let plain = cmyk_widths(false); + assert_eq!(plain.len(), 1, "one image for every piece: {plain:?}"); + assert!(plain[0] > 100 && plain[0] < side, "resampled for the pieces, not for the transform's 50 pt: {plain:?}"); + assert_eq!(cmyk_widths(true), plain); +} + /// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden /// pixels are clear in the image's `/SMask`. #[test] From d4cd3f2c485f79c02c43d1a87cf21dba7e970302 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:52:46 -0800 Subject: [PATCH 012/145] Tests: the missing-font question's tests check the open question and the clicked caret An answer that names another question, Cancel or OK, now has to leave the open question answerable: the right token's OK still starts the edit at the clicked character. The canvas double-click lands a quarter of the way into the text, and after OK the caret has to be the one a click at that point puts in the type being edited. --- crates/tools/src/text/tests.rs | 13 ++++++++++++- crates/ui-egui/src/canvas/tests.rs | 7 ++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 7ee90ee1c8..249bf9d412 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -2273,7 +2273,8 @@ fn the_answer_to_the_missing_font_question_passes_the_option_check() { } /// Cancel starts no edit, and the edit in progress on other type goes on; an answer that names -/// another question, or one given to a document changed since, starts nothing either. +/// another question, or one given to a document changed since, starts nothing either. An answer +/// naming another question leaves the open question as it was. #[test] fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { let (mut d, first, mut tool) = editing("First"); @@ -2296,6 +2297,16 @@ fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { assert!(tool.poll(&changed, false).is_empty()); assert_eq!(tool.editing, Some(first)); assert!(!tool.waiting()); + // An answer naming another question leaves the open one answerable: its OK still starts the edit. + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": false})); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": true})); + assert!(!tool.waiting(), "another question's answer"); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + assert!(tool.waiting()); + let acts = tool.poll(&c, false); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [other.0]}))), "{acts:?}"); + assert_eq!((tool.editing, tool.caret), (Some(other), 2)); } /// Every new edit of such type asks again, after an earlier OK too, and a style the family lacks diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..52d455d0d6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9471,7 +9471,8 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); let b = node(&app).geometric_bounds().unwrap(); - let at = xf.to_screen(b.center()); + // A quarter of the way in, away from the middle of the text. + let at = xf.to_screen(Point::new(b.x0 + b.width() * 0.25, b.center().y)); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; let double_click = |app: &mut VectorcraftApp, time: f64| { timed(app, time, vec![egui::Event::PointerMoved(at), button(true), button(false), button(true), button(false)]); @@ -9502,6 +9503,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { assert_eq!(o["editing"], json!(id)); let caret = o["caret"].as_u64().unwrap(); assert!((1..11).contains(&caret), "caret {caret}"); + // The caret is the one a click at that point puts in the type being edited. + timed(&mut app, 5.0, vec![button(true), button(false)]); + timed(&mut app, 5.1, vec![]); + assert_eq!(app.session.tool_options()["caret"], json!(caret), "the caret where the type was double-clicked"); app.session.tool_text("X", app.view_info()).unwrap(); let NodeKind::Text(t) = &node(&app).kind else { panic!("not text") }; assert_eq!(t.plain_text().find('X'), Some(caret as usize), "{}", t.plain_text()); From fd27b2e6d4309daecc5ac222f8b28928213aa819 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:40:58 -0800 Subject: [PATCH 013/145] Command Palette: docs rank typo results that match a word by description last A result matched through a typo that also matches another query word only through its description ranks after every other result, since the ranking compares that before the whole-query match and the label-before-path rule. Two typo words split between label and menu path tie with the reverse split only when the other words get the same grades in both results. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..8223cfd204 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1590,7 +1590,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way round. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result that matches a query word only through its description; a result matched through a typo that also matches another query word only through its description comes after every other result. Within each of these groups, how the whole query matches a result matched through a typo is judged with the misspelled word replaced by the word it meets. Results matched through a typo in the same group that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way around, when the other words get the same grades in both results. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From 63fe462a1d77c90f6bf36a3a0e95426b0dd097dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:41:24 -0800 Subject: [PATCH 014/145] Docs: a clipping mask that matches the old file's clipping path is relinked as the file's The PSD clipping-path entry in docs/target-app-parity.md said that links.update and links.relink keep every clipping mask made in the document. placed_clip_to in crates/engine/src/cmd/links.rs treats a clip group holding just the image as the old file's when same_path finds its clipping path equal to the old file's (anchors and handles within a thousandth of a point) and the fill rule matches, whoever made it. Such a mask takes the new file's clipping path, or becomes a plain group when the new file names none. The entry and the matching DCS sentence in docs/mcp.md now say so. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..a44f0aada7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9023,7 +9023,7 @@ file's composite is drawn through clips the image (a clipping group, its path un clipping path kept as the same area), and `file.place` answers the image's id as `image`, since the Links commands take the image and not the group. `links.update` and `links.relink` clip the image by the file's clipping path again (a plain group holding just the image becomes its clipping group, a new clipping group holds it when no group does, and it goes inside a clipping mask made in the -document, whose path is kept), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no +document, whose path is kept unless it matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no clipping path, a clipping group holding just the image whose path is the old file's clipping path loses that path and stays as a plain group of the image, with its id, name, visibility and transparency (one whose path was given the even-odd fill rule stays as it is). The link shows as modified when a plate file of its own changes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..330330957f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document whose clipping path matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From 1be942d7fc435d6a517724f8dc62aabc54018044 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:16:42 -0800 Subject: [PATCH 015/145] Dimension tool: a drag from a dimension already drawn moves it With no points or lines picked, a press within 8 pixels of what a visible, unlocked dimension draws (its lines, arrowheads and label), where it is the topmost object that can be edited, followed by a drag moves that dimension as one undo step. A segment of the art as near the press as the dimension's lines and label, or nearer, takes the press instead, and a click there without a drag still picks a point. The part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center as the pointer turns, or toward the pointer when grabbed at the center. The dimension keeps what it measures and its link to the art. With Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line, as when it is placed, and of two lines on one level the one nearer the pointer along it wins. Isolation mode, clipping masks and locked artboards apply as they do to a click; with a part of a dimension isolated, the dimension is not dragged. A dimension that a geometry effect on it, on one of its parts or on a group around it draws elsewhere is not dragged, except in Outline view and on a layer whose Preview is off. dimension.update takes `at: [x,y]`, which puts a linear dimension's line through the point, gives an angular arc a radius of the point's distance from the vertex (at least 12 pt), or turns a radius or diameter line toward it. With Real-time Drawing off, a dimension.update preview that names its dimensions outlines only those dimensions. A dimension pasted into a document that had none now marks the document as holding dimensions (Document::insert), so the Dimension tool drags it like one drawn there and edits refresh it. Opening a native file sets the flag from the objects it holds, which covers files saved after such a paste. Docs: docs/dimensions.md, docs/target-app-parity.md. --- crates/doc/src/document.rs | 8 +- crates/engine/src/cmd/dimension.rs | 7 +- crates/engine/src/tooling.rs | 22 ++- crates/engine/tests/it/dimensions.rs | 278 +++++++++++++++++++++++++++ crates/format/src/lib.rs | 5 + crates/tools/src/dimension.rs | 194 ++++++++++++++++++- docs/dimensions.md | 26 ++- docs/target-app-parity.md | 1 + 8 files changed, 520 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 608902756b..388c51abfb 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -551,13 +551,19 @@ impl Document { } /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes - /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). + /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). A + /// node that is or holds a dimension (a pasted one) sets [`Document::dimensions`]. pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { + fn holds_dimension(n: &Node) -> bool { + n.extras().dimension.is_some() || n.children().into_iter().flatten().any(|c| holds_dimension(c)) + } let id = node.id; self.check_ruler_guide_place(&node, parent)?; + let dimension = !self.dimensions && holds_dimension(&node); let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &node); ch.insert(i, Arc::new(node)); + self.dimensions |= dimension; Ok(id) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e38f8f99bb..9f631aafd2 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Update Dimensions", [], None, - "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", + "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}", has_doc, update ), @@ -159,6 +159,7 @@ fn update(s: &mut Session, p: &Value) -> Result { return Err(error("Select dimensions to update")); } let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None }; + let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None }; // Every dimension is checked before anything changes, and an update that changes none of // them records no undo step. let mut next = Vec::with_capacity(ids.len()); @@ -178,6 +179,10 @@ fn update(s: &mut Session, p: &Value) -> Result { } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; + if let Some(at) = at { + dim.place(at); + dim.resolve(doc).map_err(error)?; + } if dim != old { next.push((*id, dim)); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..9edfa98661 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1,7 +1,7 @@ //! Hosting the active tool: pointer/key events → actions → commands. use serde_json::{Map, Value}; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_geom::Point; use vectorcraft_tools::distort::perspective::widget::WidgetPlace; use vectorcraft_tools::draw2::FEEDBACK; @@ -1754,7 +1754,7 @@ impl Session { (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { - let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default(); + let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default(); let (objects, color) = self .active() .map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id)))) @@ -1795,11 +1795,17 @@ const FEEDBACK_MAX_POINTS: usize = 100_000; /// The outlines of every selected object, a group's members each with their own, or the selection's /// bounds when the outlines' points and the objects evaluated to make them come to more than -/// [`FEEDBACK_MAX_POINTS`]. -fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec { - let nodes = selection.objects.iter().filter_map(|&id| doc.node(id)); - let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| { - doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect() - }); +/// [`FEEDBACK_MAX_POINTS`]. A `dimension.update` preview (`cmd`, `p`) that names its dimensions, +/// as the Dimension tool sends for a dimension it drags, outlines those dimensions instead. +fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection, cmd: &str, p: &Value) -> Vec { + let named: Vec = if cmd == "dimension.update" { + p.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect() + } else { + vec![] + }; + let objects = if named.is_empty() { &selection.objects } else { &named }; + let nodes = objects.iter().filter_map(|&id| doc.node(id)); + let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS) + .unwrap_or_else(|| doc.bounds_of(objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()); outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect() } diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..c92390feec 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2115,6 +2115,284 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() { assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); } +/// A drag with the Dimension tool from a dimension already drawn moves its line as far across as +/// the pointer moved, keeps what it measures and its link to the art, and is one undo step. A +/// click on its line does not move it, and neither does Escape during the drag. +#[test] +fn dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let (count, label) = (s.doc().unwrap().doc.node_count(), text(&s, first)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Dragged up and to the side: the line goes up as far as the pointer, and stays over the + // points it measures. + drag(&mut s, (150.0, 170.0), (180.0, 130.0)); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(100.0, 200.0), pt(200.0, 200.0))); + assert_eq!((s.doc().unwrap().doc.node_count(), text(&s, first)), (count, label)); + // One undo step puts it back. + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "edit.redo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Still linked: moving the art moves its points, and the line keeps its distance from them. + let art = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + run(&mut s, "select.set", json!({"ids":[art]})); + run(&mut s, "object.move", json!({"dx":0,"dy":10})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 140.0), pt(200.0, 140.0))); + run(&mut s, "object.move", json!({"dx":0,"dy":-10})); + run(&mut s, "select.none", json!({})); + run(&mut s, "dimension.update", json!({"ids":[first],"at":[150,170]})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A click on the line picks a point there and leaves the dimension where it is. + linear_click(&mut s, plain, 150.0, 170.0); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // Escape during the drag leaves it where it was. + ev(&mut s, PointerKind::Down, 150.0, 170.0); + ev(&mut s, PointerKind::Drag, 150.0, 120.0); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + ev(&mut s, PointerKind::Up, 150.0, 120.0); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A locked dimension is not moved: the drag from its line drags out nothing either. + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +/// A dimension moved with the Dimension tool lands on the level of a parallel dimension line +/// within the Smart Guides snapping tolerance, and its own line before the drag is not a level. +#[test] +fn a_dimension_moved_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 250.0, 150.0); + let second = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 150.0), pt(300.0, 150.0))); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // 3.5 points off its own level, with no other level there: where the pointer puts it. + drag(&mut s, (150.0, 170.0), (150.0, 166.5)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 166.5), pt(200.0, 166.5))); + // 2.5 points below the first line's new level: on it. + drag(&mut s, (250.0, 150.0), (250.0, 169.0)); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 166.5), pt(300.0, 166.5))); +} + +/// `dimension.update` with `at` puts a linear dimension's line, an angular dimension's arc or a +/// radius line through the point, and keeps what each measures; a bad `at` changes nothing. +#[test] +fn dimension_update_at_moves_the_line_through_the_point() { + let mut s = session(); + let line = edge(&mut s); + let linear = dim(&mut s, line); + let label = text(&s, linear); + run(&mut s, "dimension.update", json!({"ids":[linear],"at":[130,50]})); + let d = recipe(&s, linear); + assert!((d.line_ends().0.y - 50.0).abs() < 1e-9 && (d.line_ends().1.y - 50.0).abs() < 1e-9, "{:?}", d.line_ends()); + assert_eq!(text(&s, linear), label); + let angular = run(&mut s, "dimension.create", json!({"mode":"angular","a":[100,0],"vertex":[0,0],"b":[0,100]}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[angular],"at":[60,0]})); + assert!((recipe(&s, angular).offset - 60.0).abs() < 1e-9); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let radius = run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[radius],"at":[172,400]})); + let d = recipe(&s, radius); + assert!(d.b.distance(vectorcraft_geom::Point::new(172.0, 244.0)) < 1e-6, "turned toward the point: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + let before = recipe(&s, linear); + for bad in [json!([1]), json!("x"), json!([0, 1e12])] { + assert!(s.execute("dimension.update", &json!({"ids":[linear],"at":bad})).is_err(), "{bad}"); + assert_eq!(recipe(&s, linear), before); + } +} + +/// A dimension dragged with the Dimension tool follows the part grabbed: a diameter grabbed on its +/// far half turns that half toward the pointer, and an angular arc grabbed away from its middle +/// grows by as much as the pointer moved away from the vertex. +#[test] +fn a_dragged_dimension_follows_the_part_grabbed() { + let plain = ViewInfo::default(); + let mut s = session(); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let diameter = run(&mut s, "dimension.create", json!({"mode":"diameter","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[diameter],"at":[244,172]})); + let angular = + run(&mut s, "dimension.create", json!({"mode":"angular","a":[500,400],"vertex":[400,400],"b":[400,500],"offset":60}))["id"].as_u64().unwrap(); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Grabbed left of the center and dragged up: the left half goes up, the right half down. + drag(&mut s, (120.0, 172.0), (120.0, 152.0)); + let d = recipe(&s, diameter); + assert!(d.b.y > 172.0 + 1.0, "the half not grabbed turns away from the pointer: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + // Grabbed at the center: it turns toward the pointer. + drag(&mut s, (172.0, 172.0), (172.0, 100.0)); + assert!(recipe(&s, diameter).b.distance(vectorcraft_geom::Point::new(172.0, 100.0)) < 1e-6, "{:?}", recipe(&s, diameter).b); + // Grabbed 10° from the arc's start and dragged 20 points straight away from the vertex. + let (sin, cos) = 10f64.to_radians().sin_cos(); + drag(&mut s, (400.0 + 60.0 * cos, 400.0 + 60.0 * sin), (400.0 + 80.0 * cos, 400.0 + 80.0 * sin)); + assert!((recipe(&s, angular).offset - 80.0).abs() < 1e-6, "the arc's radius: {}", recipe(&s, angular).offset); +} + +/// The Dimension tool takes a drag only from a dimension the canvas hits: one painted wider than +/// the reach is taken by its stroke, while one outside isolation mode, around an isolated part of +/// it, clipped away where the press is or drawn elsewhere by a geometry effect stays put. With +/// Real-time Drawing off the dimension being dragged is outlined. +#[test] +fn a_dimension_is_dragged_only_where_the_canvas_hits_it() { + use vectorcraft_engine::tools::Overlay; + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let at_170 = (pt(100.0, 170.0), pt(200.0, 170.0)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // A 30-point line: a press 13 points from its middle is on its stroke. + let (mut s, first) = level_start(plain); + run(&mut s, "dimension.update", json!({"ids":[first],"options":{"lineWeight":30}})); + drag(&mut s, (115.0, 183.0), (115.0, 143.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Outside the isolated group: not moved. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":50,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In a clipping mask that leaves its right half out: not taken there, taken on its left half. + let (mut s, first) = level_start(plain); + let mask = run(&mut s, "shape.rectangle", json!({"x":90,"y":140,"width":50,"height":90}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, mask]})); + run(&mut s, "object.clippingMask.make", json!({})); + run(&mut s, "select.none", json!({})); + let count = s.doc().unwrap().doc.node_count(); + drag(&mut s, (180.0, 170.0), (180.0, 130.0)); + assert_eq!((recipe(&s, first).line_ends(), s.doc().unwrap().doc.node_count()), (at_170, count)); + // That press picked a point, as a click there does: Escape drops it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + drag(&mut s, (120.0, 170.0), (120.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // In a group whose Transform effect draws it 50 points lower: not taken where it is drawn. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[group],"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In Outline view the canvas draws no effects: taken where its recipe puts it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + let outline = ViewInfo { outline: true, ..plain }; + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), outline).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // A Transform effect on its parts draws them 50 points lower: not taken where they are drawn. + let (mut s, first) = level_start(plain); + let parts: Vec = s.doc().unwrap().doc.node(NodeId(first)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":parts,"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // With one of its parts isolated, the dimension around it is outside the editing scope. + let (mut s, first) = level_start(plain); + let part = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The dimension line, which the press below lands on. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x0 < 150.0 && r.x1 > 150.0 && r.y0 < 171.0 && r.y1 > 169.0)); + line.unwrap().id.0 + }; + run(&mut s, "object.isolate", json!({"id": part})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // Real-time Drawing off: the dimension is outlined where the drag puts it, and other selected + // art, which the drag does not move, is not. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":400,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, rect]})); + run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": false})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 110.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + let boxes: Vec = s + .overlays(plain) + .into_iter() + .filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(&path)) } else { None }) + .collect(); + assert!(boxes.iter().any(|r| r.y0 < 111.0 && r.y1 > 109.0 && r.width() >= 99.0), "the dragged dimension is outlined at its new place"); + assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}"); +} + +/// A dimension pasted into a document that had none is dragged with the Dimension tool like one +/// drawn there. +#[test] +fn a_dimension_pasted_into_another_document_is_dragged() { + let plain = ViewInfo::default(); + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 612, "height": 792})); + run(&mut s, "edit.paste", json!({})); + let pasted = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let (a, b) = recipe(&s, pasted).line_ends(); + let mid = a.midpoint(b); + for (kind, y) in [(PointerKind::Move, mid.y), (PointerKind::Down, mid.y), (PointerKind::Drag, mid.y - 40.0), (PointerKind::Up, mid.y - 40.0)] { + s.pointer(&PointerEvent::new(kind, mid.x, y), plain).unwrap(); + } + let (a2, b2) = recipe(&s, pasted).line_ends(); + assert!((a2.y - (a.y - 40.0)).abs() < 1e-6 && (b2.y - (b.y - 40.0)).abs() < 1e-6, "{:?} → {:?}", (a, b), (a2, b2)); +} + +/// A file that holds a dimension but was saved without the document's dimension flag (as one saved +/// after a dimension was pasted into a document that had none) opens with its dimension dragged +/// by the Dimension tool. +#[test] +fn a_dimension_in_a_file_saved_without_the_flag_is_dragged() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (s, first) = level_start(plain); + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + doc.dimensions = false; + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(), None); + reopened.select_tool("dimension", plain).unwrap(); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + reopened.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&reopened, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + /// A second dimension of the same two points as a dimension already drawn lands on its level too. /// Off every level, a pointer moved in small steps while it is placed puts the line at each step, /// with no pull from the preview of the dimension itself. diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a8c7358aa7..430769069d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -637,6 +637,11 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize // Untrusted: the type's sizes, leading, baseline shifts and scales, its indents and paragraph // spacing, and its tab stops, each within its range (after the depth limit: the walk recurses). doc.keep_type_values_in_range(); + // Untrusted, and unset in a file saved after a dimension was pasted into a document that had + // none: the flag is set when some object is a dimension (after the depth limit too). + let mut dimensions = false; + doc.walk(|n| dimensions |= n.extras().dimension.is_some()); + doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index dffe13a378..081703bb13 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -106,6 +106,12 @@ pub struct DimensionTool { /// The document's next object id at the dimension's first preview: the id its preview takes /// (`dimension.create` gives the dimension the next id). The preview is not a level. preview_id: u64, + /// The dimension drawn already under the press under way, when a drag from there moves it + /// ([`dimension_under`]). + grab: Option, + /// While a dimension drawn already is dragged: its id, where the press was and its recipe + /// then. `pending` holds it where the pointer puts it. + moving: Option<(NodeId, Point, Dimension)>, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -536,6 +542,107 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) } +/// The dimension drawn already that a drag from `p` moves, and how far `p` lies from its lines +/// and label (0 inside the label's bounds): the dimension holding the topmost object the canvas +/// hits within 8 pixels of `p`, when it can be edited. The hit takes in what the dimension paints +/// (stroke widths and arrowheads), the clipping masks over it and isolation mode. A dimension that +/// a geometry effect on it, on a part of it or on a group around it draws elsewhere is not taken +/// where effects are drawn. +fn dimension_under(cx: &ToolContext, p: Point) -> Option<(NodeId, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + fn art(n: &Node, p: Point, budget: &mut usize, near: &mut f64) { + if *budget == 0 || !n.visible { + return; + } + *budget -= 1; + if let NodeKind::Text(_) = &n.kind + && let Some(r) = n.geometric_bounds() + { + let (dx, dy) = ((r.x0 - p.x).max(p.x - r.x1).max(0.0), (r.y0 - p.y).max(p.y - r.y1).max(0.0)); + *near = near.min(dx.hypot(dy)); + } + if let Some(path) = n.path_data() { + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + if *budget == 0 { + return; + } + *budget -= 1; + let d = sp.segment(i).nearest(p, 1e-4).distance_sq.sqrt(); + if d.is_finite() { + *near = near.min(d); + } + } + } + } + for c in n.children().into_iter().flatten() { + art(c, p, budget, near); + } + } + if !cx.doc.dimensions { + return None; + } + let opt = vectorcraft_doc::hit::HitOptions { tol: cx.tol(8.0), ..cx.hit_options() }; + let hit = vectorcraft_doc::hit::hit_test(cx.doc, p, opt)?; + let chain: Vec = hit.ancestry.iter().copied().chain([hit.leaf]).collect(); + // The innermost dimension holding the object hit: the one that draws it. + let at = chain.iter().rposition(|id| cx.doc.node(*id).is_some_and(|n| n.extras().dimension.is_some()))?; + let id = *chain.get(at)?; + // In isolation mode only a dimension at or inside the isolated object is moved: one around an + // isolated part of it is outside the editing scope. + let scope_at = opt.scope.and_then(|s| chain.iter().position(|a| *a == s)); + if scope_at.is_some_and(|i| i > at) { + return None; + } + // Where a geometry effect on the dimension, on a part of it or on a group around it draws it is + // not where its recipe puts it, so a drag there could not follow the pointer. In outline, and + // below a layer whose Preview is off, the canvas draws no effects and the recipe is what it + // hits. + let nodes: Vec<&Node> = chain.iter().filter_map(|id| cx.doc.node(*id)).collect(); + let below = scope_at.map_or(0, |i| i + 1); + let outline = opt.outline || nodes.iter().skip(below).any(|n| matches!(n.kind, NodeKind::Layer { preview: false, .. })); + let displaced = nodes.iter().enumerate().any(|(i, n)| { + vectorcraft_effects::has_geometry(&n.appearance.effects) + || (i >= at && n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects()))) + }); + if !outline && displaced { + return None; + } + let n = cx.doc.node(id).filter(|_| cx.doc.is_editable(id))?; + let (mut budget, mut near) = (20_000usize, f64::INFINITY); + art(n, p, &mut budget, &mut near); + Some((id, near)) +} + +/// Where [`Dimension::place`] puts dimension `d`, grabbed at `start`, for the pointer at `p`: the +/// line of a linear dimension moves as far across as the pointer moved, the arc of an angular one +/// grows or shrinks by as much as the pointer moved away from or toward the vertex, and a radius +/// or diameter line turns about the center by the angle the pointer turned through, so the part +/// grabbed stays under the pointer wherever it was grabbed. +fn grabbed_to(d: &Dimension, start: Point, p: Point) -> Point { + let handle = d.handle(); + match d.mode { + DimensionMode::Linear => handle + (p - start), + DimensionMode::Angular => { + let out = handle - d.vertex; + let r = out.hypot() + p.distance(d.vertex) - start.distance(d.vertex); + if out.hypot() > 1e-9 { d.vertex + out / out.hypot() * r.max(12.0) } else { handle } + } + DimensionMode::Radius | DimensionMode::Diameter => { + let (from, to) = (start - d.a, p - d.a); + if to.hypot() <= 1e-9 { + return handle; + } + // Grabbed at the center: the line turns toward the pointer. + if from.hypot() <= 1e-9 { + return p; + } + let v = handle - d.a; + d.a + Vec2::from_angle(v.atan2() + to.atan2() - from.atan2()) * v.hypot() + } + } +} + /// The line of a linear dimension already drawn: its ends and its direction. type DimensionLine = ((Point, Point), Vec2); @@ -816,6 +923,9 @@ impl DimensionTool { p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { + if self.moving.is_some() { + return self.reposition(cx, p); + } self.level_guide = None; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) @@ -856,15 +966,10 @@ impl DimensionTool { if !self.began { self.preview_id = cx.doc.peek_next_id(); } - let (from, at) = match cx.interaction_doc { - Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), - None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), - }; - if !self.began || (cx.smart_guides && self.levels_at != at) { - self.levels = dimension_lines(from, (self.preview_id, [d.a, d.b])); - self.levels_at = at; - } + let points = [d.a, d.b]; + self.read_levels(cx, (self.preview_id, points)); } + let Some(d) = &mut self.pending else { return vec![] }; let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; d.place(level.map_or(p, |(on_level, _)| on_level)); if d.validate().is_err() { @@ -879,6 +984,51 @@ impl DimensionTool { actions.push(Action::Preview("dimension.create".into(), Self::params(d))); actions } + /// Reads `levels` at the first preview and, with Smart Guides on, again when the document they + /// come from has changed since: while an interaction is in progress, the document as it began. + /// `skip` names the dimension being placed or moved, which is not a level: its id and the + /// points it measures. + fn read_levels(&mut self, cx: &ToolContext, skip: (u64, [Point; 2])) { + let (from, at) = match cx.interaction_doc { + Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), + None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), + }; + if !self.began || (cx.smart_guides && self.levels_at != at) { + self.levels = dimension_lines(from, skip); + self.levels_at = at; + } + } + /// Moves the dimension drawn already that a drag picked up ([`Self::moving`]) as + /// [`grabbed_to`] says, and what it measures stays. With Smart Guides on, a linear + /// dimension's line lands on the level of a parallel dimension line, as when it is placed. + fn reposition(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.level_guide = None; + let Some((id, start, from)) = self.moving.clone() else { return vec![] }; + let at = grabbed_to(&from, start, p); + if from.mode == DimensionMode::Linear { + self.read_levels(cx, (id.0, [from.a, from.b])); + } + // The levels are measured across from the line through `at` and, along it, from the + // pointer, which may be far from the line's middle. + let dir = from.direction(); + let along = at + dir * (p - at).dot(dir); + let level = if cx.smart_guides { line_level(&self.levels, &from, along, cx.snap_tol()) } else { None }; + let at = level.map_or(at, |(on_level, _)| on_level); + let mut d = from; + d.place(at); + if d.validate().is_err() { + return vec![]; + } + self.pending = Some(d); + self.level_guide = level.map(|(_, ends)| ends); + let mut actions = vec![]; + if !self.began { + actions.push(Action::Begin("Update Dimensions".into())); + self.began = true; + } + actions.push(Action::Preview("dimension.update".into(), json!({"ids":[id.0],"at":[at.x,at.y]}))); + actions + } /// Places the pending dimension at `p` and commits it. fn place(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = self.preview(cx, p); @@ -906,6 +1056,8 @@ impl DimensionTool { self.second = None; self.level_guide = None; self.levels.clear(); + self.grab = None; + self.moving = None; } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { @@ -1038,13 +1190,37 @@ impl Tool for DimensionTool { && (anchor_under(cx, ev.pos).is_some() || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); - self.press = Some((ev.pos, self.target(cx, ev.pos))); + let target = self.target(cx, ev.pos); + // A press on a dimension drawn already, nearer to its lines and label than to any + // segment of the art, moves that dimension when it drags. A click there still + // picks a point. + self.grab = None; + if self.points.is_empty() + && self.lines.is_empty() + && let Some((id, d)) = dimension_under(cx, ev.pos) + { + let art = pick(cx, ev.pos).and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); + if art.is_none_or(|a| d < a) { + self.grab = Some(id); + } + } + self.press = Some((ev.pos, target)); vec![] } PointerKind::Drag => { if self.pending.is_some() && !self.dragging && self.press.is_some() { return self.preview(cx, ev.pos); } + if self.pending.is_none() + && let (Some((start, _)), Some(id)) = (self.press.as_ref(), self.grab) + && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) + && let Some(d) = cx.doc.node(id).and_then(|n| n.extras().dimension.as_deref()) + { + self.moving = Some((id, *start, d.clone())); + self.pending = Some(d.clone()); + self.dragging = true; + self.grab = None; + } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..1e5b52886a 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -86,7 +86,26 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its radius, inwards its diameter. Clicking it gives its radius. Ellipses have no single radius. -- **Escape** or switching tools cancels a dimension being placed. +- **Moving a dimension:** the + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes repositioning a dimension by dragging it with the Dimension tool. With no points or + lines picked, a press within 8 pixels of what a dimension draws (its lines, arrowheads and + label), where it is the topmost object that can be edited, followed by a drag of more than 3 + pixels (8 pixels when the Linear tool finds an anchor, a corner of preview bounds or the end of a + dimension line within reach of the press) moves that dimension, as one undo step. A segment of the art + as near the press as the dimension's lines and label, or nearer, takes the press instead. The + line of a linear dimension moves as far across as the pointer moves; the arc of an angular one + moves as far as the pointer moves away from or toward the vertex, to no less than 12 points from + it; a radius or diameter line turns about the center as far as the pointer turns, or toward the + pointer when it was grabbed at the center. The dimension keeps what it measures and its link to + the art. Isolation mode applies as it does to a click: with a part of a dimension isolated, the + dimension is not dragged. A dimension that a geometry effect on it, on one of its parts or on a + group around it moves or distorts is not dragged, except in Outline view and on a layer whose + Preview is off, where effects are not drawn. With Smart Guides on, a linear dimension's line + lands on the level of a parallel dimension line, as when it is placed; when two such lines lie + on one level, the one nearer the pointer along it wins. A click there without a drag still picks a point. + How far the dimension moves is VectorCraft's own rule. +- **Escape** or switching tools cancels a dimension being placed or moved. **Tool Options** set the style of new dimensions: units (inches, millimetres, points, picas, pixels, centimetres, metres, feet, yards), precision (0–6 decimals), scale, the dimension and @@ -156,7 +175,10 @@ another document. line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear - ones. A new orientation keeps the line on the side of the points it was on. An update that + ones. A new orientation keeps the line on the side of the points it was on. `at: [x,y]`, applied + after `offset`, puts a linear dimension's line through the point, gives an angular dimension's + arc a radius of the point's distance from the vertex (at least 12 points), or turns a radius or + diameter line toward it, keeping what the dimension measures. An update that changes nothing records no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..eac5e220fe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -690,6 +690,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool points on preview bounds corners (#8537):** With Use Preview Bounds on, a Linear point can land on a corner of the preview bounds of a path or compound path with a stroke or effects; the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes measuring a stroked segment by snapping onto its preview bounds. By VectorCraft's own rule, only the four corners are snapped to: a click within 8 pixels of a corner lands on it instead of on the anchor at the same corner of the object's geometric bounds, and any other anchor nearer the pointer takes the point; for an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the size that W and H show. The edges of the preview bounds, a group's own strokes or effects, type and paths made into guides are not snapped to. `with_preview_bounds_points_land_on_the_corners_of_the_stroke`, `preview_bounds_corners_take_picks_as_anchors_do`, `a_corner_takes_only_the_anchor_it_stands_for`, `a_point_is_held_for_a_corner_only_when_picked_on_it` and `hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring` cover it. **Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. +**Drawing tools, Dimension tool moves a dimension already drawn:** As the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes, a drag with the Dimension tool from a dimension already drawn repositions it, as one undo step, keeping what it measures and its link to the art. By VectorCraft's own rule, the part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center; the press must be where the canvas hits the dimension, within 8 pixels; with Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line. `dimension.update` takes `at`. `dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line`, `a_dimension_moved_beside_another_lands_on_its_level`, `a_dragged_dimension_follows_the_part_grabbed`, `a_dimension_is_dragged_only_where_the_canvas_hits_it` and `dimension_update_at_moves_the_line_through_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Dimension tool Arrow Style offers every stroke arrowhead (#8049, #3222):** By VectorCraft's own rule, Arrow Style lists Filled, Open, Tick and None, then the other 38 built-in Stroke panel arrowheads, each with its drawn preview. The options save the head in `arrowHead` (`Barbed`) and keep `arrowStyle` at `filled`, so versions that have the stroke arrowhead but not `arrowHead` keep the saved arrows until they draw the dimension again and then draw Filled arrows (versions without the stroke arrowhead do not open the file); documents and tool settings saved before open unchanged. `every_stroke_arrowhead_draws_as_a_dimension_arrowhead`, `arrow_style_shows_a_stroke_arrowhead`, `arrow_style_list_names_each_style_once` and `built_in_arrowhead_names_are_in_complete_catalogs` cover it. From 011b6fb0e7e7e6bbe08f80ef4a2397109dd54993 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:56:06 -0800 Subject: [PATCH 016/145] Docs: limit the matching-mask rule to a single path holding just the image The relink rule for a clipping mask whose path matches the old file's clipping path applies only when the mask holds just the image and its clipping path is a single path. A mask that also holds other objects, or whose clipping path is a compound path or text, is kept, with the new file's clip group inside it. The kept-mask sentence now excludes the matching masks. Update Links and Relink keep a distorted image's corners and draw the new file's clipping path through them; the PSD clipping-path entry said that Update Links left that clipping as it was. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a44f0aada7..1ebbf85d45 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9023,7 +9023,7 @@ file's composite is drawn through clips the image (a clipping group, its path un clipping path kept as the same area), and `file.place` answers the image's id as `image`, since the Links commands take the image and not the group. `links.update` and `links.relink` clip the image by the file's clipping path again (a plain group holding just the image becomes its clipping group, a new clipping group holds it when no group does, and it goes inside a clipping mask made in the -document, whose path is kept unless it matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no +document, whose path is kept unless the mask holds just the image and its clipping path is a single path, not a compound path or text, that matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no clipping path, a clipping group holding just the image whose path is the old file's clipping path loses that path and stays as a plain group of the image, with its id, name, visibility and transparency (one whose path was given the even-odd fill rule stays as it is). The link shows as modified when a plate file of its own changes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 330330957f..d6acb9a509 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document whose clipping path matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; for a distorted image, they keep its corners and draw the new file's clipping path through them. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document that is not taken for the old file's clip group (as the next sentence describes) are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document that holds just the image, and whose clipping path is a single path (not a compound path or text) that matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From 7f3888c59d165fde691acf4e170ce6246e7db89a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:07:47 -0800 Subject: [PATCH 017/145] Fonts: a rescan clears the version record after it publishes its catalog A rescan of the font folders cleared the record of families whose other versions had been looked for before it walked the folders. A version lookup made during the walk read the old catalog and recorded its family again, so a version the rescan found stayed hidden until the next scan. The record is now cleared after the new catalog is written. - The font gate used by tests: a thread's first SteadyFonts no longer waits for a font change that is itself waiting for guards other threads hold, so a guarded test does not hang when another test queues a change. It still waits for a change under way and for a waiting change that can start. - Tests that check a change waits for a guard now read the gate's own decision, recorded under its lock, instead of the request to change. --- crates/text/src/fontdb/db.rs | 5 ++- crates/text/src/test_fonts.rs | 30 +++++++++++-- crates/text/src/tests/sysfonts.rs | 72 +++++++++++++++++++++++++++---- 3 files changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 046db94dfd..1b8d9cd04d 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -374,8 +374,6 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] fn scan_font_dirs(&self) -> usize { - // Files may have been installed since: other versions are looked for again. - self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); let mut catalog = Catalog::new(); let mut aliases: HashMap> = HashMap::new(); let mut postscript = PostScriptNames::new(); @@ -455,6 +453,9 @@ impl FontDb { let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; + // Files may have been installed since: other versions are looked for again, in this + // catalog. A version lookup made during the scan read the previous one. + self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; *self.postscript.write().unwrap_or_else(|e| e.into_inner()) = postscript; // Faces loaded from a file this scan did not catalog (the font was removed, or its folder diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d8f91f8d50..6dd0ba0449 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -105,12 +105,17 @@ impl Drop for SteadyFonts { /// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for /// any guard, so this thread can wait for one running on another thread while it holds a guard. A -/// thread's first guard waits for the font changes under way or waiting. +/// thread's first guard waits for a font change under way, and for a waiting change that can start +/// now. It does not wait for a change that is waiting for guards other threads hold: the thread +/// waiting for this guard may hold one of them. pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { db.ensure_catalog(); if STEADY.with(std::cell::Cell::get) == 0 { let mut s = steadiness(); - while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + let waits = |s: &Steadiness| !CHANGING.with(std::cell::Cell::get) && (s.changing || (s.waiting > 0 && s.holders == s.holders_waiting)); + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Guard, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.holders += 1; @@ -150,7 +155,10 @@ pub(crate) fn font_change() -> FontChange { font_changers().push(std::thread::current().id()); s.waiting += 1; s.holders_waiting += usize::from(holder); - while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + let waits = |s: &Steadiness| s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 }; + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Change, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.waiting -= 1; @@ -175,6 +183,22 @@ pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec std::sync::MutexGuard<'static, Vec<(std::thread::ThreadId, GateAsk, bool)>> { + static DECISIONS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + DECISIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 08f6584186..b6a1e8c1aa 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -4,6 +4,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::fontdb::fonts_outside; +use crate::test_fonts::GateAsk; use crate::*; const FAMILY: &str = "Sysfont Sans3"; @@ -83,10 +84,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); db.add_font(font) }); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "guarded {guarded}: the other thread's change waits for the guard"); assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); @@ -99,10 +98,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let steady = crate::test_fonts::steady_fonts(&db); std::thread::scope(|scope| { let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "the other thread's change waits for the guard"); let before = db.generation(); assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); let after = db.generation(); @@ -114,6 +111,65 @@ fn steady_fonts_hold_back_other_threads_font_changes() { }); } +/// Whether the first `ask` that the thread `id` made of the font gate waited, once the thread has +/// made it; `None` when `finished` says the thread ended without making it. +fn first_decision(id: std::thread::ThreadId, ask: GateAsk, finished: impl Fn() -> bool) -> Option { + loop { + let done = finished(); + let waits = crate::test_fonts::gate_decisions().iter().find(|(t, a, _)| *t == id && *a == ask).map(|(_, _, waits)| *waits); + if waits.is_some() || done { + return waits; + } + std::thread::yield_now(); + } +} + +/// While a thread holds [`test_fonts::steady_fonts`] and a font change on another thread waits for +/// it, a third thread's first guard does not wait for that change, which cannot start before the +/// first guard is dropped. +#[test] +fn a_first_guard_does_not_wait_for_a_change_that_waits_for_other_guards() { + let db = FontDb::with_font_dirs(vec![]); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let adding = scope.spawn(|| db.add_font(crate::test_fonts::variable_font().unwrap())); + assert_eq!(first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()), Some(true), "the change waits for the guard"); + let guarding = scope.spawn(|| drop(crate::test_fonts::steady_fonts(&db))); + let waits = first_decision(guarding.thread().id(), GateAsk::Guard, || guarding.is_finished()); + assert_eq!(waits, Some(false), "the new guard does not wait for the change that waits for this thread's guard"); + guarding.join().unwrap(); + drop(steady); + assert!(adding.join().unwrap() > 0, "the font is new to this database"); + }); +} + +/// A version of a family looked up while a rescan of the font folders is under way, before the +/// rescan publishes what it found, does not hide a version of that family the rescan found. +#[test] +fn a_version_looked_up_during_a_rescan_is_found_after_it() { + use crate::test_fonts::{TWIN_FAMILY, TWIN_VERSIONS, twin_font}; + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-rescan-versions", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Older.ttf"), twin_font(false).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + assert_eq!(db.load_system_fonts(), 1); + let face = db.face(TWIN_FAMILY, "Regular").expect("the installed face"); + assert_eq!(face.version, TWIN_VERSIONS[0]); + std::fs::write(dir.join("Newer.ttf"), twin_font(true).unwrap()).unwrap(); + let versions = |db: &FontDb| db.versions(&face).iter().map(|f| f.version.clone()).collect::>(); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let rescanning = scope.spawn(|| db.load_system_fonts()); + let waits = first_decision(rescanning.thread().id(), GateAsk::Change, || rescanning.is_finished()); + assert_eq!(waits, Some(true), "the rescan waits for the guard before it publishes"); + assert_eq!(versions(&db), [TWIN_VERSIONS[0]], "before the rescan publishes, only the older file is cataloged"); + drop(steady); + assert_eq!(rescanning.join().unwrap(), 2); + }); + assert_eq!(versions(&db), TWIN_VERSIONS, "the version the rescan found is loaded"); + std::fs::remove_dir_all(dir).unwrap(); +} + /// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] /// held for another database, so a thread holding one can catalog a database that another thread /// is scanning. From 32afba75ae22ba3c79886042a8edec15d490b2a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:15:40 -0800 Subject: [PATCH 018/145] Live Paint: a Cmd-drag cut short keeps the bucket's colors With the Live Paint Bucket active, Cmd lends the Selection tool for a drag. When the bucket was chosen again during a drag of a corner, pie, blend or similar widget, the lent tool canceled the drag as it went back, after the session had already stopped treating the bucket as the lender. With New Art Has Basic Appearance off, the cancel then gave the selected object's appearance to the colors the bucket paints with. The lent tool's last actions now run while the session still counts them as the bucket's, as the Eyedropper's sample for the bucket does. --- crates/engine/src/cmd/paint.rs | 13 +++++++++++-- crates/engine/src/lib.rs | 5 +++-- crates/engine/src/tests/build.rs | 28 ++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 6 ++++++ 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b94a45e4f5..6666a1d7a3 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -373,16 +373,25 @@ impl DocState { } } +/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick? +fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool { + t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET) +} + impl Session { + /// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)? + pub(crate) fn lent_by_bucket(&self) -> bool { + self.lender.as_deref().is_some_and(works_for_bucket) + } + /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the /// sample its click takes before it switches back to the bucket. pub fn bucket_paints(&self) -> bool { - let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET); // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. - self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket) + self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket() } /// The tool the active tool's armed one-shot pick switches back to after its click diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..68067dc697 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -75,8 +75,9 @@ pub struct Session { /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the - /// colors the bucket paints with ([`Session::bucket_paints`]). + /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent + /// is deactivated as it goes back: their paint commands change the colors the bucket paints + /// with ([`Session::bucket_paints`]). pub(crate) back_to_bucket: bool, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b37550d5c5..32a9db4b21 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3493,6 +3493,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample"); } +/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the +/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's +/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance +/// does not replace them. +#[test] +fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() { + let v = ViewInfo::default(); + let mut s = session(); + let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.select_tool("livePaintBucket", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let fill = s.paint.fill.clone(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let cmd = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag"); + assert!(s.in_interaction(), "the corner widget drag is in progress"); + s.select_tool("livePaintBucket", v).unwrap(); + assert_eq!(s.tool_id(), "livePaintBucket"); + assert_eq!(s.paint.fill, fill, "the bucket's fill stays"); +} + /// A gradient stop selected on the selection's gradient is not selected once the Live Paint /// Bucket is active (its proxies show the default paint), and one selected on the bucket's /// gradient is not selected once another tool is chosen. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..4323323e22 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -319,6 +319,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { + let lent_by_bucket = self.lent_by_bucket(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -328,7 +329,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); + // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint + // Bucket's when the bucket lent it ([`Session::bucket_paints`]). + let outer_bucket = self.back_to_bucket; + self.back_to_bucket |= lent_by_bucket; let r = self.deactivate_tool(view); + self.back_to_bucket = outer_bucket; self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { From 6d264b28905a2d0102ae38e0cdb22aa1787a5d05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:27:37 -0800 Subject: [PATCH 019/145] Expand Appearance: Safe Mode skips symbol art of a hidden instance in a group's image The image a group's or layer's raster effect makes leaves out hidden objects and everything in them, as the renderer does. The Safe Mode plug-in check looked into every object of such a group, so a hidden plain symbol instance whose symbol art holds a plug-in effect stopped Expand Appearance of the group. The check now skips hidden objects inside the group's image. The group itself still counts when it, or a group around it, is hidden, since expansion still makes its image. --- crates/engine/src/cmd/effectcmd.rs | 50 +++++++++++++++++++----- crates/engine/tests/plugin_safe_mode.rs | 52 +++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cb399eca1c..2b28cd64ff 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "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, 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)}", + "{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 visible 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,33 +1611,63 @@ 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, and so does -/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's +/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the +/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). 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) -> 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; } - holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)); + holds |= has_own_plugin_effect(c); if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { symbols.push(symbol.clone()); } }); holds - || drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen)) + || (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new())) || 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)) }) } +/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke? +fn has_own_plugin_effect(n: &Node) -> bool { + let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); + n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)) +} + +/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect +/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or +/// a group around it, is hidden. +fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + let mut drawn = vec![]; + n.walk(&mut |c| { + if is_container(c) && !rasterfx::raster_fx(c).is_empty() { + drawn.push(c); + } + }); + drawn.into_iter().any(|g| draws_plugin_effect(d, g, seen)) +} + +/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, +/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object +/// in `n`, and everything in it, as the renderer does. `seen` holds the symbols already looked into. +fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + if has_own_plugin_effect(n) { + return true; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && seen.insert(symbol.clone()) + && d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen)) + { + return true; + } + n.children().into_iter().flatten().any(|c| c.visible && draws_plugin_effect(d, c, seen)) +} + fn expand_appearance(s: &mut Session, p: &Value) -> Result { let roots = edit_targets(s, p, "effect.expandAppearance")?; // In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..98047a2d86 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -506,6 +506,58 @@ fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() { refused(&mut s, &json!(outer)); } +/// In Safe Mode, a hidden plain instance draws nothing in the image a group's raster effect makes, +/// so its symbol art's plug-in effect doesn't stop Expand Appearance of the group; shown, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.hid", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.hid"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let hide = |s: &mut Session, id: u64| { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(vectorcraft_engine::doc::NodeId(id)).unwrap().visible = false; + }; + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + // A blurred group of a visible rectangle and an instance, then one of a visible rectangle and a + // group around an instance; the instance, or the group around it, is shown and then hidden. + for wrap in [false, true] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let mut hidden = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + if wrap { + hidden = s.execute("object.group", &json!({"ids": [hidden]})).unwrap()["id"].clone(); + } + let group = s.execute("object.group", &json!({"ids": [rect, hidden]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap(); + let (hidden, group) = (hidden.as_u64().unwrap(), group.as_u64().unwrap()); + let err = expand(&mut s, group).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + hide(&mut s, hidden); + expand(&mut s, group).unwrap(); + } + // Expansion still makes the image of a hidden blurred group, or of one in a hidden group, so + // a shown instance in it still stops it. + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 20})).unwrap()["id"].clone(); + let blurred = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [blurred], "params": {"radius": 2}})).unwrap(); + let parent = s.execute("object.group", &json!({"ids": [blurred]})).unwrap()["id"].as_u64().unwrap(); + hide(&mut s, parent); + let err = expand(&mut s, parent).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + let blurred = blurred.as_u64().unwrap(); + hide(&mut s, blurred); + let err = expand(&mut s, blurred).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..a6af3a0d23 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13275,7 +13275,8 @@ runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an er object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a -plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as +visible plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. A +hidden instance draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From a84a398a3f7e29e7a84c5a766ae6cde563284c6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:06:07 -0800 Subject: [PATCH 020/145] Expand Appearance: Safe Mode skips symbol art in a template layer of a group's image The image a group's or layer's raster effect makes is drawn with templates skipped, so it leaves out template layers, guides and ruler guides with everything in them. The Safe Mode plug-in check still looked into a template sublayer, so a plain symbol instance there whose symbol art holds a plug-in effect stopped Expand Appearance of the layer. The check now skips them as the renderer does. --- crates/engine/src/cmd/effectcmd.rs | 9 ++++--- crates/engine/tests/plugin_safe_mode.rs | 35 +++++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 2b28cd64ff..c33ebb61d7 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "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, a visible 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)}", + "{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 visible plain instance outside template layers 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 ), @@ -1654,7 +1654,8 @@ fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections: /// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, /// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object -/// in `n`, and everything in it, as the renderer does. `seen` holds the symbols already looked into. +/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does +/// with templates skipped. `seen` holds the symbols already looked into. fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { if has_own_plugin_effect(n) { return true; @@ -1665,7 +1666,9 @@ fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::Hash { return true; } - n.children().into_iter().flatten().any(|c| c.visible && draws_plugin_effect(d, c, seen)) + let drawn = + |c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. }); + n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen)) } fn expand_appearance(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 98047a2d86..c2213a930a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -558,6 +558,41 @@ fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_ assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); } +/// In Safe Mode, the image a layer's raster effect makes leaves out a template sublayer, so the symbol +/// art of a plain instance in it doesn't stop Expand Appearance of the layer; in a plain sublayer, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_layer_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.tpl", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.tpl"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setCurrent", &json!({"id": layer})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap(); + let instance = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].as_u64().unwrap(); + let sub = s.execute("layer.newSublayer", &json!({"parent": layer})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.move", &json!({"ids": [instance], "target": sub})).unwrap(); + s.execute("layer.target", &json!({"id": layer})).unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [layer], "item": null, "params": {"radius": 2}})).unwrap(); + let blurred = |s: &Session| s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(layer)).unwrap().appearance.effects.len(); + assert_eq!(blurred(&s), 1, "the layer has its own Gaussian Blur"); + let expand = |s: &mut Session| { + s.execute("layer.target", &json!({"id": layer})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({})); + safe_mode::set_active(None); + r + }; + let err = expand(&mut s).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + s.execute("layer.setProps", &json!({"id": sub, "template": true})).unwrap(); + expand(&mut s).unwrap(); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index a6af3a0d23..11e8bb47f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13276,7 +13276,7 @@ object's geometry unchanged while the object keeps the effect: `effect.list` giv Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a visible plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. A -hidden instance draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as +hidden instance, or one in a template sublayer, draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From 92c63bb8cf0ae10101da593c47b577e51c8dd470 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:03:29 -0800 Subject: [PATCH 021/145] Expand Appearance: Safe Mode skips raster groups inside a blurred group's image A group or layer whose raster effects are not all shadows and outer glows (a blur, feather or inner glow) becomes one image of what it draws, and the groups and layers in it make no images of their own. The Safe Mode plug-in check still looked into every group with a raster effect inside it, so a hidden blurred group there holding a plain symbol instance with a plug-in effect in its art stopped the expansion. The check now stops at such a group. Under shadows and outer glows the members still expand on their own, so their groups are still checked. --- crates/engine/src/cmd/effectcmd.rs | 20 +++++++----- crates/engine/tests/plugin_safe_mode.rs | 41 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index c33ebb61d7..90176831a4 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1641,15 +1641,21 @@ fn has_own_plugin_effect(n: &Node) -> bool { /// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect /// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or -/// a group around it, is hidden. +/// a group around it, is hidden. A group or layer that paints something and whose raster effects +/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers +/// in it make no images of their own; one that paints nothing makes no image, and its members +/// expand on their own. fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { - let mut drawn = vec![]; - n.walk(&mut |c| { - if is_container(c) && !rasterfx::raster_fx(c).is_empty() { - drawn.push(c); + let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] }; + if !fx.is_empty() { + if draws_plugin_effect(d, n, seen) { + return true; } - }); - drawn.into_iter().any(|g| draws_plugin_effect(d, g, seen)) + if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() { + return false; + } + } + n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen)) } /// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index c2213a930a..6cb261dd0f 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -593,6 +593,47 @@ fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_laye expand(&mut s).unwrap(); } +/// In Safe Mode, a group whose Gaussian Blur makes it one image leaves out a hidden blurred group in +/// it, which makes no image of its own, so the symbol art of a plain instance there doesn't stop +/// Expand Appearance. Under a Drop Shadow, whose members expand on their own, the hidden group still +/// makes its image, so it does. +#[test] +fn expand_appearance_in_safe_mode_skips_a_hidden_blurred_group_that_a_blurred_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.nest", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.nest"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + for (outer, allowed) in [("blur.gaussian", true), ("stylize.dropShadow", false)] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [inner], "params": {"radius": 2}})).unwrap(); + let group = s.execute("object.group", &json!({"ids": [rect, inner]})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": outer, "ids": [group]})).unwrap(); + let inner = vectorcraft_engine::doc::NodeId(inner.as_u64().unwrap()); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inner).unwrap().visible = false; + let r = expand(&mut s, group); + if allowed { + r.unwrap(); + // The blurred group became its image: the hidden group in it was not expanded on its own. + assert!(s.doc().unwrap().doc.node(inner).is_none(), "the hidden group went into the image"); + } else { + let err = r.unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{outer}: {err}"); + } + } +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] From b919dbd66f7a70dd0b56c5dca81d37d83ea32963 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:41:45 -0800 Subject: [PATCH 022/145] Plug-ins: read the manifest from a custom section before running any code A module may carry its manifest in a `vc_manifest` custom section, with `"abi": 1` in place of the `vc_abi_version` export. When it does, Plugin::load parses the manifest from the section and does not instantiate the module: its start function, data segments, `vc_abi_version` and `vc_manifest` do not run when it is inspected, installed or loaded at startup. The host checks the imports against the manifest's permissions, the exports `memory`, `vc_alloc` and `vc_run` by type, and the initial memory and the tables against the limits a run has (at most 4 tables of 100,000 elements). A module with more than one such section is refused, and so is a section over 64 KiB, before its contents are decoded, and a manifest in the section without `"abi": 1`. The host uses the section and does not call a `vc_manifest` export. Modules without the section load as before. The Desaturate example carries the section and keeps the export, and its fixture is rebuilt with Rust 1.100.0. build.sh clears RUSTFLAGS: .cargo/config.toml sets `+simd128` for wasm32, and the host refuses SIMD instructions. wat::sectioned builds test plug-ins with the section. --- crates/engine/src/tests/plugins.rs | 17 ++ crates/engine/tests/plugin_fuzz.rs | 12 +- crates/plugins/example/build.sh | 4 +- crates/plugins/example/src/lib.rs | 20 +++ crates/plugins/src/manifest.rs | 6 +- crates/plugins/src/runtime.rs | 160 +++++++++++++++--- crates/plugins/src/wat.rs | 51 +++++- crates/plugins/tests/abi.rs | 126 ++++++++++++++ crates/plugins/tests/fixtures/desaturate.wasm | Bin 60341 -> 63851 bytes crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/plugins.md | 33 +++- docs/target-app-parity.md | 1 + 36 files changed, 539 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..2c6026c85d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2017,6 +2017,23 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed +/// without any of its code running: its start function traps and its `vc_manifest` export loops. +#[test] +fn a_plugin_with_a_manifest_section_installs_without_running() { + let mut s = session(); + let id = "test.engine.section"; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","abi":1}}"#); + let extra = r#"(func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0)) (func $trap unreachable) (start $trap)"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::sectioned(&manifest, tpl::ECHO, extra, 1)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert_eq!(inspected["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "inspecting installs nothing"); + assert_eq!(run(&mut s, "plugin.install", json!({"dataBase64": data}))["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn invalid_install_flags_are_refused() { let mut s = session(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..d0b99e3efe 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1,6 +1,6 @@ -//! Untrusted plug-ins never crash the app: mutated and garbage modules handed to `plugin.install`, -//! and plug-ins returning hostile output (random JSON in the object model's shape: huge or -//! malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object +//! Untrusted plug-ins never crash the app: mutated and garbage modules, and modules whose +//! `vc_manifest` custom section holds garbage, handed to `plugin.install`, and plug-ins returning +//! hostile output (random JSON in the object model's shape: huge or malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object //! filters (`plugin.run`) or live effects (`effect.apply`), and plug-ins running bulk memory //! instructions (`memory.fill`, `memory.copy`, `memory.init`, `data.drop`) on ranges in, at and past //! the ends of memory and the data segment, under small and default budgets. Each run must end as @@ -620,7 +620,11 @@ proptest! { } let mut s = rich_session(); s.execute("select.all", &json!({})).unwrap(); - for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone()] { + // A module whose `vc_manifest` custom section holds the garbage. + let section = tpl::custom_section(vectorcraft_plugins::manifest::MANIFEST_SECTION, &garbage); + let sectioned = tpl::with_field(&tpl::module(&tpl::manifest("fuzz.section", "filter", "{}"), tpl::ECHO, "", 1), §ion).unwrap(); + let sectioned = wat::parse_str(sectioned).unwrap(); + for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone(), sectioned] { let r = catch_quiet(|| { if let Ok(info) = install(&mut s, &module) { let _ = s.execute("plugin.run", &json!({"id": info["id"]})); diff --git a/crates/plugins/example/build.sh b/crates/plugins/example/build.sh index 1bedbc2fb0..614f683613 100644 --- a/crates/plugins/example/build.sh +++ b/crates/plugins/example/build.sh @@ -3,7 +3,9 @@ # Needs the wasm32-unknown-unknown target: `rustup target add wasm32-unknown-unknown`. set -eu cd "$(dirname "$0")" -cargo build --release --target wasm32-unknown-unknown +# An empty RUSTFLAGS replaces the `+simd128` flag that the repository's .cargo/config.toml sets for +# the web build: the plug-in host does not accept SIMD instructions. +RUSTFLAGS= cargo build --release --target wasm32-unknown-unknown out=target/wasm32-unknown-unknown/release/vectorcraft_plugin_desaturate.wasm cp "$out" ../tests/fixtures/desaturate.wasm echo "built $out ($(wc -c < "$out") bytes) -> crates/plugins/tests/fixtures/desaturate.wasm" diff --git a/crates/plugins/example/src/lib.rs b/crates/plugins/example/src/lib.rs index a1b08d8696..d5451860c5 100644 --- a/crates/plugins/example/src/lib.rs +++ b/crates/plugins/example/src/lib.rs @@ -12,6 +12,7 @@ const MANIFEST: &str = r#"{ "name": "Desaturate", "version": "1.0.0", "kind": "filter", + "abi": 1, "author": "VectorCraft contributors", "description": "Moves the colours of the selected paths towards grey; an example of the plug-in ABI.", "params": { @@ -19,6 +20,25 @@ const MANIFEST: &str = r#"{ } }"#; +/// The manifest in the `vc_manifest` custom section, where the host reads it, with its `abi` +/// version, without running any of the module's code. The `vc_manifest` export below returns the +/// same text for hosts that read only the export. +#[used] +#[unsafe(link_section = "vc_manifest")] +static MANIFEST_SECTION: [u8; MANIFEST.len()] = section_bytes(); + +/// `MANIFEST` as a byte array, which `link_section` needs. +const fn section_bytes() -> [u8; N] { + let text = MANIFEST.as_bytes(); + let mut out = [0; N]; + let mut i = 0; + while i < N { + out[i] = text[i]; + i += 1; + } + out +} + #[unsafe(no_mangle)] pub extern "C" fn vc_abi_version() -> u32 { 1 diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..899cdb9152 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -10,6 +10,9 @@ use crate::{Error, Result}; /// Longest manifest the host reads. pub const MAX_MANIFEST_BYTES: usize = 64 * 1024; +/// The name of the custom section a module may carry its manifest in, so the host reads it +/// without running any of the module's code. +pub const MANIFEST_SECTION: &str = "vc_manifest"; /// Most parameters a plug-in may declare. pub const MAX_PARAMS: usize = 256; /// Most parameters outside groups (`group`): a dialog of more is sorted into sections. @@ -299,7 +302,8 @@ impl ParamSpec { } } -/// The manifest a plug-in returns from `vc_manifest` (UTF-8 JSON). +/// The manifest a plug-in carries in its [`MANIFEST_SECTION`] custom section or returns from +/// `vc_manifest` (UTF-8 JSON). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Manifest { diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..853fe5def0 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -1,13 +1,13 @@ //! The wasmi host: loading, instantiating and calling a plug-in under resource limits. use wasmi::{ - Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, - WasmParams, WasmResults, + Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, + Val, ValType, WasmParams, WasmResults, }; use wasmparser::{Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -198,10 +198,96 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none. +/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`], +/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must +/// give the ABI version as `abi`, in place of the `vc_abi_version` export. +fn section_manifest(module: &Module) -> Result> { + let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION); + let Some(section) = sections.next() else { + return Ok(None); + }; + if sections.next().is_some() { + return Err(Error::Manifest(format!("the module has more than one `{MANIFEST_SECTION}` custom section"))); + } + let manifest = Manifest::parse(section.data())?; + // `Manifest::parse` has checked that the section is UTF-8 JSON of at most `MAX_MANIFEST_BYTES`. + let abi = serde_json::from_slice::(section.data()).ok().and_then(|v| v.get("abi").and_then(serde_json::Value::as_i64)); + if abi != Some(i64::from(ABI_VERSION)) { + return Err(Error::Abi(format!( + "the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements" + ))); + } + Ok(Some(manifest)) +} + +/// Most tables a module may define: the store an instance runs in holds no more. +const MAX_TABLES: u64 = 4; +/// Most elements a table may hold: the store an instance runs in holds no more. +const MAX_TABLE_ELEMENTS: u64 = 100_000; + +/// The number of tables the module in `bytes` defines and the largest initial size among them, +/// from its table section, or `None` when its sections can't be read. `bytes` is a module +/// [`check_features`] has validated. +fn table_sizes(bytes: &[u8]) -> Option<(u64, u64)> { + for payload in wasmparser::Parser::new(0).parse_all(bytes) { + if let wasmparser::Payload::TableSection(reader) = payload.ok()? { + let count = u64::from(reader.count()); + let mut largest = 0; + for table in reader { + largest = largest.max(table.ok()?.ty.initial); + } + return Some((count, largest)); + } + } + Some((0, 0)) +} + +/// Checks the tables the module in `bytes` defines against the store's limits ([`MAX_TABLES`] +/// tables of at most [`MAX_TABLE_ELEMENTS`] elements), which instantiating it checks. The host +/// offers no tables to import, so the module defines every table it has. +fn check_tables(bytes: &[u8]) -> Result<()> { + let Some((count, largest)) = table_sizes(bytes) else { + return Err(Error::Module("the module's table section could not be read".into())); + }; + if count > MAX_TABLES || largest > MAX_TABLE_ELEMENTS { + return Err(Error::Limit(format!( + "table budget (the module defines {count} tables, the largest with {largest} elements; limit {MAX_TABLES} tables of {MAX_TABLE_ELEMENTS} elements)" + ))); + } + Ok(()) +} + +/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. +fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { + use ValType::{I32, I64}; + let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); + let Some(ExternType::Memory(memory)) = export("memory") else { + return Err(Error::Abi("the module must export its linear memory as `memory`".into())); + }; + // Pages are 64 KiB: the engine's configuration leaves custom page sizes off. + let initial = memory.minimum().saturating_mul(1 << 16); + if initial > max_memory_bytes as u64 { + return Err(Error::Limit(format!("memory budget (the module's initial memory is {initial} bytes, limit {max_memory_bytes})"))); + } + let wanted: [(&str, &[ValType], &[ValType], &str); 2] = + [("vc_alloc", &[I32], &[I32], "(param i32) (result i32)"), ("vc_run", &[I32, I32, I32, I32], &[I64], "(param i32 i32 i32 i32) (result i64)")]; + for (name, params, results, signature) in wanted { + if !matches!(export(name), Some(ExternType::Func(f)) if f.params() == params && f.results() == results) { + return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); + } + } + Ok(()) +} + impl Plugin { - /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and - /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) - /// and its manifest allows. In Safe Mode nothing is loaded ([`Error::SafeMode`]). + /// Validates and loads a module: reads the manifest, checks that each host import it asks for + /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the + /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is + /// checked without being instantiated, so none of its code runs; one without that section is + /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded + /// ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { @@ -222,22 +308,31 @@ impl Plugin { let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let deadline = Deadline::new(p.limits.wall_time_ms); - // The manifest isn't read yet: every host import is linked, what it reports is dropped and - // there is no storage to reach. - let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?; - let version: TypedFunc<(), i32> = live.func("vc_abi_version")?; - let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?; - if v != ABI_VERSION { - return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}"))); - } - let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?; - let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?; - let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e { - Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")), - e => e, - })?; - p.manifest = Manifest::parse(&text)?; + let live = match section_manifest(&p.module)? { + Some(manifest) => { + p.manifest = manifest; + None + } + None => { + let deadline = Deadline::new(p.limits.wall_time_ms); + // The manifest isn't read yet: every host import is linked, what it reports is + // dropped and there is no storage to reach. + let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?; + let version: TypedFunc<(), i32> = live.func("vc_abi_version")?; + let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?; + if v != ABI_VERSION { + return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}"))); + } + let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?; + let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?; + let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e { + Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")), + e => e, + })?; + p.manifest = Manifest::parse(&text)?; + Some(live) + } + }; host::check_granted(&p.manifest, &imports)?; // A heavy filter's runs get the larger budget the host allows for one, which the host // lets the user allow or refuse before installing it. @@ -246,8 +341,16 @@ impl Plugin { p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); } // The other exports must exist with the right types. - live.func::("vc_alloc")?; - live.func::("vc_run")?; + match live { + Some(live) => { + live.func::("vc_alloc")?; + live.func::("vc_run")?; + } + None => { + check_exports(&p.module, p.limits.max_memory_bytes)?; + check_tables(bytes)?; + } + } Ok(p) } @@ -294,8 +397,13 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { - let limits = - StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); + let limits = StoreLimitsBuilder::new() + .memory_size(self.limits.max_memory_bytes) + .memories(1) + .tables(MAX_TABLES as usize) + .table_elements(MAX_TABLE_ELEMENTS as usize) + .instances(1) + .build(); let mut store = Store::new(&self.engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 936d5d9e53..fbb93f6e51 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -7,12 +7,25 @@ const OUTPUT_AT: usize = 0x1_0000; /// `s` as the body of a WAT string literal (every byte that isn't a letter, digit or space /// escaped). pub fn string(s: &str) -> String { - s.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect() + bytes(s.as_bytes()) } +/// `data` as the body of a WAT string literal, every byte that isn't an ASCII letter, digit or +/// space escaped (so it may hold any bytes, UTF-8 or not). +pub fn bytes(data: &[u8]) -> String { + data.iter().map(|&b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect() +} + +/// `vc_alloc`, which grows memory by whole pages, so its blocks never overlap data segments. +const ALLOC: &str = r#"(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32) + (local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16)))) + (if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))"#; + /// A plug-in module: `manifest` (JSON), a `vc_run` whose body is `run` (parameters `$in $il $pp /// $pl`, result i64), extra module fields `extra` and `pages` of initial memory. `vc_alloc` grows -/// memory by whole pages, so its blocks never overlap data segments. +/// memory by whole pages, so its blocks never overlap data segments. The manifest comes from the +/// `vc_manifest` export, which the host calls when it loads the module ([`sectioned`] carries it in +/// a custom section instead). pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { format!( r#"(module @@ -21,9 +34,7 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { (data (i32.const 16) "{data}") (func (export "vc_abi_version") (result i32) (i32.const 1)) (func (export "vc_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 16))) - (func (export "vc_alloc") (param $n i32) (result i32) (local $old i32) - (local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16)))) - (if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536))))) + {ALLOC} (func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64) {run}))"#, data = string(manifest), @@ -31,6 +42,36 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { ) } +/// A custom section named `name` holding `data`, as a module field. +pub fn custom_section(name: &str, data: &[u8]) -> String { + format!(r#"(@custom "{}" "{}")"#, string(name), bytes(data)) +} + +/// A plug-in module like [`module`] that carries `manifest` in its `vc_manifest` custom section +/// ([`crate::manifest::MANIFEST_SECTION`]) and exports only `memory`, `vc_alloc` and `vc_run`: the +/// host reads the manifest without running any of its code. The host loads it only when `manifest` +/// gives `"abi": 1`. +pub fn sectioned(manifest: &str, run: &str, extra: &str, pages: u32) -> String { + format!( + r#"(module + {section} + {extra} + (memory (export "memory") {pages}) + {ALLOC} + (func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64) + {run}))"#, + section = custom_section(crate::manifest::MANIFEST_SECTION, manifest.as_bytes()), + ) +} + +/// `module` (a module in WebAssembly text that starts with `(module`, after any white space) with +/// the module field `field` added first, such as a [`custom_section`]; `None` when `module` does not +/// start with `(module`. +pub fn with_field(module: &str, field: &str) -> Option { + let rest = module.trim_start().strip_prefix("(module")?; + Some(format!("(module\n {field}{rest}")) +} + /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..aa6c3ad2f0 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -6,6 +6,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; +use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; @@ -488,6 +489,131 @@ fn host_imports_are_checked_when_a_module_is_loaded() { assert_eq!(plain.run_reporting(INPUT.as_bytes(), b"{}", plain.limits()), (Ok(INPUT.as_bytes().to_vec()), Report::default())); } +/// A start function that traps: a load that instantiates the module fails with it. +const TRAPPING_START: &str = "(func $trap unreachable) (start $trap)"; + +/// [`MANIFEST`] with the ABI version, as a `vc_manifest` section must give it. +const SECTION: &str = r#"{"id":"test.plugin","name":"Test","version":"1","kind":"filter","abi":1}"#; + +/// `module` with a `vc_manifest` custom section holding `data`. +fn with_section(module: &str, data: &[u8]) -> String { + tpl::with_field(module, &tpl::custom_section(MANIFEST_SECTION, data)).expect("module text") +} + +/// Asserts that each case's module is refused with an error that contains its text, and lists every +/// case that is not. +fn assert_refused(cases: &[(&str, String, &str)]) { + let wrong: Vec = cases + .iter() + .filter_map(|(name, src, says)| match Plugin::load(&build(src), Limits::default()) { + Err(e) if e.to_string().contains(says) => None, + other => Some(format!("{name}: {other:?}")), + }) + .collect(); + assert!(wrong.is_empty(), "not refused as expected:\n{}", wrong.join("\n")); +} + +/// A module that carries its manifest in a `vc_manifest` custom section loads without any of its +/// code running: not its start function, not `vc_abi_version` and not `vc_manifest`. Its runs +/// instantiate it as before. +#[test] +fn a_manifest_section_is_read_without_running_the_module() { + let exports = r#"(func (export "vc_abi_version") (result i32) unreachable) + (func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0))"#; + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, &format!("{exports} {TRAPPING_START}"), 1)), Limits::default()).unwrap(); + assert_eq!(p.id(), "test.plugin"); + assert!(matches!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Trap(_))), "a run still runs the start function"); + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, exports, 1)), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + +/// A module with the section needs neither `vc_abi_version` nor `vc_manifest`, and when it also +/// has a `vc_manifest` export that says otherwise, the section is the manifest. +#[test] +fn the_manifest_section_needs_no_manifest_export_and_wins_over_one() { + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, "", 1)), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); + let exported = r#"{"id":"test.exported","name":"Exported","version":"1","kind":"effect"}"#; + let p = Plugin::load(&build(&with_section(&tpl::module(exported, tpl::ECHO, "", 1), SECTION.as_bytes())), Limits::default()).unwrap(); + assert_eq!((p.id(), p.manifest().kind), ("test.plugin", Kind::Filter)); +} + +/// The section's manifest gives the ABI version as `abi`, which the host checks in place of the +/// `vc_abi_version` export: left out or another version, the module is refused, whatever its +/// export returns. +#[test] +fn a_manifest_section_must_give_the_abi_version() { + let says = "must give `abi` as 1"; + let version_1 = tpl::module(MANIFEST, tpl::ECHO, "", 1); + let version_2 = version_1.replace("(result i32) (i32.const 1)", "(result i32) (i32.const 2)"); + assert!(load_err(&build(&version_2)).contains("vc_abi_version returned 2")); + assert_refused(&[ + ("left out", with_section(&version_1, MANIFEST.as_bytes()), says), + ("2", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":2"#).as_bytes()), says), + ("a string", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":"1""#).as_bytes()), says), + ("a fraction", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":1.5"#).as_bytes()), says), + ]); + // The section's version is the one the host checks. + let p = Plugin::load(&build(&with_section(&version_2, SECTION.as_bytes())), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + +/// A `vc_manifest` section that is repeated, too long, not UTF-8, not JSON or not a valid manifest +/// is refused, even when the module's `vc_manifest` export returns a valid one. +#[test] +fn hostile_manifest_sections_are_refused() { + let base = tpl::module(MANIFEST, tpl::ECHO, "", 1); + let with = |data: &[u8]| with_section(&base, data); + let long = format!(r#"{{"id":"test.long","name":"Long","kind":"filter","abi":1,"description":"{}"}}"#, " ".repeat(MAX_MANIFEST_BYTES)); + for (name, src, says) in [ + ("repeated", with_section(&with(SECTION.as_bytes()), SECTION.as_bytes()), "more than one"), + ("too long", with(long.as_bytes()), "(limit "), + ("not UTF-8", with(b"{\"id\":\"\xff\xfe\"}"), "not UTF-8"), + ("not JSON", with(br#"{"id":"test.plugin","#), "manifest"), + ("empty", with(b""), "manifest"), + ("a bad id", with(br#"{"id":"a b","name":"x","kind":"filter","abi":1}"#), "invalid id"), + ("an unknown kind", with(br#"{"id":"a","name":"x","kind":"panel","abi":1}"#), "manifest"), + ] { + match Plugin::load(&build(&src), Limits::default()) { + Err(Error::Manifest(e)) => assert!(e.contains(says), "{name}: {e}"), + other => panic!("{name}: {other:?}"), + } + } +} + +/// A module with the section has its imports checked against its manifest, its exports by type, +/// and its initial memory and tables against the limits its runs have, before any of its code runs +/// (its start function would trap). +#[test] +fn a_sectioned_module_s_imports_and_exports_are_checked_before_it_runs() { + let call = r#"(import "env" "vc_call" (func (param i32 i32 i32 i32) (result i32)))"#; + let level2 = LEVEL2.replace(r#""api":2"#, r#""api":2,"abi":1"#); + let e = load_err(&build(&tpl::sectioned(&level2, tpl::ECHO, &format!("{call} {TRAPPING_START}"), 1))); + assert!(e.contains("imports `env.vc_call`") && e.contains("the permission `commands`"), "{e}"); + let sectioned = tpl::sectioned(SECTION, tpl::ECHO, TRAPPING_START, 1); + let tables = |t: &str| tpl::sectioned(SECTION, tpl::ECHO, &format!("{t} {TRAPPING_START}"), 1); + assert_refused(&[ + ("no memory", sectioned.replace(r#"(memory (export "memory") 1)"#, "(memory 1)"), "export its linear memory as `memory`"), + ( + "initial memory past the cap", + tpl::sectioned(SECTION, tpl::ECHO, TRAPPING_START, 60_000), + "exceeded its memory budget (the module's initial memory", + ), + ("no vc_alloc", sectioned.replace(r#"(export "vc_alloc")"#, ""), "must export `vc_alloc` with the type (param i32) (result i32)"), + ( + "vc_run of another type", + tpl::sectioned(SECTION, "(i32.const 0)", TRAPPING_START, 1).replace("(param $pl i32) (result i64)", "(param $pl i32) (result i32)"), + "must export `vc_run` with the type (param i32 i32 i32 i32) (result i64)", + ), + ("five tables", tables(&"(table 0 funcref) ".repeat(5)), "exceeded its table budget (the module defines 5 tables"), + ("a table too large", tables("(table 1 funcref) (table 100001 200000 externref)"), "the largest with 100001 elements"), + ]); + // At the limits, it loads and runs. + let at_limits = tpl::sectioned(SECTION, tpl::ECHO, "(table 100000 funcref) (table 0 funcref) (table 0 externref) (table 2 3 funcref)", 1); + let p = Plugin::load(&build(&at_limits), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + /// Progress is clamped and passed on to the caller's sink as a share; the run's last report is kept. #[test] fn progress_reports_are_clamped_and_reach_the_caller() { diff --git a/crates/plugins/tests/fixtures/desaturate.wasm b/crates/plugins/tests/fixtures/desaturate.wasm index a8b4cdf0726ecffd2ce24d0e00768e44e4672d5d..730ec3554581ea4f7691a5fac5b5f9d5ea922d7c 100644 GIT binary patch literal 63851 zcmdqK3!Gn7dGEc~zWnbq^A8LVNPs>6rZ|y=1cfAAD%m4)m5TLpwCyPj$pD!Nxy(!= z)R+tqF>Pr}t*vO$qM{%|#g?8@i#2W0m$tO!wAR`dE48-uRBJh>dg?i%Ip5#2*8X26 zA!xPl`+iO)Gkfo~*X3EyZ9VH*&ssa0oV&qAQRF`CmR;@kMOVlB_PKpmC;RNeLqsYG zQAmugPI+bd_K2?zQq<_D0FCxsSLst0akw5`OrXRQPpqC8_W~sV22bHL18tz0piaB&ju& z)P|z8Iy_QMTzd)shTG(e(j?B(V~!n7D%GJVQkAibhK@Vl#ns_q=c=jw8y$7dolxPO zi(C>ftyH2)mQ||yH(YT^GOT8!YIQV81P>{dYLvtjAc21;#wVqj+u`y&1L!4{I;brc z77j+u>JMa<8>Vj9K6_If4e#D`)#No>uG&2{JGW)~w&=2&61HyLzA3uA$?Xl3+qPUg zH8&rr+c4k{QNiLkGON3+Z%7pqt#JV9C8;AMMX5y%%hcYH0IhjFDxuX zooFIjAGh)-ckAOcr=@jqlt;}=T)gl5$gmIdUy ziH|EWqW+>i9SXSS&0w^w>B(rOlY}=(5v_}t=1Cr}i$}T8ZaYtk1$S<=oGUL|c`~79 z+XfhE>2&+nvR&V!i-sbKMk|x{`ed!YtF2GQ{av&^$tiXIv@g2f7X|2Kb##6qY~;y! zym2gUxu(*7KxvN5$FGYov@-m8EShe=StZ9}b?gw}fgS;!@;0At-=>$8A6Ej{Xum}X zyn8YVNNE1m(zv=W*&ERLq?_r)0SR$&pPSBIy9-;q@jLs;d(`XsF8dAGoS3U*Q^a{VLal>o>U8xL!F;r*{^O zONZ)tTr}3j8*;}_Txc`j-#IYI^RvI_v;){mb)FWoGq$gbaPM~qprnc50?Oer5giCn0b^;n zb+cm`w;L?6;_pbS7J#0>g#GMYvg$=cjUIQVo>lL60-{qZJ`2}Hq$P#hiG0?IRTo2i z*UuhDsC1~+tFfkA>icXY0gsF04&%U7ND$BV3kMXllT=-yvER(O80PHj8vD;~s3S6p4{4 zk(lJ_2Z&fq##_~sq*w9rC=UeMaJICuen*C9_Y}|;z z_vFt|lZY9U9y3y0fNl^g3awpM+}M7nZ&t7GbDgxvG?L3v}kNX zxkH#*7tgmW1t|9Lg3COY?A&NaDEW{x4&%jE|9&&&&?*msVU;(Gr|W2$*Uv=4xKQy+ zB`Vb69W>~nhURhc1APwoh}m#k0jwA=Cc%60MGx~+PxBM2VXb7h?=o;+O{Gsau%+#+<=Hn&Kk z(Y}wgJ;7T{+E#>+894di;oaVW0NTiBG!X>ZYYf z2lP_BQD`0(uPdgePE_F$ zG+ffE=*76k6z4}IwY4%CpV;?9v;$Gb!%YbYDlnCtsUwRne zu0$UQHTwb*d1WV&k^XPruJS;O%6DTB#pO<8Z^<#@)IRG^+`(vXrYRK#!KRy}f5NAi zT=PkBjg6K^=Ngbpn}b{fNB5@zs+3_D4z-3NuL`v#x7w{ArH?YQCSI8zfqV1n%Z#xf z04E-&8W@Vh`KnYuS3(!qfv)Fh_w%_Rpc_C%#oGrZ-BBTd?C6z1c9c!zA$cycTjS+R z>PNs|rW$)R2fEdfD5t>;NyNN=E<+b$Q`F`lZGUGrfu+e#XsJ)dx4}NprDw3h@2Rvp z)r`k^pRB5~CtW$WxW&0_pAoo&K`54bCn+E`jnNb@vINSRH^R0a&Gc?~7KiDlG$ zX(U-NdC>fJICIX$iA_J5D0&U8$*v}5{0S2?rD!5)g4t|K7a~|_$^T+1eJPce(`9Mo zD9rDg$J>iypCuwIHp^=^R~$Ki*^04x^J-?mC8XmqQ*QnY$B`4gZT>9TFgOLs&zi~+ zc2`Gfkr>e|m(gc4L?Vqt%XVbQ|GUl5Y17M_zIhCX1 z`=*uLKIDrsg&B)9M3#7|6-xtNcHj>1s4n(Qs}D(W<4$b7w9p(e+1W{!} zcL9CWsTOzY5i~N>qfAqP38*hT(hn3SR?*su{Ex@Cqd1B?V$nC4gL=7i>$GQ(LZcXy zn7r&{71s#}qAL!OlG<4WKP)D|4UOa}y+X}@NnBD=Gw;_IngAPj4SGbRi(B1cvEAq6 z7z(MYqhYvFmccif_en!Vnx&iOMU%?G6c?kVE5}q<@Z{LQEtg68qY+w+;;Uo+iAo%t z9@)%jzlaJo1ezEgVxZ)_o>tY^9ll28=m*ou5hLM~&4=+(ED?NCh&>3U`^|*Ij5^Xg z%oeYMp@%agMpodFa%%jSmQF)|tnJWde~V+z*QkydO3Z{o|1L(|qHNS36$|E4iJNeU zjacfxhN*no%W3m8VM@GggNn2xD)hI6L73QiEtW^khg{EB2wx<=v`1sIkt$+&FyT6Y zvk7X{{-`RE_pT-HRlu|(EBClGR!8OrK(9*E#S%cd`&7Ih5GJv}kQP?L|*&v^iS7xY(f)jZQuVT))iKzXkFyb*pPuip=NM7ioY?X<9a$dmT z46eS%Lw))Dbb}#tAe#Z16|eBlz&eVaTKkK63?5#rANo#(VWEO)Qbh}2IsM?oA$RK- zt}x-DF8b2hYMyF{t#^CqaeOJ{M>9^$@Nkij>TzmK(@bSwAYx6S08gYDsWzj)(#5`OPP)irgak8 z&va$tf&&zg(5@|o_FtQEy=T|;IJ*RX@TyTjW{NRt+R4yuWd^981 zYTnePkvCUj+qNd&``Ce>({Ja^6NkR}jeq->&wc#R-aUD1;^~hc`j(!r+Owahrylw5 zpZ~;9z5Q37iu$wZ&AvC^I6 z)5EnYTEFJ%jfmX5c{gd9jQI-KGcFOdYqTm6m_@*}1WbVArvwMhj*5Ld?c1&Ubv-;4 zg(u_eHQ~X$CbjTj!)z-&nCqeu9&7|03J=gWF6!aIMuAaj_n%f2`;_|#2o(zz3;01i?2UOutJ{_7f>|PZ zr~OvLH#ou97#ZJy_xrd3Rew(&%DF>pt(nF)3)4h~f^*vGe_N&L{u*q+K6ZplBj5L4=va(1Zd7**t z(cd_TRx8y*YH44#w7(51gQ@rth+#I*kzSbEQO!>b)Z%M?Y9P&{&c=Wqwghk2Qrp?H z%$a8e3ycgJVcNf9%7aRntqb*d7Z^_P&1;g5vBB^!s{)$k%wEb%j-t!sXB*On3|2-i znIyqBe5K8fZ5oFQL-SXg^0q&z#;imT1Dhc;%rRL3vtbR!?t;ICG0%V_Cjl59!1Rjt9WICF2VZd0KdmsjK9Lyr3Pq64Y1e| zbw*@WaSwXb-pIXj964$>j1)}`0cmkN-5ln62iGdgg6eCl$n+9}*ihXn-Z(uR#|}Yg z6*mbhX|X>PW08ttm9aWdp`i|cm5tS#?VAlvHO+_Lny{b>&<8M}!S24fK%jWK)3mon zw@yQtN60GR1=>_rLe&xVlXM9m%b$qZMpC##^fvfA49>MBiv&h#7A@I*st{|#{0xi& z70h4&fkpCW`z->Gs?E>9%Nl71LR#H`V&=LsS-U=F?Z<96td9?d+l}kBNMwZAAFj9S z71U*k$%uVGS7^VWtJp{jji^SuyOFYMr}^`BmIPB&5+02G*0@@VA7<%+^(ni5l>58G z{bSs-=0v)d*laCwNCbug`N;bC)m)ewU1~S!o4XX`)`iD=#agd0C+ig9QFrX&h%p*Gihu zLae2V157Rbu$cil*$pC3&663_7a#s=R~6cyX7_V*XqsWdsumzT#8nIs99n zX38p_@0d@gB4?wK9Ae53nYa9akArwxD!ODi5f-ug4#mp^1s0K1o3|iufMwK$iAmnZ zA@CEW+w?@2Iq6Zt!|O-Mu8w3Rj< zU*gA*AnIC}giFDw=1EPEa2QyvmN3{Xn#JuO1-tEl!QuhKac~b8&zh-LK0TqF#oFRo zD^b$nE=$de+s(0DrrvHeJG*$y=u@VOW{X+`U#9Q!L3Jl@k!jKXaV(5o{Ue&jF$>{v zV=YSH51|Q@ak!WBv8_P^Qad%Oeyg?uob@uj)bYxSHTO zU8S7x+EJ}>G5CB1lm0r0b<@WFy0wu@urV({A>nS2+({wntyf4Tlm@TCWp`#gc1KXLw;xKj+Mu4nt9UZCHiaZzr`;R;@#B+VijWm-m)8#mIz zn)z#1N8C9xM@&vp^0nY7I+Alop!*7X4j)$BJZgh;M^t9qI6Y~%-z^cAzrw~5?}BUp zvL(u@lvM}aCA!?V&_-Gbx?AsM)3nB9%E-7WqfiFTN^gHcu&WUT#z%sbG%CH$6qm}% z4)jY1Um2YhBHqU1tJg&r__XsB`$pHuFdp9pOiWdRDQs2y^*{|7u{dp&zpUVbiMZ5b zM2-}p15xIZcG6|*80#$>NvqXNd|vL0DO>?@y0}9-7y1kveFoOCRlR~7cy|_0D=fCi z5E9D(iHozQ+wUnc-R`8eZjPjZ3y%a?+p9w#0_a&w-FjU&BIrk%9jGe^f&MIS|Aep5 z@FcDvSud`ZX&kzk+^f(n#ey0-my-=eZQW8x)`CR{bjh?JGKC1D{Z4eslY6}hEiUe# zWaOD&j9mw=(b7)W&H7^l z)5hM6+dD%-oTsfoEngQAB8`rXM`34>U{RhpK~_eYc;4<>dX@C1b(?$DGocR?IxvFk z26STZK4!cDSFunRW7Wf6VI@NMt@bAZYM8O`Xp*B~93Fdf_-A64XT^z1_!pqFg|TBbC;X;bp=7N~g9bikfTS+0Xq&-mNkIBVwxz5#zdTetIyf@-KN;v+ zAWT%0$*=cCfl3*&wgzkQowRIoVc_ogwOEV{<~>+xpv0lKI2yZ|c{ZW&kPiqM z6L7(q(G~RP%;@E}q6L$UENJZ!(_o$|2EeLXSa|0L{^`Si=Uzoch|WYb@y>FcjD^C7 z;11F;(K^}0?!9@s#~OvD(|h4*tOG1$MG&OajaZ6h4aGnrB=fJfAC}I5)Pp6L)fEzn z)zQnD%X(N0x-s*t`(7;k?q94~pee0xjojM4mwH6jjD&X>xUcE3%Vb0?t7E|vg78eJ z5{R=#6wRXy!qDKZohM_R~#O|G}I~xq)8ecMcuq$O11z}Q14Z+XMF_I z7PzGH+A_%EAD0x&E_ke>v0;f~3GNJ{FLo}Yw9FrTMDa#2l}#7N$#WyFr|*QhV877@ z>n9}U6;@j${Fir{3g}IWQ+IVLbMl2$iuz?NAW`Wz#&8BdqSa2MZkvw^}Y4)o1twPJxZLWUv zm}%14D^n!kC$G(PSeg?Cpy}GY>MM|d5n@d>9ydV;06f~!w?gz45$;{o2tNJ%qXcb?1RcgBU&innQ5NhjnQwoRe6gCO>w#Q{h>NpF#TGplMH#} zsi&xRTeUOsH7Gu`2nw=8Y}|9i$~2+-(ye2#3F8pO9T*h{ffZ}|!~IQ5#E#H*9R#}e z`_u|m^CYtv;SG6fGM4e}S@edmsOUXS__oMIU>lQhlMdi572=k1MXM) zf$O%{LpRWfXB0)%tNMY%u^~)&?6cyDGQy*xwo(QNZx1v0VGql)SW8Xb28SP_i#yzp z^M(v7e1_a-Sk4pgmV(t_Iy0oa$2ZM7WGB*+FdAUgb2X^isYSY@VO=$K#}JX+kYIr7 zPt7xuy*R?4(=AXubOfv&UN@}QC8>xex^HBOi!j!HC}21!BgQC6cLbhCzt+@4>vK2b zVnRUU6i+;Xbq_p+7U`}+A=^H#^P#6qtzcS8w9T(vWC zR!2V}^{VDjiHy0cBh$A^s65CJW8+u==Z-(NAd9&8Vh@&1^-7wu7O`ikq9dyhhx0-Q zN8H{w-HW~tZR6;hU*oKL>FbOIT%3Oao{HeiEICl>L&#UBw(oE2|=@3C7Yc#tbm%W^zbiiL$6G2M32_P)9HgJytumlQrXRt50Y zXmdbP{K8-VkLp(YJ6*JQLmg_YPCs~C`&U94d9YNbI&to8R&1hjV1I{Mz(k{K+L%Y* z(H)RG^WcF_JmC&>YHu3I16vT`@mjppF0Z{>+u5j=#hsN&PHo?kjiP_ip4`3q!9BM5 zKp`w_@6(?)c?c%yy}~xg8$>uUd;(Bje{heViihq$SI^Bu`|b5y&93d#2D%*&bO}{! z{k5J=xLfyhz=3rVg_FmxRVQnLt|I8L5vZ}IKg?4mv@OE^?c0-A)nkg5Ne81>(lZ%O zM1i-spsX25a~!LZaJ0IdLfJ5?Z4^X z86tY*^CPO-6(2NBo(8)hcs8295fgRa3wST5Us3VP{fa-?$Do%c5&@9h$!y+hE8{{M z`tTk=G<#~G80@c+K(qK-Ii1mt-L6n(2&K93Q)^vYcXtzv0f4Zm zc;sl>PKeIA5x!IcR@4F2M~0yIrMS*_3P-2w|65(RG1a^d3Ks~Nk$Vfx3w&Mkk9`VV zf_$VO!`MMWl|{h2;@wAlbydF`rx(Qrtjv|!V=fy)xV}XYX|BwSQDAGrto`YFYS~k} z_}>fQf@eAE+E1!L)Z9#$daMveF_exREEa9>m~|CHq$b~|ERx`0p^JkK7CrhoKA?e* zF3Fo))QK{VuosvSZ=^!wC1!>XsU7)VE{wuIKP6(sZhypJAYif9eW?JBhi%E_^wA}p)O+z+@N!om?t`Am8=kx10G?7j?R82^NMkkBJ^kEQ>Lmh#bpHtRqo zu#%aQUtV}E@A2DR!nc%}yuOV6ztLrwF^iV)HI>050@DxdS|GJtm$yv|Mb!L}Skaaf z_=#vrPWD23UW6n=6h=(fhpt$Wk76Up-OcT9nzfV5Ij#sxXsp0aXPf@>7#-34gGSug zmzE^ZNd|$`-Rhb7MU2wDogG>mkuhUa4RFcC28$J=?^iuFWVG|zOnC`MSyKSlo5xlh z*X(1)+*zQq2{pzEh8jJDQlUDYhqYGwxq>p`T+C5|7Bl_2fiPBM*!Yl z4*+jf3;=J<^nh<&_~Kb;?w;3UTM&_}Bja0LNw;w*&Rk+(K|I;*P=A!kV-v%AuE)G{RO(morNuf;kY;h!#8KLO@@WM}u4YU)8FXg3IBuxvke8mPNLL3=1d^ z?}g927ao12c5uDO&d7>emB)PYEUN}9BkS|jXEHq6#XD|2sH$j-<xr=--Fa08OGyrTj``woOc-VaK8Jn zHKmNQE~25*N6di{3oc}>M+H}u3xC?;Riv|ihwsE*jh?Q%(8X?up z=4SG2wothKjl^2(g2U%%^+0e=OJP5OENu3*I1N}p0BtS-G;2dfb|)@w)W$fb?`1=k z#SPhVS4I!Cw3(5g(W(dJ(aUNz9#vrAeA$+p{#JYfyQ%fDxa@<#9l%9w8}JNI2;jgw z`HXTmV?!BZledbfFJ(5ZASttxsF)UBfucF!3^hcIj+ zWVZc#CR$pp7)!c4g;}F+Q4`G)9As0`BkdG^d&~yqxLnDl_CCeXE^8XgzZ+zioe$t{9@8!CRXGZ693Be6SY5Pu%a`fq1f*VDc}5d_l>s&Wi1=z zw%ZE6!Fa`KG69m`#B4lz{ZPc7AM9v!mbBAHKc;D||F>_y8BFwlQ7yowDg9WY%FLKm z%nc@(?AU(w#j{pHkiMHMR|kQidnfDI|En2))x(W-|xJRUVgd9qw#sA{ma ztJ9P(l9dcLZ86Rn<_L+j`6^>yI8mztWo@DZXuLG@Ft1DHYWo*Rr6ZZP<2_F~aPJE+ zQ022m8blGc5IKl-{5be3qg_Ih(SiEajXasSvs@N?9gQcw-DKK6MnrDdK89O7pv0S- zETa+kZja7<2WK&_Jm9k2q{e^5zaF}gXV+gRcHLr_L`v`v}p@_dzlD!*Se_Nbt z{ysQ|FU2kSsP~hqN#Oz5Q!Nix>6rTYum(vwm&~7@JfyfkCR#*5Tn2>@z4y^R!%gMF zDEynWO{10pR8d-{X63@WAOF&u|MiK#-KYG5H!FrESdx-VBKcbaS`-C&RQujeS<$iqZU>uIxF#B8t z0l(fOu?UyHqmw^`=z{(s(kwJ^8SO|mgf_rcSUqF6E#Y2}r$9%eC-7<{V z%5y@5d8co^I2u59uQdT-~m-h?4`1*{Pj&FPL~PwQB$ z4EHI6mYL(?ROEvSSWh!^vN#PZvbOuWPBgO{j}Nch{7mr@)DbdUwy3MBxyPzORapH6 z`zLjC=`!r@WOv8yrYngZNkfX!{= z0tY~8WqA(;>Obag#4Gq5(8N=aTE>AaT!lyL3EB-g1rZp0upJeO&lv@ls#>8d1cLxL zK&a4C>l46{nYJw(yYqUSZjj!UqzB7=q^GaQqF}^s7M`$7 zMS87fgQUHA?F~EEd4@A7ERtEIlC~A%3XNrf(GH6as8k%-dMgGomg&gi*VDsdpfM*1 zd;E*KWy+H5p6}EM@1QwGQi>aM^MW~P$*eXCTM``Z6XmY$bwetG^*X5y`mS!2;ew`` z;DykeN?&grcf~KZNySKJ%CFK8Zt`g66g=u&jlhGgs5p^)Zubm-PrYc_ygw)?QSqz;s-<8$&|28#GQ+*o zw2IXgJmZX>UMur#X=Zp!s5R7Rmtv(jd3TZSM69s{E?%b8Wn_gTX(|UKi_?PSvjIAm zB)bxobAl7nigF*+d}F8u(w&^$#!5oIfDuCRhJ;HsMWsoSUV)WFpU4dyz|YO7 ztOkw$6)8e9*6j=s^~9XzQVL#-yo@1xLW85mc!seAjnc0yd62TKN?BIDI_p!GSx;G# zk=VwP7vOtiA&MxRPg=33EVISRGV3YJ%qvU5S}IF=h`I!5qd)f6pu&Wn{R-12HGK+G z4o*Sk6{e<8dIDEMHJuI$lS;uM&5#7}I#`ozC`?|A2Jf)n$?9Ji_x4M$pc<6mQhvpe zUVgcgqA2CpYe9gahpt#KI*``>(9H|Xp<`16YN8yk9l0dE6)(N;VOM%x@pU4ug2LnM zD2cD7brmVkO%Qe#lD4#Kr;0C{^<&>?)4{N zP3lY%JRuAjeHmv^Wr;Mg*jt-K3?6C+h(}7$%n@Ku>UGer6bNLK!p1+RY6iw4UuU%# zv94)k52{SJCS9Pg)PLL!;;*a!EGG~ey2}9r>V)A?bs$6HS#o%gL|hFb)K0_>3-dbe zBD$DW^tTYF@{)N2B*;B?8LG|&zN5%nsRUxYrPN9xm~LWE*$f!pqV@M zIkAJ5;E6r>w}(x%Hp|#D4acHnqj=1WI@4&K%CvSHk%G01YuUW89KGquAe)5j9HJt# z29+m`3^_oqim>%jMul1m1(Z9_E(I=2;1M!a%f?Fp0m48)Y05(FHjXd1S8W&IIOGoP zN`q1YCvKIQniZ(|g+(=OYQ)~tvdo%{NNNqEH_DnRxrfM(GLf00iIkbPU7QIg@Oxk_ z&Rzisvf>ji(MZ|r9Iv+D87N=ib;yZ#$nt(C2sTA-D znODZ1){2^70fpzciCJ~xWkpTl59J;hux9Si8-cUV7vh$lSbi}gyQr0ca?4rlPBtQK z-kQb5Lp^W|V;E+oJ_W#!%nnZ=tT2`e=(RWF%z%m@5j`o#;xGpILw$NALM4z(B+5LA z;HWN%qW&>JGapD`X|xnxOxQ=Bs4) z8n~NX1--fKH7{_P-VmB(aGJe-M5=r2VVrw@@ED|5;n8r*#3MXDpeubC%xtM(@nQe= z;9zD;0`O-aZiC+7*@gh#usi$62? z_^I${*LCsJgO5*zN4u_zzc~2#h45%s=o=ottSbZ^d~2y-Lti&E)?Qg``M zhmA#ONUzQ`(s%`)9eFHbgu}B}Dnv$v_zIc8=%Me*5|w|qiA{u-ZvTn*SFXcfNn&BweX!F-RT^(&yj18MTK%0zvepwb`aaK01)!P0^0nAvyG>?_oD;08McLd}RH?A}S za&$tFKeB3rzvCo=wf>HM1>*t0v>2Z*-t%*Gi$L4oSG^&aGd(@Igb5TLxs3vn?AQ+X zTE?o+*s=Be^kNalj8$fqWV$f2f6rVHZX){YIh@v`z$ZHZ$RqkdAPW^f1Ig3kS^LZRNnx|OC)xqyGF27t;J^rh z0pvGgU8y`9&aEDmdPF&Kd8CD&Zu8}!Q}>qhRxQ=S0v6#X>meud$VokN4tjJLa+q`K z$)DScRq!0hDL!NL&i&a9UEcivGe+e55M9H;>XNEHF_JiX;X$BW$it3%iv=)xT*x@< zx)EkZfe>Q$kZ{osA!eR<&z<@4!OX?o<+lI4(mVkR)$sa##qDoZogw@xD7Xi1URYp3 z=Hi}`VkJKbN-7ZxYnMJ8Owfxy7RBex?$W(tKJXsMdPYKB#?XxRQ!<33w+O?)IAi>;O|^(Db4K!inE<|#-hzLlcJVpihU zW!Y&&I{Hh{M$L~@!uEaD;(w@P50e~Cl!;`L%T-6cXUzUsM!;xgA_3vdo6p1{9QCet z`j(A4wQ}JoVWovthlHggD$^CuVVyRJk!qApmi4iRhB-4ELiOir^EFsMnG4m9K$=1E6-#f(A zJayRIs2oeH?Y|JxwbD_y2@zAZynY26F$pcUd(92q{1rnrHe1pNx?yo6i)v*mqjC5F z4e4E|tHOn<7QAxdP!$uDop{x{z%Hr>oXgW}-Zgbj*?XBo&wM{Z&ul{2KluX?%_koY z)&=hkDk(1m1#iI>;Ql#k$9oSN6*?|*bj^=SKpD%OrMVHhiC0Xss_)=q07q`xSVa4$ zt#|Z+*}9oQ+|mc*8BVeFK2wtldfx`u|!zLQUFAxKP(A%?gns-+9%@1!Qnw(mLl2VRA!{DNN+GR4%C1%mosd@tm zpMcsnV^3r;k_!mpNn zj&M@F8Vf><66!W>pCSaxK0gvQV!C!65sn9egQn`18iY}lrHayxQG(blD2Ic57+?YG z(frt^ry|w&gz-E9l{8`Z^1;U@n^KLX{Y_49U<gI)y|V zQAe81<7`Mp<^iC$L+q`IqMm@Yr4U^IL+8Wd$~a*FCbSR|)|WK;HF^q+c4EKw96i#m8i)Lm9Aoq=WM;JE6v9LrW3ekM#^VN?$qcX!N&*ii zqVfI+0CAXB)X@_xTFGf`HqB@r4{1wz?!2ywiQ?9@$6gXZZmXrfUxL~KjsQTW5zCLp z8BK6rpUY_<(%kSr`~k+m?xQtyQwc}tOzrg%kF-zR3GYHs@$ z!yZnF0i&NHySl7S%bGwiyu$K|lQc<|_*6M^PRX!JjR8d}(Auv!A%|y3+YC`EPMQfE z2^)cFI!09kiqk5hbyJtI;O?qRd$I=o#t!@RPAIKZ*@L>we#@Ti#?I{ya<X zL`_^)Y3T7>;;HsLPTJ-ucod&R#w_i>lul{BujZPzt3io1Xh`b8u*1!>7AW;0W|peG zlzgqGE780~Lbc!xcL=T1#h#rVPX5HwBkFUf54uKYrXr0+-{>KC_VEKYTdj(s;^X@+ zQ=BI|va}aXVSk;9^cY3#Y!)ruJQ3HMypD>%dhHg~CLb%RV~;xo8?Y3`2Fu;d zaxJ!6Dn+3P1am0X;Gm*54zm8=X$r!Y2~d+T2##TXrnwwT84Fn$ z0yIqe+V0}e&CgbMa%82?A_oUMM=+z~)LeV>QRxVTe`&vatKTf>8I45o4rLV6Y!uhtI+&zhT>T15(!t#tPyo6}NZx)qCkQd8p&K)*T}L;U z90HIQ`&FCKv=Xn)8rSMHtRA+A*t|p-s(2|t1_)6}b`Ga;x zM-R~Eh8Qnp-~JRArW33LVxFjsUjmEuC3JmjtNl*zgZOGXuz@4><+|whbAZ)QJTq;R zX>697Nx-&j!+vyx01a6w6^K@a;bN(Tny*fO^X#DF&Y3OB?+F_%u#o6rl7q}-z@m7^f2sT93?6FuGs7V>>fNG5>DDX%%Xi1gwZ3}Qs&@UD{ z0mjz2)T-xY9$uoMBrV~kIU6|pnRAJA&T!WW_v} zl-N5T_~%Jt7|(6)9gksT+JM2?EPdk?Vy{4hhO`jF3|bEdOt(hBkP_l#;7Bddb!)>g zkKUgdV}H6G(n%M zBSCHTV5lr^UdOE+-aNyEwSkc^P;-nQ4AB(C{aS%IkQRfbZ%t#mGbI`NO=L_@Nglo1 z3anAzd@BGp(24^kL#T?b#x)d>Diknu_Msrk<;7zI|6mnf&0Z8iQg%UVu7WH|$Mp{h z;JjZIQ|J)?i)DkLx_s-U?Lg^=i?OS4Om9az!0!@kIqxSTZS)A}%VNtcU5v zP)}GVFccgTwGGpN%T_t{OnARQlH7%T=R4V%e9*f10{MKdf%oD3Cl;I@_-;pm+1V6R|Ka3jKgr-_3%p>ND-n ziZMZqW|dxKBg(_;UoXfY zoOd%EL%{Yc(UwzGT`qM?XjVN~&4kKWL=_&?F{v(9ggi~7&5DM+O;8-^>}Z;;quLva z7inFNsSqC_JIb^_yV^n*s*I@-?Y#9Hd^uX2I>i}7-R;3cY!B8BWo`D?o2dIHnhkrC z!$tkjH_JMx9b5`#v^R1cBw^h{E31A!#lc4v@H5Yt*$Jc5x1nC&P>G9yRdkq2(pAPC z?aD-TGM>|M1w-~QLsOzfUZas3yhK4n&S0TYg4DcXs|p5cGeYU~5%Eo0eBdJo7wDy& z1A{`XW~&}t%IHCI>3|vK?McG$MnV-BVb~^Hfpb0^hJ0h4F0N0GTRNY!j`mQ`|l*tEKD`}QOs!r zSrBhK(LhK7W|2)j5KHv`P?beVGJk;rs#w9W@(=0FE4VC_ZvCmGFwA7rVzW9K9Uk?u&lq+bQZZ4>b8_#&C<9>^nuG4Yt6F z*Mh>bJ?m&o-Iy-#BJ1V0OI-nfqHu|Euw+iUa#kqhc4TCA5$@ocLjjIc ziHjhX@K7^+>#2(X4bqXK=>f#&JYFfdPGqKrp1Ez_u%OH@#7(S zp6Z_qJ>O3CGQPX^Z`%A_ZO%S?0^uwkPAKf8#S4T>;un~rbX=c5#4spjC4*A-cKaX1 zN`^?LXwsNqn*XO523{Lm@A^g z6*t55WBzvG;2w@VdQo^-xNuq%cK?*?ORTJ~Eo|&dd^0FxYTo`w;nKgaT&e?}+h6p8 zTC-Eq`HX}E^Tkt-5V;fa;if$5COu_In!b0FzGz80UcH<21xvy)(@T2VK1PqL6!o3; zrT?*|GkrB6@VbCYSRZp(Yd@-Q7Ky6TdGB z>F$2L!l|sJ;pXnsH8Oi$(HcmT7newbfi!09n(v{5X0KyKfQexzF1}%kL>3z-hf1ed z9vdZ5YdZc@<5arR;Q-XjZ<3;q2)cd!PNwkfXuro#_3_b<{5f{^HUEDq< zgt5%POQxKlIA=o^bD*3rq0pVK1U7GVEbozr!L$50@FHrnN-tqy%gMpa$_4WyPeH{(kZb5f+Z&HYyZ%@Qf+8Q z%4)M*7?xQ?AR^$yRK`>th7YgPqrZ-i{@U!^=dS!{ulwL>vbG1zT+)j$G15y}Le`nl zEb+vJfvlwy6p#o1xZPuM@lzGQp`8KdR2hhJ^y2Vi0K?h>E13@Kg1X+DX2S`ZN{7&T zv&PNXsHB5yL0iQ9R^9lo?*c#5t0UX1W_FPZsT+PVhx?t)5B1?1A7HWYtb%xiYq4t= z*N;E67}o>n_|9G%wtSJJV#~4wZ29blt?%n1tMR=<)>H5M4w03CtdG5?WXu6%ef{Xj z`p#Y(vV4)FBFnM_Wclodtkb*5@(!=>31=Ppc96A|QLu1clYpzQGispP7;Q!rQ-rEo z*kI;&@${jKr;DfM5+!xvTRc2t!!!@w;mKZ=;aW=3e`OO_m#lL zBmHdrsRtLcarNl0+5OcMg2PKA*++XlAR~)P8(n?cQR!+~0$qJ}qwB9XyM#UWdnW~V zDQx%oR0d(bhaM0fUtB!!H(X2S&eEv3)A0MR>`}8b_Jh~w51!L29HXhssACM`afE0Yjk|aL19?>R4!h~kTAIRW3V*4#6C(SBN8MS;Y{ z{l1MdMT>0@90B~p?DHS%chB|CPZBQzg%2*JN!&Mr%oTiIMca#>GK6}@E`#OyP?jQ2 zvjK6XagtyPK;>dHApC@Vc0f zA5Pp&Di$FXlfDY9Y>1)Xcm89|4WGC)a{7j5rCO^unysPXk@k{fjvYPj_!E{gRrNnY zKsuZ%Ba;pA!JK_ve2D?@cmxE3`8L4vXR^ixiQWwy7jNk$D+#|0F#GNle`;O`VXXa> zvJEY7Ez<;Q6*I2YQPz>AG#)=?td*>e9@0(wYnF3a>m=pm2wnlx(X3Q6-_*ww4V~0F zkujnB#xm;l;8NDmi7lev44`MUd5RBo`r4PaP6+7-{zB=?Li!1<<3sxUEd8XAethe= zkp3}CKQW{q*WxHatN+uM-U{iXtz$#_=Pmu%kbZ3In2`Rpf%IcqOG5gA&j_C3kbg<5 z9nybsAidpEh?)?6kENIGj_7O9mj2K{{^1rgL`(nef%G9w-YoqIOE2LhIi!Ei(n~xv zHUG2x|I5-}65wnoqTkYg<1YpOXh^SXH-M%8p{1V{(rrD;(hphss*qllU)s_?^jE59 zMM$@^LoNMJEWN~!%?K_1vzA`MZ_Xr3f5y_6hk9(PWa+m{-b#K5s!T7$RQTQDtWX4# z96211&+^)dk7=&rh){qux48e_l8%qkaoOEO`|OhKW6}4qY}1ssv`~?SWr~^Q*C_sO zk$^}!=p}zre_$}hd!GqXsLfLb_aqwC@NtIOiqTq?w5~(DPi#*P32L$9W6)(CkG2}DCTncku^Tz!e~OZw+cvnUh7Cy-&W?=aW}1Lf7O3Q4k-rqaHd?I;7-d8tM#tS5s3y_Mi4JFE zjkkDI16%3e_b3gHGEOKG=M9kCjw0X%G+?Q*zgptvt+X5vEMUMs!$u?ezF?;t$Cgke zEP2Yy#N25N)r2!cfpUwAig;EuQWcwA%RKgWf4iHPqm9y5gAK#SUu(GJqVKGspoK zy^9jt+_R{9I!w@ZQHGH)!)iQO*A{54_+Vzcww?7T-e&(qH|7PzcXtx?sHD(kPI{0^ zrQX=vEX}XRan_4GWEH)#0>!!z35fuJMW~5kA}PS%CIS!`2!=*OSYVz#Skw>$BET+U z%an0JhhUC*Vs;cz6l>3us?n7*H=E(i&1Ub+%~WS@T5EM{MKs~;660X;k=m1)y&M_O zw&HTC=zA#))daO-yje+NmX^acK+N4zf*tXB3sdl~KcQ3U#GZ)CI`2m5eix-}o0Dkt zWwd~|4C%9WN2!XhA`rwlhOQy}R~94HwFL@$D!hx*`L%F3gLwg;MIqV=I@u%va#@k0 zdm3;@keX#3hy9x{2E^5r0_u>v`ATJBb9gkd@0Ii>Dte!FXO}q6M0=@Yz2o*FQOrV_ zI2~Odf>&KS`QHxx=8oOuQS()XDnl3cX*4XSyqUyWrtx3sX3K=hr^%!jQl;qqPpgf- zmp`Lt)~4)x43LSBtb~PUr|+xCo)EX{{C5*mLjexx;_-yfrEm~#_?W_F1FRo;?xRUI zk?XrE-SbstwD|8mDD`o*E+Oj8R~)C&cjqNY(W0szKVns+9G;5bglXt`SpTf1yNX2Yn7w_CK+r=;b8UrQ8FDE%@FF8Zvd)K%;TgkvM_ZHZ9^Wb-k@h=h zD5DQbQ#Q7%D?hMhj}la{>`lRh$YUJ$&8wcf)}?*5>Pt7O)xLPstCdI98o1K#j4SQV zxbhsh5;!$%>81;+O_i-8%)+lea&RFk#*4dtlWY6WJ@FTpEWvsHlAm_A9m}v^e%1<` z3<7ph50V8{Ks~BfaqqZ=Fqx{r$(CbVzSpHDOhdaF=6n9IK1K1dIRH%)+conDDIWvf zDn?C2!K+6brQ&%E0sG33Gd|<38IPXN;=pH2rQtJ$fsc7=6U@TIyg9YVACLrTN~8*1 z_<#b$;2VM1OqhdKiraOc?orY_euo3CHgN*r48L(_NjnTE4HubHTW zZ8|MuCTjng=^EoN=@WP#mS<%0Bk8}n-V!|n*Z?>vCPq$^HnT}sbiGF-VEbnzQt?Je zNncxqjqo7Dc)#Gnxwhg4#<}*-Dyz&XVTF|p*aFOxlftQta)oJr=8vgWk612x{8Juh zf2XL;D-AU`e?~~tGs;BIDl!X17Eq4_9=TNpUY5K7Cp}L~Q*mz;SsMWXoeL&59O%an zSOf4hAOI>qY5Q-z#C-Ssp_NT)Jt}`ZhcN@JJ!+(~!RVP^BqW_NQr=n&Cd0HyU_&AO z)!-x&^qZXD16G$6_IzFWj93f6BPIgEG9nkOO+bbd#9f%2i7^tH%(O&9V{HbrvWQDN zR*PQ7W_r(>tG6B@kL8x7Dsz&}Um;R~bj-$Q%*I@tODe-E=@ny|D|+LQGzo#~_Nm** zEK#e(_#tZFZn*s6upyN()uah6O<_)qr(&ofmpsE9%q8_hPeq(g?5DD^U#}M{+5!k@ zL3=6&(6rD8vw_g*)T;+SbZQw8vLit^*%1rOZgdc=*67&smd6~7Nk;7MWTSAZAG+i} zE0P_=u#7H&44fl7!!{xy!sGca+ zL-!+zMB)r5I0>2B*ycHGdIc$B&WGvfW$bJ%Uoy|q(G*y?dg)KFU{HA4;;^#fpABvG z;#BVlXz4)xIy)|lZ5Olr-zb=nSzV3d>Yc^i#H!mC+D7rqr~>oi7zEY`UX}hv3?l@S z18nA^C}M=BW}Ld3cM}j8YS;M+w8LRH_F^q`Qg}h5_*u1}9x`xQ4^@A!hnfen0=Vc6 z;2Kl_{)0A??3RxDN?S;wor_-%HJSoKT`p{z2_ufhjPg;PVgwZht!W*8kcpqnc$TQ@ zP|vn}WoAOz!7svx-z!EwbVr~#xEDuA%^Aijj29xYYJ=L`B$}!Mr3~<3j`sx#`~?

kfXKelHy}_(CETV3h%PhH7Y5dw41gdZl0g+Xx=0eLhn`r-{WIJj` z&4j;o)3BOLoMLwzD*0I&({?P%apa_biugLW@4{yUBuFE7`$*woI;GMJE( z=r9cU{n7}v#spClS`Yyt?d`&hsQ8qe0xH2Ibu~dN{HeEp!8f4ph&C?la4ViUO6L7u z9h(do04N^m1MYP$sf89W59TZhM(9G_)T!3X&|dJrfEJwSG&`(D!A|}}4{a3x4$dNZ zbrkyVC)_r82?Fb(Ss8<#59wWSV{eqFCDaLggFDQ_zsY{cfq8f^V`xf+i+!?$xND)H zW38~@dM#I2v?{^LUymB*Y)Ya(enG)jCQd?1AKqkAQ!E^@9;6R=+31eJShjCprk9(%f zd%n}|oSF>+#*229){HqH{&i#r4k<<|~{d5@$4T0^*SC=7Ra93XhFJ`u;|U1i3Ai`SxO zm)|S^3mdvs)BhL8NZoRnfJ)*d9RKf$XQ}M&8Blh2mCEjiZH^Id1Vu&`1F!V1Njt>t zyG0B^jVzcoiklf_QFaAO6~v$_Q(VD{H1*J8&k1a_=08sK-Wy+- zL7GyUxOrfLR|ZovHOMIx?9t%iWcs<-!-?}i?nh3d3a04udN{3wmdMS+siU@f9!`6Q zQRzLLdgojAO$>TC=~VD=f=yYY;KrPfUPFPqp!8OlN;6d39}2=MgW9wCa)xM2*WiLQ z$=WVz1B$2CuXy~>gIrT(@x?)v*x;A&) z1ysp`umbiO47>A(Zvc?=dItpAw`lC_D1Ss8u<7d(0JVFDzxH*B1RF{E!G9FO2N}b| zsBl2nD1vI&0M2lkt165o9yMDwa1ajZZ@`hpx4sER=}QJQebKAz1XDF-=<7t&xYxDc z;m7zdx;WjJmb=^gr|7`_VL4KY<=dDC^EHZWW%9`9K~|?SAz4g|+ca7ZLci;&p?OwhxCm-mZPA#v$`a#_<-P5U0M6Uw4`h>eJuT5NV zV86D!>4E9NUVCOqm-iYQHP3Lx`+-kq(%9Jw}Llvrw z4CbV$0DP_sy9`iEin~e7?tu^7bBXqJocG)^JOMdLwLJnT?KKoWyoo57UWzwDY&ms1 zh>$Lva=}O;qnUfwZuN=3$~TL^fj3vCiBq9t@1*ax0StYK2Gr1 zgG26dbn=d;`rbYIc-C!uI*k%hb-ospS6=PEYD=E|dvMQJU;Q9wc;;>|q>T6Op%b-c z^RwHM2%UE@YTkbR+|=xr$*o&{eCn#*lUsL9<(nqAZk^hkUo&;>_Svbt_jYFLrsLc)I-esXqxE}xvw4-Vzm?3&M~wr%#0(Q((@G(VNkPHwx73Z6S#sAxN7 zw_lrIvwas8oSV;IKb3Et+Lmvb%MTu76)VNJskCT`Rhe5GKKbAalzX6_9O!9#cFVTw zR5=x1H-9~aM}YF*S@f8`4h47)cFI=$J8RT%)Zb>?zf{Ws-fyee!T4MNUNgIEZhq66 zwNuxgdCjI5Z&~qdOXWiz>&669hy=L9n*POlftQVaCrY6_Dc>Uy>ty`{{ zot(XC4OHB|Y0cd1rZta7Pt(m)N+om@%qX>PLOhLJNi%}&lw&7HAj`|2~#IqRHF*KXLf?i%`b_WEnrz=4~mu9}|PzHRlH zXRJNr%(Kt3a>lHB`Q7xPha}G`-_TJ!~B{X zwr~D!;Oy1~O26B>di0r{e8W|{r#5vf{EuQQF|PG~5v#uF>`j|D!;X_v=Ult?taUG1 zvw7>=o-?r`Z`DDK7`pH?Z zN>Kvm|$@~PQbbnrp9GOD~x zx8nzEtMaW|woRed8mn@oWY-PbxF^Gp#qDS+ilX~n6rIX-*Ve7GyQU_$&P~0kbFD7( zJZ>ZPN8Y&V-2WU!?W7%DMZSqRia6UPf@P<+&R%!TrW-jx{-#Wi(_*Hrs>#qKxskvQS=g&QN*S0szPVN|Ad3C;hTRyohzZ$@=&P~;H+x%6^ zt>E{KjXdvc+1xod?`)sF?hKf7e)}wX?ArM=rf!_PVaL{~Gd54nP0sIU>w=f=WpPln%fMV0^mK_=Zl=+J7yWs$hsZe11u2}}oYwdAvO2Y(0|BlJ|>&dbG z4U@Bs=-16o!AKw@^s3ChW9zQ#R&Uvs7ZaDB;Tzg9IXij79Bl|Sba(OwhV*$ocjj-} zVLjir>xOI8m%MYs7D2OCcat}Acjj8%Z=Sk#5=!{zH&M--8gKH|Y`jmHZrU<`Qw~06uid)+4V2lOwxcV#p3HB? zZxmP3DpUGV7rE2i26s+nSz2jE?)-Ra_`LYcc*HG_oon*xxPNvvzHffKBX^RM{mr7DHJAw$P5D#{y6kfRD;|QKe+zGB7tM;@S^B1V%M)i10Z>T>1CQ}*OZK=eI z`K_ew_$02!BujzK#Z@wBGhwaLh?Ca2>B--(HZ!-BzbC{BVyLDfh%Q}LX)*aiGTRt8q3CsmrsOPFV!95=}`9CI+T`#|mdWF&b>c6!{bot{Cr_%wcP zdn2u%8lMeJ!*RtO3pMI)imha?Y>tiGo<_%WTxc9+s}0%>)p&Smy-IKTfA+@d@{`=_ zTc1AZO846My6klKWA3%}wJu85*Q3!#YJZcu;q#M5Wkc;EzKt{AJSF)-*G$LU`ucF( zh_73^yioy`iq-p)crQJRS|_Aurcpe7TD6sBC)wUi@kW%tu<~MetV`3(5t!wEJF$|G z7I+#N=VhJ5TbLsr?z}Ne($&f9+)(1yoN>#^$(bX|(-rkoveUCu-1n!$FMK!ctVma+ zgC}HY!8Mo(pG;E?*Xpq$m95 z`I}$Ws)1f&=G`gCK&#%ks1~0QHpqDs{Ko4L43^o^-q$zEsk< zDp7NFdRF23{rpydepL!Vzj9)A386tJzs8NcXehciYB8D&G1#CsaJ*Dcb&d3uu2DH9 zt~4%cG{F9G*|E{NpZt;R#Q4Njm#61cmu$?M)q1p|bJg5XH2mTyH3~&_cQXAQ&Zi-%O&)367Wnpgy5KfBye$M2#1{WVAKf`cL%}-|`xFv9yYG4lB2k#RA!? zab50G@fO?@Ik?LDv$La)5Lr)(by0I z>W;6)Pgkh{esiCQ+bdt5D$j*4|AF64-7-@3zrlO{Rs4mfLb?+5Pr1~y)G{>O5_C=G zmYfwwtJ2M_5j5zC`~Jp<*PlGJDy<`Zm3Kz*l4K}(3VC0iZUFP+wNp55E*`GGAgT>> z(Cx)EatvJG%6{H4#OJh9VUghTEV<1}e=glUXo8$lgK>2k#Klz1asq+s?Y3{8Ez z;*Q&`L5bnwuK@sPC2`0D+T5)zM$)y7G&!x_!tEGWHt>Q%*#@NW&V&<>8Kf$R^Cve( z?)S!`>dZUWtOIJMKgVfw#ve9W&%ktDV?Hog`~P4qmE#P%o)W`oj+Z)+#5;y(x;GrZrlxM5 zAYA)&xaCX0j53Uu=`ES34NFt{iyR@E@z)UR)ZIb*DRIH$72}agoSXp>81Sg^_p6}G z{m}6yUGa}sNP-&9U83gP>kz|cd{&kvC(!T82rH#Yl$}?N+y$tMW(*dP@F+e%ODeTm zTsj3*3VcV=`t(ILH|&l_ilb^Nznk6Nl>UJS$GC z<@k65$APRSO*gKU%Vx*a>@;KwVcHeuQ zlC%D`2uVYWh77`p;R)ci6rFIelm+w$Q@|3UmJJ3bP~>DLP%48BCcxK0nY=V^jDVK} zloFrKXALf&k&Ie;>F`nuRD_TRn_$RRoW>I;13`o`8FGV)$ri}ouG7JeVqkvD{dOQz z1dGELrK1Dd@VLq87>Zp1_JX3A z$q>QLU~ZJDN)xbwn9E=Zcw8QsfAVz+;XRloWU-P^qesj|k5K)|c9A0Hi5Q@ySQd-P zV#;O}@pzbI;Bi=R0>FF#J}^csOlL`0v0~A0{bXfKPzb8XSOHHcv|+MRQSwl>BiOWn zg<3=CU>pWFT~;hqtQnmLt%X^{95`W63m1%RVjegC>&aqsVWR>uAFd8qx0uhDT_|EM zOTw31GAQK+)(tw|AUnumad?7sxNP_W9#}R)P{QB}U|6pF%*ixq2OUs_%FGKMm`eir zp_m&B_FOzq0E{V9UIg|A*bS)N@dWHwJ&+2!(pP46{n4(((0zDZ)}UPp4~75H1grfg z6Z&-jegdoHcS-gO4?|{Th~PHiqh}Xxu2ht!h)I`Sp+hP_ow4F%P`k`d6|guAlr#D=R{p>x-(cD6Mw8 z&RD(cHe+pbD`QjP-Lg%{!}d+Z9rc@AI+eDiysY1b^eimD+qZCE$j7pS2+~p6w$rI< zVogld!7Jre?Oh#JQLoIZk@qpxCLb47Bgl^Gxw;M28N^4`NXw*Sj-Q;54Sb0OlpKSv zeq^yK23b9fjzsE85gkL!L`@8RVz)JBniW<$jkl9-t-QO<+N8hD1{uJRw|$|LKP$D9 zl}4IU%ty6T_GvL_c4OOVZ%j<*IuhIGn=niRdlJh6eR-xqTkFb#kgH|EQ?IoLBX=1g zNSkT+!H%+smz|8LmS^oz7=%mjQTjsng*A*kUu|N*zs(UA5Z8z$OibZ;uVKsa8dd2M6>;PX)J+nTtFHR zD0Xgaf`WBRfG0M}{G%iX%B+A(B$mNNzdquihDM`dEW}jHzo!q*l_={I4E$9HtlJAV zf$n3-Z3emTCuQKpAjv?V!t^LII3*nOW(p0orNhB$uo*^HiI<`Lm}Ih=bq|J?pt`unOnMgI$f{T2DkgL&;ip1T>wo(lMydS=Ow%^l@3R4yHhP|srdC52qNXN&e*m97?CgkTr0?R_-Eq5f z++3G6x4hM^_T;+sdA2ty+f=($ZT&gjS@ObVwX%h^)e4L&NdS(FDem!Ok0Sev>e*4oo|~E3KWQ1y^E~tULF#ozz9%+oo!*? z2g%7*J)T!C=q)X1H=jHElTqSxqp-Pq9Q-k8Q)_xtQ} ze(-ML_zs`dB{#+8I}CiQPk89A@bdBg&lMfLq={kMJ#0*4(_3b&fa32YeC zE}_qBvLXf22+Y|2jiHt!Mkj6e zpK#{{>v{PNe{&y;(>qqE&p*KU+rh$vGv{k&1^;SjBb@IWao}0x`(5*6kKTz9_dS?z z!f%WmQL7U$*^5@aB4JK|?e>E5gHBliSq&wV4|p62i0J*m9ee*tfH0+Ixyjn`fzRBI z8oaqTFR*+p{eHLqlE8~5k{kP;o(!C&JB@jX|2k0X4#{Dld2*1B&*EkW$MB#_+Sj*F zQC}T2P;!0_*7K(z2m6}Py3&t9apt-;Z_BX3xxX4t5nf~lw>{h1J^J&e;KItYZ!KrG z1b0UggjL?EAxR{p*pxvF`N;|CWuM@MoV3iPcHGzzVnvjmzuR;tgf!b-GNxZEwBEv| z>qUff=xf3IipfMt=z*ft(RQ;BhBh1RWuJQ15jsn%ckX4mVVG}|(c4`syuSp0PrrVX2E)NPX969}jvrS?6h9~FddzRLR zJ7A7Ii%{tc_ul=;jF>kq0_$;QofOZA$hFf)Qt|W>r7w7caIiyMULH3m>oU!sD1Zi!=ur! zqemn?eDE~-*W;I5gKtfs_xf*N5mez%ubf(7yWgh(?hXt4V6#(nCJ)mcJ^yV>OvSSol->AYu~*9cKabDkZd*T(nm2A|;Hn|4g~aN=k5d8Hm|7u`D6%)~Wvd_*)5;o(D4G z>qoK=`Rw1{R^!MHi)n2g`&7h!ZGU;xL(E?GZ5L_6ihwq@W>AyULAG9EQBuYYqdbp9 zp<1Xr=5bD<`VSNvV)xO+kt_45N?p$qy?S;osh>PC2^(b5yD@Ek(#a$|E+=ql(q6Tk z&%Y%8m}JG|MO{*UlSFdRAZIsBO#Vw0B^}zl)Y2p?dt+B#$zru?^_UEvgN}KM zYt~_2vjOMw`qEBbPDE2~U4s$-DlMxeaGW3Cd1b; zTsHi4j9^)B$+8RF4T62Rk6jBqFAFrHGleUCl!cd5!&|T&WZ}X9f$FKv$-)*U)qPo-G=iAqu>5T`bzR@!E@pbM}d1znsNaYPO4J zoEGLh@YNS<9P)d3bBCump0h@SwKG?IMm^1E;A)ll^+mmo&nhp(w+FlqWIJI}3uj70 zOy&oq+W9oSdK|wj^&}%B@nQYxRQ;^N@@YT6NewHtTakLzB8|Ve-zGpMI&BL6RH-5H>E{vdrEZl7)bkYR@=1cSG=U=O@O8So_I+GcJI-pYqv_`qdfVf%25o(QG#@brZv;I7w=5>&PW^CNW7oU-@iQWlXOf*VX#f^ z^bu|uyaQDF@)Zj*Sjm$z$&|{BoH^FUs`-yIqC(%9x;`1V;NAv%QrA_#1=k&xDL+xk zU*NWK+Tw>UwF|tc{goO?Jqx1MGPYgGH_z-V80+S=D>U>cyE=o7ojrx%J{&jKOem}dc=^MtKNm>(|HPXTKuv*&2EU!Y#h^CS&S%=?kqJ18(l3glB zmd@y;WUH)2_Rf94$?gbu^z_|Zo_$x)GX7COYj$ywYNxT)sGQoL7jfs=JLOmwPrCTH zDK&>6+CO9Bg8eztrmp-q&Fwj8DBpi)LM=jYn*uvK3{2_aK<17>em~zx_$w4m@R4gF zqyJFz`*z>U{j>eQH|}5M{}mbl>j%MrHRT8q3v}>#J719sFmldG>ACM^Nw?}4ia$~zvzkn!8!DCc72Q7_-98Vuh0R*fuN={E|T zZcqPuYz=`;0t`L!&qY~Zi-3a#UR^<<|6w#Ux`L#Ks3HdcH}8Wyut)y+yO>x-b1|14 z3%miiaNvW_1L|HDsl-c`g{(0k@JN8Mh!A5T*`NaFW-0eC{YhE!ur&xr#&94s76O$) zf$}oNT(UI-ccIt=+7|d_S#H9~;doK-7R!_o#0ah`2sV&G6(kx1r3DxbP$VTd&;~FtE^Hw`nURiRqXB8C zFGcR=60jgHjSCJ8G_DJ!Lc#H)P*-v~at`A0P+s*gkf!L^GPV??f{(0&V|0!&0CX+r zI&=Ui2Zj1S(1bb{(QLR4fgL#o=&x905nfk#J-j1xLlv@K`(!kH-`6 z5ciEI<0*J5o<_hDa0EPoKp+xG1PB8sPzf|5mWU(bi3B2%NFtJn6e5*KBVkE65}rgL z5lJKxnM5H`A(k9V#*y)40+~oAk;!BVnM$TnuoN5xPa#l<6cU9@p-`w48Wl^$QSnp) zl}IH~$y5rJN~O_Yi8PoVVzyx*8Z@HO(0xM6m3<B2Pxjq#Y>hHAXUL5XBi~y zLCSt@zG8g#hBQylkufhcuc^YQ_(TP-!hSTScWTk4D?H;>7TN);4&C+cj5^r!a=2&z z_TG(CT`ISx&3<@w%;inPyEo-)%o;eNzqjiClU);+#QqqjrcqH>wRe7!IAi#)qt#Da zTLv<7jyd0|H1ukkKCXXyH~VaXTaDAMSB}2(A|1LObo#lC)2Y?%1UI(#n>8;ESsd%0 z(s8no960jbGSy|H>6eB*uQ_(g^g{i~g6BxU`smGhl6ys`i7lrDs{R{)nYw(N6nX|8^^q4@$B6Qiyxb!B_TJpB-92WFec30DU$^&m@@h)C#aXL+ z;RV&?vXOnA%J{&2O1YXNE}gd?e&h7p0}*A#>bjH!mCM?N84U%y?~!f0hwGd@qI|Wk zS0$=5{zFM)ek+^%UhSHH?T<>WWI}tUbUbmltM-j~(h)ji+Eczv;Uv?acEz2kv7>4uqmMC#PW$~&Gv*O^HUF7&62okjK;>4-i!;C^;QFy``g zBbvFoO^YVBc}0!x!?vQ&5Hx-I^6v5-rA6Fpvo1R-O=jL3h2FI0s(Oypl=)Q?B(8cP&^9L{w5DO3j76aA;b_1#b4S+jo06O~G zh&jLxfS`XghiEjbpo;n{{a@FB67mIoE0}$!3r^~D<-a1<|3wk&$XjKN)YxbUY+=W- NgrdLn{x8z|zX1V{_bdPa delta 29513 zcmcJ231Ah~)&Ja?dHZ|GBqSjrfy{es31k7mgjF*Lfd~p#P*fBG#3d|&Bp_PLJQfud z1-!Pku3#yv3lSZGGnA3#FHGBW+TFREFAh>>Mze$CJVM$pXer1^b@krOcdn$U&j%gqyh zGvG!dLI}Un*&hr90zrR7^9KTcVHgoV8b(5(ut1GK4!R?1(MLctbbuKHBVR8tePW&{ zF7^S-EPsLF3MZM|rA1uL`Q}sgPW~S6z~q2`PQ#q0=4*54)J4gtGG@4OoTr?s&5pw5UyThYu1uvGN~m*Oml)r zEv1weu|>pvzn31waOgGkpRGAxim@?GrSuv{E7A9Vx{GQ$7BVA^&M{*?ebf~ubjMhj z!2dMIm><(@oeCeI!so<%wiXkVev2z>qX=@PqqjOcK0$%T5?xD}CA#S>a_8InthiyD zabXYwfLaL+&EX@5KSYV1ANP6qArVbzwit~P!pQ+rfS_EVYLYsQYf&APmFU5QX=_z_ z)J9`fdN3*gb#fZ<$7-~-!noh4vHfm5V4ENTaE;;AoQX^%sd+QiGPo6R&>Y@Aki*;p zdrS19cCv^jt(Mql`#^^+@NI+gDm@1b(W61sr4(2h6VX7#Hf@)hw246x;OVQ<^HCYC zS_yL$Dl_W9f@?Cf2Z1B@I>WB^lO$bmC7q%8Rqgo{5jkDY0 zi21hRHYWUz(FzXi{T+==LI>gd`I838U^WsNrmYh%^%O518i2*N|LXZwN<<>)6{65w zrBnZC3D^@(LP4BhW2V=)ZL~T%{-9IMwY6Ez^RG+<2ni#F1X@T#0?h;yenP@ey+?tI zUk#{-L?8_b5=4arz8Vt(xPT?PhlXYwjYJ5BNQtWpqM6l{JVeqOH;6-&RFdy^z(0t3 zYa#$KM~{9x0FpQp8H?t(AszRVj1eeddO*mL*-lB^jG(pw+-ZD>62m1@@Mg9~h@L8i z20no&&nK{znCGB#Z$^RfBzZ(O&oE{z1jlf!I_qBo7|>_-dq%xg~DfP54Kt zsj7$vW73HafOyCUi1#Vt1GcY?cz+u4{&;|hClCZm$r7fPKaF@lW)R775In$(=4GHN zhu_|C0&$F1V?q{8D|Ru`j1m|Dj2T&)z(EKWFs3<9`Uo$YgQs)8-$2J?EofafEzWCW?0nl z<~A6F^2GCTT^Bm$d|+TD#OOi-7oseL5q;Ufi6%0jX0wN$Zu@vb(R{Ll^NC5Ag`Uop zL#GtFg7AR&kqFi$(3}q)>2;*)AdW}}s73A&nBpTRjuADWvizh+P=r2Ag)<>wlZw)7 zi1$1^32>4KM!)E4e2gYTyYhBxC`H=aB<*b~^_r%=MZ5M!!62rtCncB?ti4gC5%tov zHzZ7)sJunH@)k;Y6SwSutF$+0g#HHF^dE>qSLqrYW0$VM%@Z^@Ca{mtQW~5_jZ)wi zL^4f*qfrc-QsBTID}k-Ktih3!LpcD@RL`LtWMJ-eoZf_1$LXD#+$4TV!QqRvtdXwU zXmW!t!%6Z`AlF)lwI6Gu%SwUVtEmmCYn$4Jb4;`;HX|-*ZZoV+N5`pl z+d>gfu_8#LuO>Ihqd5+Yc=TK-A4a$h`xDj(Qk^ur!AUhb>Td_}!W>cpcTgD?w$9cH zSn^2Hgr;+>g*8~U92X+yXrwbSX`mHb6T%%8!vapN9ih7DESbCx^Te6gNMqq(5NFjE zCIY~qN);gxmH&+UBB?gU7FMZbJ8p+nE~%Xzv~I>VqlRV=mK9zA6MmQ+wJ{wl9Z5B8 z8_f2$vG`Ka;fcyQpdGz}a||b$I9^<(AEQEm2deaEsS8zvdqW9Uwpa*MjvA9H{h*ih za`*p^6dFn&Ab6F2xMOLCBKMHW{mjet3NsYBM^x^YUanV|p~yX|a=-R+y}}Gd?lD(o zFF&mC@Jb)^N+$_irLXjI8C<0^6qS*)+bg(26}-bM=+$E=3VOM#yGx0)^WX8( zcY4|UuF}_cOs@5k{I1d;?3mo-CHY;YKh`n1%}eqdqm`B%}^wdsN65TT(2-g zk$Y6-e(mLYg&B(6V=8yKl3Xh65}FJ~c9P&2ZZF#_%~0g7P`P(_xn5z0B6qdQy~oS- z3NsYBcdFd=UanUdQ1p-NwJQ5TFWW24P~>h>xsQ3dUSWnJcbm$6*30z@GZeWyRPJss z*DK6WE<{t*t%l1m|Qc0TetVg&c7u@UR1f0o@q>)(R(Q4sodwexIB`~&81>PJQ zI7&6h$ADQuwg&Vqlp|@KC~ScU$v?h5g+ndbq7Lee0Z0ZKVdU(fSr*rnb~8LZ1{=1P z7Oa%|(y{cbR-vuhYOwJGFzG$+m`nzwNiEmK^oY`b@Xla4CIFqf=GO78+$u2!v+0YyuU9l|$|IHf|h!ELI50&R*1 z^@v6Dc z3D{5LhNTM}=H*zZ^(A4kRp!O%V{c#ItY?aMKc0t#engF9^wM$`sc zpe{(hCoeO^JsKm7J|Qh+*7O_~Z(gX`FDIGdfvSZ)3FdlUQf#^IHe31Q*jDD zX&a|bFkJLg7%o67jZ-jO;PMiuQihAGJY8T#oMH!o?AZj8JPFl2VxB+(h&FHX63g32 zN*QV7yFuvvkogV{CK!)4O(zp`R0-N4HRByxC=Sp!Vf61DYBm_jY2=a+Wwx!L1-KOq zV4LF&JwfHTgldgUIdUk00(@B-_zonwP9{w*SW%c>DcaBjT9`#dC`|-A$!Mg>ggzAn zV$()FvQD9!44U|$E~V<)8Z*#Xsu_d?JT594Q9i{Pl=m3J<<&RPO6!&e4Z=@;qO$(l zFiwC&=Mb-nRo^w5Fw_~re>nId-{-zPGhI8LbsA9m>nFVg{T=+VUs+-YQ&*m}9P7nl)8^%DJc z!EO_f0{qn!yj*)tM$ECb6F>@xp{^{((UOd*Xh#$zn$ZHNCkJ6cDxX%GJabSa?=idP z?OL@f2|Z!0rUuBjL=XX4`_1CKmrl$A1CZtS^~u}AS!R1Jl{MN|k$*R{K`%A(M;PbD zvLQ0Mliz5qlehZ1HEbiQohXt1fGSs_KPI5&LGm`?=(RBm#fdiz+99l;t75iZs_zxm z+WFKToKR7vU4oJZjS3*8+JtHiG}70F((?CrcOW$abz$68qiNMD1Pe3$dm`3DN9uZRw&+mnE9E)kt`M`7jp;F}Y{w@tC z)sGrQvRglPSO>gqMA{|Mm; zZ4x?>nc(A4WkwozNMnUc>P6A=|6GU-0-Nf4Q(- zE_fYkVz%rDEz|;Y6iXO$bPzF=n6gpfriOly!;xi0q3(Q*ky3={&Y(tX6BPx3rs-zy zdxdC(@yAjKFnuD}Xt*S9G|ne6{yUk@9Q+?M9i5ScQX{V3f$4_@%wZth#`GiLw8uC4 zgh9(pr}!4e;WL3yS~~vBBZWESltp7ANQO=8X-ShpK5Cdy(Lbawh6T$U&0k|$B2;Z0 zpfNyVaw1%9@PHsOArYxI_R6MkkvpNLNTo(8M03#+vn5>2cciWwxO=*HSY5<)RSQLg1<>I~8Hk>jlsl&3_F7l{#V ztAs(;I3}T5BOptv)N2A$@f*@dSdq%e0n?ql4jM+j66x-qxG-QVl+Y<5EiEio<?ni5&S`nibigN{P9ibQvQ+2H4-WQh36T2`~7Z{fbHbs@0lWL(gX)EfK z3zo^!;b0I?Y>wp!2o55tnZPVIYO0ON>T683F%4g+cO~cuZ6rm_Qx+*BrpXU8ie09d zmv=5m>jO<#Uf&rZ5^*S4%HU$gs2F`8L7}ZoG)bd|0Rt-uSfrG{HamY zH>5A4r+W%1O9V*9Qi8>wukk|nT`QKMlx{~!Q$5)Mid*Z>>mXaPjg+{<5^{nZq;$iT z7&?q9jV09ZM7%JeCV*Z)1#)Qs0m9g0+QV#Mby00#U8OH52;R!|#_SYB%iXJSA4u(E zLQ)_#ZD4_4xrWi9l?SN9(o46qT7n~@LCk}bK?FcC}Nr|G565XZ_)g&S|92F^} z@dg|!kVi7R4KQkGWYx|OER{x}0uccW!bkJk&%%6lBX&PKlN*R2jI6eLWYg@UKCn+S zL=%w(x-K6cSJ)SU9CFqzcrtj=+MIxHKtZFf(7KJrh}ag4o7O7%s5Q1qsUz}M$il@R z&%z}LmMs!ps4I)Qg6Kh8JWqh_tIsYGffcXpN@~_8a_87}VvPJ^OP4O#eX;&T1@szj ziw_eJaH*WH=g3F%28cEC)4Wmc?NlhPlN=djx?=AeA32RyDgz9JZDEmBZom#t8Pt){ z!l1(n*n-KyHZ)$KlsC=5U1f&=2K$TohzW@B%McCDJ8LVX6u)qaVv0O;Z=Q6mKsGEE z>t4b~amD~=-XB*!uon?Qjghzr_JoCp9@5qwTtkbHpMq^F)7lMy^q zcd?$_D&IbDGD=napb~#C`@sX9xNSujH*KQnPUmk$?#}az19#(W4LmM6ttnT!o&6ZM z8#>SH{$s`meC1KIfE2~mJhl+KK}kV=QN+{qoUX|)i>P6RfFb|t{08x3`9b~^agQ8Q z&=piqE+~;7p1-W;$rv#&Pr&hpiKE1A^7V-&;|stQ7%;n%m=?-UB%#H`h;Ys=oMWCM zN1m$AUb&>8qNhRIyte3T;AqHmBaWy3Y0FaI|2VEqlCKt&>Pwc$FAK(+M1Ig%U8c5@F{UnhMOH6%WAafRcpGLLN!L4&jvum1V zE7s7HxPHX(Z@&7+7a#3BzW6#jGUCwAUGQQi0oTfa9(7Dd;PKz$t6pduUNen zfy-ry$OH;A3L6p4S$5>wjffLMX;65IWzgqrV*GXxeq1n&0FE7m?H+_UC*_X|Ps<7+ z)B^r&-9&|V<5Ue_!(t*0R%|=SiQh@{X3U`VFK|#F+>@#hjnv?-Y z=MD_2B5R6l{oACRUUY+djM~I`fE-eb3G1KSMTimyH7`Z$s8i`B$oz4FUV_*1sFz@4 zBJ3r2$&GmlT40=zmtaLgCwr`ap)Yww*P-q=)TwQhYfzK5AP--;@RkJ4dW=5nlOV?D zAbdCM&GWe+tG!Zs4b!7D#L*H8zO;3P9x6pnj8r;4@)98jXTKVqFb!mtS=26=@%KE8k98rZs;AEMb zWG|viwUteMTgQ@eUU5N*k}ULqBO}h<4)RGy34G2mhJ7L*EzTX45*gM$ojWw9WQpaR zY8_Cuh*^+y)zT5KrHEZCUX)$p6XgawU%VoB+JoiKa=IfF^jyvb(7HLfb@;w4_rk8M z!w7p8x6~p9kplj=$lv6aqV(6feerjEUalOTm&IR0%>`JZ0lcw3+h%m3ak2g0}uue?*HH&`}FNnVKZuskJfkUN-h`#9}iQ zK0GSVOx!PiAwNp==~DtGM62{3cm=C;o91VgUIeEa%_bM&Yyk-Yq{q5dR(3C+)Q^Jr zReG5!N0reVRfhYcB{HjxeENpiP+OTBRV(m5Ac#J!E(VVNK^9GCHKK_bc;AV4P(IYX z$_>H@4#7Htkl=`xv)n5HcR3z(d=MP#Golp6jy4nxVNL*#70{KK4sMHTJ%Mm~gmXa# z;Q6z0KCRS%M>hy);R|jasUUp8_ZveBDfQnK>cfsWQPNL7XC>MSqm3xHp_}nc8~Za_ zJZ2LVD$P$>m`{F0^?(h^+Y#&k5RT~EPkkdZ0NCdq3@ace<-iqa=O1~2VVEc!P)%1># zAVe+sQm@|nokD)rYXTv1M(;k@i%PZZV=*9}+4zJUFjMgfK{z7pC=GiMqff)$$s2ZG zDGxgiW5Q9g35sF&@vvvxzFCQE;6uY6^@bg%dwAFZ2Mohr2U!3DERkSVDWV#*i^!jc z@EKH}NAPLcewrU>9*m8mA>b3Tv+U3;J32ZRmY0>3xH!7xw__=;64@*%-#OMN4KkFDW4^fozahOEP3^Gay9r>ymueNJ$F@z63ZRj)wPY z3IaiX;EEHG{8d9V@)yM2qAvveNU5|*8C2P1h#!cKVe&`7u9Gl{X3)k@#ECd}zP1Z? zl=}(cr$wAydnx&>m)ieodMZgNr=PQpq5D#0sD@)ZyE;I3P_xeI&QWeYRaS#gq`FM? zNU*5uY~q3`;34j+#95JE9qi<}iAYNN)TA&5&-rxK>8Z-RY3dGS^I^vXtuP7py( zR%Qve39aHpJr7HRX`y_tNEdis*2~lg^@43E{57pT1c-br=k?u^_b`2X-V^X(Z_au| z_A4tE+vJ3@+$izIdT6vVJKe6bM#|ga8nC$?*zu_HkJIAfaak~6*qOYG3OE{U z%T{f{0@iD6t*>D{moQVFBsO9KPoa94wxc8wXCp-){!K zr?38S`+?JOviW{$Hih$_s|v(&8L5sJu3}rJNDIQP?y5h>3yZ@dljY)Du~{f zj@}KZ*h2i^)1i^bHu|C=%{- zI632iB&K|$Nm7x!cVWoKiY^ky~YtWXsr}ne<&IxFB(SnJ;z<{(MLU|W$Vs$ zIFn%e(FyOyfM*9b0T;`QX*k!N2=NrMhR_I*(9WX+*g8m56bnUxvC-+*OhF@CN2Ce7 za1O-Mo4rR~G;B1K)w*E=uo}EQtS4sYSHrsFZ}IT%-BSUgNu)fn zH-%%s6lAD{QP|A&4QmPdN4A)ea^NH<#ap9w^-V{;;#_=$RIg(VL5+f z|BNt&Bd`&T6+yGZa@)xAz#Y_#^{hNRvS;@QWg~1yssv$?)dosNFtD_J{pD?{T-m66 zH%tZv?iY|t;M`+0#;FI`R`H-wV@JrO2s?KY*oMW8<`O}yxv(&)3OQ%OdWMKY1;Y_I zV}(4&wgAEu4WpFlY-g;VV+dceaUN@jWRNFF2T5}9dMqj59MwzTo|OL_Rdm(k?WJJK zQ%g^zLFiD7={%VR$#D9qet|I>?12V3n|$cDF1QK048RZ*ug8;eaqYybcBHkWdV4Aj zqIyfiJAR7ZIJ-k{+(d`ob|mG{(K9X}f68p7fg@c4PSf25iVbNAT#UdM!lQ9ae}qD8 zj4;_C}3*$t1y z2|AYAZ-6F+$MQ>g$(U}Z?Ir1O`f>}-4o+-hf!RrQwMZw;x&LRXh-R_nD_?bbiKpdJ zr%>#Y(GjKcFJmqfN91{Rv$HoXLrI7Vrk|2*Ca6UU+CqvLYqVkZO}X@x^J(k7>Sad%C}c$8}}^Jss_v*Ia6PWv@m zWo`CZ{og?EbhF{`equz0bH|%_D`vo>T2CoJ-)e_SJ-fH~tL&3q7~l<_$VKvvNxe({ zNbR6IAdXuJ?WX~t`=MT}S1B8MQ^-F~yhi*<&YW~{?otJ_{zJV@%<)JS8Y`@@UL+9L z#BdY+9#geQmgc-hhUG&eP$ap(@AAka(wNn=(+aM^K5GKvhS0|fIdoQWvA-6JIB4g+ zF*1ZP;YltLv4BbTlKkPU@uzLP9S!0L+EdhqwM(_s*BApu123y4PIS>lA?G137_gp_ zU(cEe&00UZOK*iL$_0TcUQt|b)k-ujTBQ;8NNu}aJ}|qqOIv;J=pofnxmE)Q;@F(w zo`tP2+bsLdDed_J6@iL29mKtq6Nc}S_D}4ntdxuAq@kfHG)#rYZo=3@1Lw)GVKb*k z&Os)_wjTK}5pcg30@RFhWQnIMDG3`EOl#vh*kHZH#lU~z6&c}Taey#$1Y#tGx17|B zWqL7X&ja?(V}!2d&DrlNO@&|YSlC&c+DEnhk>C4;DG#>PcI6YG&&tMIIfObKw2)saBLZ=~OG-Z%UnN6<{r&b_SD4z!Ywv zi25QTYKRy7&DhbDM=3tjpTN0Q9QyLkVbje%PVuQ*7;~j{F*>*}KUz?MGpOVlo^)PT zVWQ5{Mf6|L-9MQBy~J z9h~81)KA6NT@58bN&+RS!qYyXWm!?g=AjT^Ixr5fn zv2?$UofsVRx5YW?H4BSD5Tir;2)NgZJwKjCC_pi2M7Y}y&kJgZ(mXh%-2)J17;0cw z(Du0`pNKjmDs788Kwz7xWAvy85N?pFyS?z-Nohfv<~KXUVTwk=Hlht6buEzaKr4I~ zK^?G1p7k4^%zWn@+Udjw{BqU&+|EisQaH4cBA=OGF#M!eF*=|}ML!5B#63^ONcA6- zS7J{I_@4xuaL$6|LL z2lqQHk?wb`kyz+X**9J40Pk^jnh=2eW=?@W;mtIpqnsL!J@jBAj=uJrzt9h1Dcn=85 zk@%5))-I^z(6);yW-%rN-3GAUlpkHwL3d(6(M9&P11?zynweNNla)%)p%MsxoNi3r z)1YDGOk||pXc4fiXqh1xRzXiez-c7~vG&@ExhJVs68MyA<>}4x!78&|xhuumQLoaa z0MdCUsYul#OQnooo0FRviFDSSuX*9^?yQz*20q-{rs|CSG`{K%4hCD6Jv}l=3IYT9 zfSlZPuJJ>}O!rU9m8~sy*SDywUPFcvr@JeC z{97Cd#U+!wfhMV8KE(;P;C?ogf|HBu>$WJgeK>!hR1L}|)kPTQBBo>*9jb#+a1xDp z#HhiJSD;MOoSp93jc|=D<1Qd0JNl+ja%!+{0vjqga)yT#rf)Q%=wl!zQw{gwu5o#3Bj@XaY6K% za9Q!v7)dw48{`yOL2*Pa9Fc~sjpGkE5|qW$3pC?i1+LQi=q{R#s{+A925(j#zh*vs z+GLVcBb-JwK^2-vFn#2m)nDqmavuL;K;Vy|QBhD`SK zZophS16wz3jWH8&F@Ts5>3}H|8DknL>DHl*I5zgfkva|N=`4@(tL2*zq?Ehv?nbXe zcV9rSt~d12*L*1JZaB?%D2fX%vbIZaT!#o}+X5S&!ux0V1T4AuJ2`HMAOYw-!RJtX zq%*O&`e|1g13o{7B}zDU9S%*v?f^r=Q95#f>mLH)FX!MPY#wWTf2|F4L=XroaC@o4 z48rQt4m!vn7a^>6*bavAS(2oVU>+S}N_F%GcLX68*2gq-6zYS(4AC;^HB^wNj^C4M zzZ#Rt0CQpb{h3Y-3%0{tG?2}}Xgd(FEQVPfU}Tcu#666c<|`b1A?=MLbcezeO>-M@ z9ECo)3@+6n@YM*G5(vOj5v}ITZve^V#`#*0yJZ&z`1nj7j;;*V=!P2@PjSHc7-qVv znZ|_O#DoYUqOe(^Ud;C8gWO=c{Rs460@aa=j9HF}jriNc_eN@C5K89|0h~j>4pUNh z?mHTGRmSQ~2>Hw#%Y~Aw@%_PUFOfvz-d2^^_FhY)bFG*0?dV45pTD1|Qb(5!g4IiF zyat~Sp8G;_7dcR^V-D*GHezO@&vNar>p*b=r}W8`)7^6IFAPAek&H0B#==1eqLl#R zj{)a(90($t-qUC>&4|dLa}WK}0R7?xU7&jY0knzLmR2nvXFAD^09l`qq-dmZ(KGP| zSkcu`oir}(i@H#`Cac_zUD8R{QxU@vnsjo0b$2>BxK70BbZRJum!gJ_H_>5~Hfmgt zoVVy_o>Js&xThmIZ(&ToCpjlmLtRpo4zxpy^RZ}(>8W86ZpuW~%d~&pOQb+YjR7j) zKDdb?3g9QEXk@SoKz4$3pXDnmNQc*&IWmv2rLxXy#?jk7rg4}Ba~h2ipG6B_&^Sh0 zmCRa!H1@gamY#=78YaJ8e`-wD^D*5tOx~x0-yai-T6mbO*O@IiIRYi8>_u{>5O@)o zTuA|vplevcVAGHkOdikLGzC+@fQ|~LE5p(h3?_FG!#e7hLWWrjak;boc3&5Cl=nRp z49c8B!Q{0om||`{t>tbubWo+}2K^Fo!f+jt7IdAk6Q$W#E{sEo`sfBIWY}Sg^{mVLnlzssh!B4Ve5ZXMfV6TR7O#G~yuf#>HxL*Z! z;Rt$GAJns-tUY)oq-Ff1p)e9{+2s7_6k=y7#YExL%|7g{CMj}f-+&)5@*zI@(DG`- z##BR!KJ%SjONa)<z7<497Vi9C5Po(++|tJr%oA zoETQ7;kQP>Z(Z>lW)krmuhB8Sf`)Ie%W-t&4{bu<|F5#!`7VBcUv}5_*>LMASZ$`x zD|t+(Dfl~*3AY z73nB`boH64xR>fGXRpaL_mZLQt{GAYX&|HDS)yBqXcjBkFV|uTL%z4BYd`eNcYUDS z$XJOc5DYZ%8%Xrih3UQo2AYe?!rObu33t!^w=TfUdj`of?z4isskcbvO1XLCpn<&0 zpmr*O3UaWULduJ_Fx&PR^tSzi$T3|vWv@+VRskzGHCh5k_7Ffo3ctMs^&52H?%+r_ zetwcB5McU4ixc4y_KJ;YH!Sbo6z|SQoKe|?wSZU`orVqBzS&UMIO2p=A4ihqN1J-} z`4b^ZaWdFTwD`i-gQhnu<>32hj-xsNf0C7(&-O9)^4iUPa_LJ`iyG7roCaFS<+?42 z&fKI9-Ab;z0Ox|(!Srs({QSY5nJ1hylkYy*x6=tQYFo;!y{x}6dgR^Ft;@eB<*QqJ z$j`Uf*o?{Cnk)F)P1S5+x{x2*CdCA!1BkqX3OmSC00>>phxP|$n7CjW@3zYNtvRs0 z&GFc&@KIi!bhqZo&JT6U({k**Y zks@l~xktwOm8C8}f5<)&r(xSx>bS}9+P2CQa{`Z^BmPrPdUU7$&!o)z<$hVWtHW{0keESe8jhL&lH zBtz#$W%l;$oFJS8-ZWj@m|iw>yEOMAB($clyOP|$A-NhaKI4& z`T+-@lSv_Km<&8|C`8AuJD-~6S?GOX@_}1eCp~hhBd|k>F!1(~VUHjPl>(_82BPbE zXj;c@1T0@qBR5?u)vl*hwMG{(kox9bP5~LZ z8!-m00=bbYh4FK4KzD3d;d>aHM!5gz+?WR4r7@U}BH4|uLe=>@uShzE*g8mM*`9zd ztx-Q0i?5O7VDN=Cu)v6QjTXYaC;NjYKK-8SfscS0<3gKh$&WcjC^30t>*2dY=jgjD zN;wZM!(U{kI*%1ayHM<)Os>7Zvs*~NRl#}>%~G*4tS3+u9b;y(E>ZlBEs^AG`xP~s zZ(Wa$wOB#4vj^YH@InusAI%qTaxLe?5QwLEGo*V7t zRd|5mojiC>G~0te-T~ezn&rXwGCad8pUpR>iGX*~;chG|%14ZlahNkw9a}j5tSCO3 zULlsLej5VizwH3eh~ls?b7(w|r#Ryb57P)m&bY!q z7@p(7!+edI%HQ$^buiF_hxj5o!FMve%!3EjEg8W7#PA*-JfK2HfUnxeKd+WzkzXAY zL&m+Ny4xu5(Rp1p_6#rb8Zv41W%%n1_hbTIa;gFembc_6aiI!iMBrD3XmaVLu5Q!S z5M8+}wB}Q|(85Hf^PlX;&{+)vMggSR#wQTSo1iJbOQW;aY;({b)4B0BppJ}`w8xRa zM58|=)w+kw_S1TkX%`joz?4zr93b7|RHM*7tphy!-fdiL zR9;U>M~l2D4?i#-{xU5iaj2HKw*9Q1cM`BhOzV)mWPOiuzzMf4paby{!g50|)`|2| zE)J}iP@BokQ5FiGb45~~s1FmI+$FhvegACmmQMB|GVkozLmmjQ2gcV-cyeBgZ zho#!k2V5Dhd>4%nokr)0_9{$?YfyY-x25b^>=~xpvuN1wB#sQ$uB*}y*Kw$7A zgd|9|fQ0Y@5IH8}j~BX+eF7+=Uvy!BzX?4w%<(XdKFK9|kV+A&9mHZdK_?DM^i2fk zy6Ov{ZC-~DE1gFmCmmb&8LslnQm((Ed&Uj;t3I{WE(`f@mHz-IvsbS%P4^3I+RM$6>UY$ z*Pmu1A7%iGTWeH9tL2C%M!GAhD3477EI|EoEo9xIN)Y4m52qW6rRXmT$fob8kif|; zuoVo_uu&-}aLJkp-`<)VnXGvQRMT?WlV{g0(RDh++nqY&GiSOoOi+^LjFEsrL#ZeX zd7Wr4v)gQy9)R>{biUjtzj(4ZyNrG;%_gl?s`p5k2*XHw$LW)x(rhFU=Ej-_`XCSj zgKZ+k>W@5n(q6ba1U-k!xI_iIHD^8BF)2SrLtm-0YLQ>atxp#F7(Mygj)bl-kg=zF z=<5&2)jJC0xTi`_f0a5Ta|0Hs;tkX+DQxsY?i(cCW>?K2YbHoe8}6fTd8!b{-u65- z`4l^>w9!?U&JK`iP&%>SwBPsCMm!9J%b7J{7jkKg|aBmQ9mc z_#HSKbYi0Zgam=W_}K){u`%WTXLb^$Yo0xOcsd_(lhz{?Zr=J--t=5$lsEGEXA1$?{oFHRl}tWAaQK1WqAbo*LxsSM zE1C_vzqQmjO06dXBQ$FRV@s-v?!fKm(m|BwJo)G6XXv{=kQeM6lA{W$Xe07y; zJX-$C=|Xe(|Dj^j^dBWIub5oayz~OsQyI(9*hK-jvp+rr9&DtiNh*%aoSZ`suS9$`=i) znp!omeBO-mtFM|nv+3%V@;NOFXH1!W)$~fLL+_U68T^f(X?UrJlrQF#)X%6Iba{RK zY5iuLK4`}D88c?~>)+5&eOkXk(=Q(|y{cjGfcom0)t3*hlKWn)>~RtiIu zRYHu-O{c^YKzdcV!Sb#F{f#6%bWkc zP%c0Ahl=_+O$+9>HcfAAn9$1g{{xmRZXrf0-w_=7<`(9OKV zkafQqu>H%o`wCa{3t>X`#Kfnh+Mt1UJxttbqyAa9-`5l zrO(wLF&@>Q)%WRd>TgBg4!xtltN&IU@_nrTUi`s4qJM55HIM24@_i+uy@#H0?)X*r z-FN>FZ;?NF;FnL|@Tfl!sv3UA1%KWDrkRspRegbbp}XbbN1i+VQ1*>C-FBZD%gD+u z?LTnHsM@--&mBLr;pUaMu6p8ymv-;@)jLz3c(Sl45DZ6hI#&%IvT5^y_d?aH*K7)e zhn{iyRjY2#YMQ$9^Di!*{?yZ7etrD>iFe&yQQ5m>(!Fcf{e1n#O%FZ&>~4P~n%i~A znWN6zu<`X@uMHG*N%TD9%#YkZeD=lhm-m=<_ny5<1`HZ9=In73&YyI_lI2!z?#0H$-Jca%oqie`b-{Bh<~;*EiD4 z=#$*y?_u^ZOM(L<=Nbc}OR7V8;b8vIQG<;c!BD?EU)(7474{lrj`dZV;eZ-278g5l(b%Mzm^VSlXC5P#U8Q&eVlPChkk z=K0Yvp>XY}!ZE?~V{Tm_d_iz>A|vdt4RMOS}@8C%*FR3Zc8sZa6 z_V-D?)7KQqT~%P$q2xbG$C+VMUzRm;-0;|>L^Dmx$jZPnO?$+nU=q zKl=1DFYkHvwGR(}dR#MkVpI^uCa);4X1(!9BBX2bF| zci;Q!8~b8er9*~}s=M%#%cjn3xOL5D)Oh*Tj}Cu&G?q20Ze~Mr`7fV!pWpfRyGQ@L z?D|{QZ+L#^%dhPF?fYZyeD2qK-q=@n?)VEYx@_uAx2<~gi6?iyu;-O`v+_D$GUf08 z`1W{m&ioHQ$|#=ORMd6qj}|}t$cG=D^USk(ox2s+jy`uhO`XN=<1fGU_Q9in{#$d) zs@4U)Dk?WV^5o7}_PzVjU0Tgg@9ej#_>JS|j=%VlK+w&!dRKn_#oVUq;b)E*b^a9# z_P)CR%>(cK;oIYyJvFiPBXjA;HTJm5UT0{%c&ctU1& zU{b&^i^3rzXao!$|4(31(}(}hFp-h#J2y}mxGXvy5`6x-5TYbcort=Tv)+ z+35C6?)5F*W_0l{{l>T`kQd4ik=!+6zI5?l6zJ=#4VU4E@`TYpQf79+E^YEbWR1&7 zeiXC`mAUc(n-E zSNDj;2W`z*H@GrCKIE_6;$v$Dt~BH8$reTei8L+4srnnx-YB{5ox+|#3%8{-&Gg>1P-oyt z{X;=5Q(p7=(BWTW`Ja!}OjMx~DN3HjH1ny{U{~4egS_%o?!K zdT<}lAM7LZ2kWc1N5EuDun89k}|b@=YFJ@#3(?xxr`7exvHw(z8wmxb?a zJTxryFNlYjnu8}7PadAmc=GX3J<6jtXqXG}ko_~~(qFw(HsMb*7C9R(oL_j$Q+=0Q zBA&b9yw9SKy?D>zS6{)F>$ora#eNMT>4Vab5+O|9eP48IgFXppOuqL;v2{8I>{67Y z-plZ8-~XF^y4%!xWka*gw%CHXGhifM(bRm^wGA^BsA*mU49BaQ=GrX_X3S`4X}NsC zY*eLxDT2D%|6`VYWqpf1x2e^h-q0}DCJ36nys6nHOBY^=rk$>5E1XDJ zX%Oh&_M=DF>ayhMUYD9p@sYmiA$}5HQ-Vp<5YI_)>6@NRJS37-mL}aGJj7e#Hk7xWgr!z!J>w#6Z)ot^i2 i32` | Must return `1`. | -| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). | +| `vc_abi_version` | `() -> i32` | Must return `1`. Needed only by a module without a `vc_manifest` custom section. | +| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). Needed only by a module without a `vc_manifest` custom section. | | `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. | | `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. | +### Manifest section + +A module may carry its [manifest](#manifest) in a [custom +section](https://webassembly.github.io/spec/core/binary/modules.html#custom-section) named `vc_manifest`, holding the +same UTF-8 JSON that the `vc_manifest` export returns, plus `"abi": 1`, the ABI version that `vc_abi_version` returns. +The host then reads the manifest from the section and loads the module without instantiating it: no start function, +`vc_abi_version`, `vc_manifest` or data segment initialization runs when the module is installed, inspected or loaded at +startup. The host checks the imports against the manifest's permissions, the exports `memory`, `vc_alloc` and `vc_run` +by their types, that the initial memory fits in the [linear memory limit](#the-sandbox), and that the module defines at +most 4 tables of at most 100,000 elements each. The module is instantiated for the first time when it runs, and a start +function then runs at the start of each run. + +- A module with more than one `vc_manifest` section, or one longer than 64 KiB, is refused before the section's contents + are decoded. A section that is not UTF-8, not JSON or not a valid manifest is refused too, and so is one whose + manifest does not give `"abi": 1`. +- When a module has both the section and a `vc_manifest` export, the section is the manifest and the export is never + called. Keep both to load in versions of VectorCraft that read only the export. +- A module without the section is loaded as before: the host instantiates it and calls `vc_abi_version` and + `vc_manifest`. + ### Host imports (API level 2) A plug-in whose manifest gives `"api": 2` and lists the [permission](#permissions) an import needs may import these @@ -860,10 +880,15 @@ crates/plugins/example/build.sh # cargo build --release --target wasm32-unk ``` The script also refreshes `crates/plugins/tests/fixtures/desaturate.wasm`, the test fixture built from that source. -The crate is not a workspace member. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, +The crate is not a workspace member. It puts its manifest in the [manifest section](#manifest-section) with a byte +array static marked `#[unsafe(link_section = "vc_manifest")]` (the Rust Reference's +[`link_section`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute)), and keeps the +`vc_manifest` export for older hosts. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, WAT…), as long as the module imports nothing but the host imports: in Rust, `std` on `wasm32-unknown-unknown` is fine as long as it never touches WASI. `vectorcraft_plugins::wat::module` is the skeleton of a plug-in in WebAssembly text, -which the tests build their plug-ins from; `wat::echo_exporter` is an exporter whose file is its input or its parameters +which the tests build their plug-ins from, and `wat::sectioned` the same plug-in with its manifest in the [manifest +section](#manifest-section) and no `vc_abi_version` or `vc_manifest` export (in WebAssembly text, a custom section is +written `(@custom "vc_manifest" "…")`); `wat::echo_exporter` is an exporter whose file is its input or its parameters (with a base64 encoder written out in WebAssembly text), which the tests read back what the host hands a plug-in with, and `wat::when_given` a plug-in whose output depends on whether its input or parameters hold a given text, which shows in a live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..f79103b179 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2655,6 +2655,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. - **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. From a93cd03c35add317bf072785d97bc87425696d01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:44:34 -0800 Subject: [PATCH 023/145] Type: text commands refuse a parameter of the wrong type text.editRange's insert, text.setText's text and text.createInPath's mode and text must be strings, text.createInPath's at must be two numbers, and start in text.touchType, text.glyphAlternates and text.setGlyphAlternate must be a whole number of at least 0. A wrong value was read as left out (an edit inserting nothing, area type, no start point) or reported as a missing start; it is now an error naming the parameter, and the document and undo history do not change. Null still reads as the parameter left out. Pathfinder precision no longer reads the leading number of a string such as "1abc"; a number, a string that is all one number and a length with a unit ("10 pt") still read. --- crates/engine/src/cmd/pathops.rs | 7 ++--- crates/engine/src/cmd/textedit.rs | 34 ++++++++++++++--------- crates/engine/src/cmd/typecmd.rs | 4 +-- crates/engine/src/tests/pathops.rs | 6 +++++ crates/engine/src/tests/textedit.rs | 42 +++++++++++++++++++++++++++++ docs/mcp.md | 13 ++++++--- docs/target-app-parity.md | 1 + 7 files changed, 83 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 96b9e51f99..1793f17d5c 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -199,14 +199,11 @@ pub fn specs() -> Vec { // ---------- helpers ---------- -/// Number param that also accepts strings like `"10 pt"`. +/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`). pub(crate) fn num_param(p: &Value, key: &str) -> Option { match p.get(key)? { Value::Number(n) => n.as_f64(), - Value::String(s) => { - let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); - t.parse().ok() - } + Value::String(s) => whole_number(s), _ => None, } .filter(|v: &f64| v.is_finite()) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0d75061bee..3af85a8265 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, - number_or, object_param, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection, + index, number_or, object_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option { /// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any /// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result { + Ok(offset_given(p, k, cmd)?.unwrap_or(default)) +} + +/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any +/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. +fn offset_given(p: &Value, k: &str, cmd: &str) -> Result> { match p.get(k) { - None | Some(Value::Null) => Ok(default), - Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)), + None | Some(Value::Null) => Ok(None), + Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))), } } @@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?), }; - let insert = str_param(p, "insert").unwrap_or("").to_string(); + let insert = text_param(p, "insert", C)?.unwrap_or("").to_string(); let clear = clear_param(s, p, id, C)?; let caret = s.edit("Typing", |d, _| { for other in &clear { @@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve /// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error /// when there is no character there, it is an inline graphic, or its font is not available. fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range, std::sync::Arc)> { - check_numbers(p, &["start"], c)?; - let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; let mut at = 0; for run in &t.runs { let end = at + run.text.len(); @@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result { fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; - check_numbers(p, &["start"], C)?; - let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation")); } @@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { fn create_in_path(s: &mut Session, p: &Value) -> Result { const C: &str = "text.createInPath"; let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; - let on_path = match str_param(p, "mode").unwrap_or("area") { + let on_path = match text_param(p, "mode", C)?.unwrap_or("area") { "area" => false, "onPath" | "path" => true, o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))), @@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { check_switches(p, &["vertical", "placeholder"], C)?; super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p, C)?; - let text = str_param(p, "text").unwrap_or("").to_string(); - let start = match point_param(p, "at") { + let text = text_param(p, "text", C)?.unwrap_or("").to_string(); + let at = match p.get("at").filter(|v| !v.is_null()) { + None => None, + Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?), + }; + let start = match at { Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0), _ => 0.0, }; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 185baf734f..2a62a46374 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -13,7 +13,7 @@ use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or, - object_param, ok, str_param, switch_or, targets, text_param, + object_param, ok, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option, mut f: i } fn set_text(s: &mut Session, p: &Value) -> Result { - let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); + let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); let ids = text_targets(s, p, "text.setText")?; // The text the type already has is no undo step. edit_if_nodes_changed(s, "Typing", &ids, |d| { diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index feb71e40ad..6bd92225db 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() { assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set); let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap(); assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}"); + for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] { + let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap(); + assert_eq!(r["precision"], json!(want), "{given}"); + } s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap(); for bad in [ json!({"precision": 0}), json!({"precision": 11}), json!({"precision": "x"}), + json!({"precision": "1abc"}), + json!({"precision": "0.5 extra"}), json!({"precision": -1}), json!({"removeRedundantPoints": "yes"}), json!({"removeUnpainted": 1}), diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..d49b18b031 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() { s.execute("text.setPathHandle", &handle(Value::Null)).unwrap(); } +/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong +/// type with an error naming the param, and leave the document and the undo history as they were: +/// text that is not a string, a byte offset that is fractional or negative, and a point that is not +/// two numbers. Null counts as a param left out, which keeps its default. +#[test] +fn text_edits_refuse_a_param_of_the_wrong_type() { + use crate::tests::not_refused; + let mut s = session(); + let id = text(&mut s, "abc"); + let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone(); + let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone(); + let string = |k: &str| format!("`{k}` must be a string"); + let whole = "`start` must be a whole number".to_string(); + let point = "`at` must be a point: [x, y]".to_string(); + let calls: Vec<(String, Value, String)> = [ + ("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")), + ("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")), + ("text.setText", json!({"ids": [id.0], "text": true}), string("text")), + ("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")), + ("text.createInPath", json!({"path": frame, "text": true}), string("text")), + ("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()), + ("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()), + ("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point), + ("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()), + ("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()), + ("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()), + ("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole), + ] + .into_iter() + .map(|(cmd, p, msg)| (cmd.to_string(), p, msg)) + .collect(); + let wrong = not_refused(&mut s, &calls); + assert!(wrong.is_empty(), "not refused: {wrong:#?}"); + // Null keeps each default: nothing inserted, area type with no text, no start point. + s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "bc"); + let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap(); + let t = obj(&s, NodeId(r["id"].as_u64().unwrap())); + assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind); + s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap(); +} + /// Where each glyph of type object `id` is drawn from (its origin in font units), document space. fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> { let t = obj(s, id); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..6848635a23 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2430,11 +2430,15 @@ with `` `font` must be a string ``, and a `features` list with an entry that is `text.setStyle` and `text.setRangeStyle` refuse a `size` outside 0.1 to 1,296 pt with `` `size` must be from 0.1 to 1296 `` and change nothing. `type.ruby` refuses a `text`, `position` or `align` that is not a string, and `text.setPathHandle` refuses a `which` other than `in` or `out` with -`` `which` must be one of in, out ``. Each leaves the document, the selection and the undo history as they were, also -when the call gives another param it could apply. A null is read as a key left out. +`` `which` must be one of in, out ``. `text.editRange` refuses an `insert` that is not a string, `text.setText` a `text` +that is not a string, and `text.createInPath` a `mode` or `text` that is not a string, each with +`` `insert` must be a string ``, naming the key; `text.createInPath` refuses an `at` that is not two numbers with +`` `at` must be a point: [x, y] ``, in area mode too. Each leaves the document, the selection and the undo history as +they were, also when the call gives another param it could apply. A null is read as a key left out. A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in -`text.editRange`, `text.getRange` and `text.setRangeStyle`, and in `type.step` and `addon.type.textTweaker` given an `id`, +`text.editRange`, `text.getRange` and `text.setRangeStyle`, `start` in `text.touchType`, `text.glyphAlternates` and +`text.setGlyphAlternate`, and `start` and `end` in `type.step` and `addon.type.textTweaker` given an `id`, refuse a negative or fractional number with `` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. @@ -6207,7 +6211,8 @@ editing the pattern first". While a mask is edited, `object.pattern.edit` and `o Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoints?, removeUnpainted?}` (or `prefs.get`/`prefs.set` with key `pathfinder`) reads and sets the options every later Shape Mode and Pathfinder -operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit also reads) is how closely results follow +operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and +any other string, such as `"1abc"`, is an error) is how closely results follow the paths (they are refit to within it and pieces thinner than it are dropped), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c4508481b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -946,6 +946,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. +- **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. From 342341a55f230235436f1fb83aac347b826ff936 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:42:48 -0800 Subject: [PATCH 024/145] Smooth: path.smoothRegion and path.joinScrub refuse a radius, fidelity or tolerance outside its range path.smoothRegion read a radius below 0 as 0 and moved a fidelity into its range, and path.joinScrub read a tolerance below 0 as 0. Each now refuses a value outside its range with an error naming the key, and the document, the selection and the undo history do not change: radius and tolerance 0.001 to 1000 pt (the Path Eraser's width range), fidelity 0.000078125 to about 3195 pt (the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom). A key left out or null keeps its default. The Smooth, Join and Path Eraser tools, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, keep what they send within these ranges at any zoom, also when the interface zoom puts the tool's zoom past the view's range. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 4 +- crates/engine/src/cmd/draw2/smooth.rs | 16 ++++--- crates/engine/src/tests/draw2.rs | 60 +++++++++++++++++++++++++ crates/tools/src/draw2.rs | 5 +++ crates/tools/src/draw2/gesture.rs | 24 +++++++--- crates/tools/src/draw2/gesture/tests.rs | 39 ++++++++++++++++ docs/mcp.md | 8 ++++ docs/target-app-parity.md | 1 + 8 files changed, 144 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..9c3dcbd47a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes", has_selection, smooth_region ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes", has_doc, join_scrub ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..52b18c3a31 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,9 +1,9 @@ use vectorcraft_pathops::addons::pathtools as pt; -use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; +use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths}; use super::{ - Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json, - number_or, po, + Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad, + json, number_or, po, }; // ---------- Smooth ---------- @@ -733,8 +733,12 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.smoothRegion"; let pts = points_param(p, "points", C)?; - let radius = number_or(p, "radius", 12.0, C)?.max(0.0); - let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; + let tol = number_or(p, "fidelity", 2.5, C)?; + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + if !(lo..=hi).contains(&tol) { + return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); + } let sigma = radius * SMOOTH_SPREAD; let st = s.doc()?; let mut plan = vec![]; @@ -882,7 +886,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { const C: &str = "path.joinScrub"; let pts = points_param(p, "points", C)?; - let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0); + let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; let st = s.doc()?; let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)); // Paths that cross with their ends scrubbed are trimmed there and joined (#5844). diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..fe151dd7bb 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3313,6 +3313,66 @@ fn path_eraser_width_outside_its_range_is_refused() { } } +/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the +/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the +/// document, the selection and the undo history do not change. The ends of each range are taken, +/// and null is read as the key left out, which smooths or joins in one undo step. +#[test] +fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() { + let mut s = session(); + let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]}); + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)]; + let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)]; + let refused = reaches + .iter() + .map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string())) + .chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt")))); + for (key, x, want) in refused { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want); + assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection"); + } + for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] { + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}")); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + } + let before = path(&s, id); + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap(); + assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing"); + assert_eq!(undo_steps(&s), undo + 1); + + let mut s = session(); + line(&mut s, 100.0, 100.0, 200.0, 100.0); + line(&mut s, 205.0, 100.0, 300.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let scrub = json!({"points": [[202, 90], [202, 110]]}); + for x in &reaches { + refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000"); + assert_eq!(paths(&s).len(), 2, "tolerance {x}"); + } + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap(); + assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end"); + let undo = undo_steps(&s); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap(); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap(); + assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing"); + assert_eq!(undo_steps(&s), undo + 1); +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 3c663006e5..800cda5d94 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -50,6 +50,11 @@ pub const SMOOTH_MIN_TOLERANCE: f64 = SMOOTH_MIN_FIDELITY / 640.0; /// pixels) at the lowest zoom (3.13 %). pub const SMOOTH_MAX_TOLERANCE: f64 = 100.0 / 0.0313; +/// The range (points) of `path.smoothRegion`'s `radius`, `path.joinScrub`'s `tolerance` and +/// `path.eraseSegments`' `width`, which the tools send as screen pixels divided by the zoom. +/// VectorCraft's own range. +pub const REACH_RANGE: (f64, f64) = (0.001, 1000.0); + /// Whether segment `i` of `sp` is straight, so the Smooth tool leaves it as it is: its handles lie /// on the line through its ends, and the segment runs from one end to the other without turning back. pub fn segment_is_straight(sp: &SubPath, i: usize) -> bool { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index dc123e6cc1..ab88d16436 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -96,6 +96,20 @@ fn fit_tolerance(cx: &ToolContext, px: f64) -> f64 { cx.tol(px).clamp(super::MIN_FIT_TOLERANCE, super::MAX_FIT_TOLERANCE) } +/// The `fidelity` (points) the Smooth tool, and an Alt smoothing drag, send `path.smoothRegion` for +/// `px` screen pixels at the current zoom, within the range the command takes +/// ([`super::SMOOTH_MIN_TOLERANCE`]..[`super::SMOOTH_MAX_TOLERANCE`]). +fn smooth_tolerance(cx: &ToolContext, px: f64) -> f64 { + cx.tol(px).clamp(super::SMOOTH_MIN_TOLERANCE, super::SMOOTH_MAX_TOLERANCE) +} + +/// The distance (points) the Smooth, Join and Path Eraser tools send for `px` screen pixels at the +/// current zoom, within [`super::REACH_RANGE`]. +fn reach(cx: &ToolContext, px: f64) -> f64 { + let (lo, hi) = super::REACH_RANGE; + cx.tol(px).clamp(lo, hi) +} + pub struct GestureTool { /// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was /// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]). @@ -1550,13 +1564,13 @@ impl GestureTool { fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec { let pts = &self.points; let has_sel = !cx.selection.is_empty(); - let tol = cx.tol(self.edit_within); - let radius = cx.tol(SMOOTH_RADIUS); + let tol = reach(cx, self.edit_within); + let radius = reach(cx, SMOOTH_RADIUS); if self.smoothing { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity)}), )]; } return vec![]; @@ -1621,10 +1635,10 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity)}), )] } - "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": cx.tol(8.0)}))], + "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": reach(cx, 8.0)}))], "join" if pts.len() >= 2 => vec![Action::Exec("path.joinScrub".into(), json!({"points": points_json(pts), "tolerance": tol}))], _ => vec![], } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1ffcf1c37b..dbbbb53a78 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -309,6 +309,45 @@ fn fidelity_sent_stays_within_what_path_freehand_takes() { } } +/// `path.smoothRegion`, `path.joinScrub` and `path.eraseSegments` refuse a radius, Fidelity, +/// tolerance or width outside their ranges, so at a zoom beyond the view's range the Smooth, Join +/// and Path Eraser tools, and an Alt smoothing drag, send the nearer end of each. +#[test] +fn smooth_join_and_path_eraser_send_values_their_commands_take() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let (reach_lo, reach_hi) = crate::draw2::REACH_RANGE; + let (tol_lo, tol_hi) = (crate::draw2::SMOOTH_MIN_TOLERANCE, crate::draw2::SMOOTH_MAX_TOLERANCE); + let alt = Mods { alt: true, ..Default::default() }; + for (zoom, fidelity, reach, tol) in [(0.001, 100.0, reach_hi, tol_hi), (100_000.0, 0.05, reach_lo, tol_lo)] { + cx.zoom = zoom; + // The same drag on screen at each zoom. + let pts: Vec<_> = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)].iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let sent = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) => (c.clone(), v.clone()), + a => panic!("expected a command at {zoom}x, got: {a:?} in {acts:?}"), + }; + let mut smooth = GestureTool::new("smooth"); + smooth.set_option("fidelity", &json!(fidelity)); + let mut pencil = GestureTool::new("pencil"); + pencil.set_option("altSmooth", &json!(true)); + pencil.set_option("smoothFidelity", &json!(fidelity)); + for (what, acts) in [("smooth", drag(&mut smooth, &cx, &pts, Mods::default())), ("pencil", drag_held(&mut pencil, &cx, &pts, alt))] { + let (c, v) = sent(&acts); + assert_eq!(c, "path.smoothRegion", "{what} at {zoom}x"); + assert_eq!((v["radius"].as_f64(), v["fidelity"].as_f64()), (Some(reach), Some(tol)), "{what} at {zoom}x: {v}"); + } + let (c, v) = sent(&drag(&mut GestureTool::new("join"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["tolerance"].as_f64()), ("path.joinScrub", Some(reach)), "join at {zoom}x: {v}"); + let (c, v) = sent(&drag(&mut GestureTool::new("pathEraser"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["width"].as_f64()), ("path.eraseSegments", Some(reach)), "path eraser at {zoom}x: {v}"); + } +} + /// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its /// stroke, and another tool chosen while it is drawn, send it as set at any zoom. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..612bfb775a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7062,6 +7062,14 @@ VectorCraft's own values. `` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. Left out or null, `width` is 8 pt. The range is VectorCraft's own value. +`path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt with +`` `radius` must be from 0.001 to 1000 `` and a `fidelity` outside 0.000078125 to about 3195 pt (the Smooth tool's +0.05 to 100 px at the highest and the lowest zoom) with `` `fidelity` must be from 0.000078125 to 3194.8881789137376 pt ``. +`path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt with +`` `tolerance` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is +recorded. Left out or null, `radius` is 12 pt, `fidelity` is 2.5 pt and `tolerance` is 12 pt. The tools send these in screen +pixels divided by the zoom, kept within the ranges. The `radius` and `tolerance` ranges are VectorCraft's own values. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c513bfcca8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1461,6 +1461,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. + `path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt or a `fidelity` outside 0.000078125 to about 3195 pt with an error naming the key, and `path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt the same way; the document does not change; before, a radius or tolerance below 0 was read as 0 and a fidelity was moved into its range. Left out or null, the defaults stay (12 pt, 2.5 pt and 12 pt), and the tools keep what they send within the ranges at any zoom. The radius and tolerance ranges are VectorCraft's own values (engine `smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range`). Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). Eraser Tool Options show the Blob Brush's tip preview under the Roundness rows. A drag on the arrowhead turns the Angle, and a drag that starts on a black dot moves it toward the center for a flatter tip or away from it for a rounder one, as the Eraser tool options section of the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133) describes; the fields show the new values, and OK keeps them. The drag's mapping and the Angle and Roundness sliders are the Blob Brush preview's, which are VectorCraft's own, with the Eraser's Roundness range of 1% to 100% for the drag and the keys. The preview shows the set Angle and Roundness, not a Random or pen-driven variation of them. Regression tests: `dialogs::tests::the_eraser_tip_preview_sets_the_angle_and_roundness_by_dragging`, `dialogs::freehand::tests::a_roundness_dot_keeps_the_eraser_at_one_percent_or_more`. The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). From 5a2eae86a7fb9bae02a417dfb81bc4215bef5199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:43:00 -0800 Subject: [PATCH 025/145] Smooth: a drag over a long path measures only the anchors and segments near it A Smooth drag measured every anchor of each path against every stretch of the drag, and every curved segment's box against every stretch twice, so a release on a path of 100,000 anchors made tens of millions of measures however short the drag was. - The drag's stretches are listed once per release in a grid over the drag's bounds grown past the reach. An anchor outside those bounds is out of reach without measuring, and a point or box is measured only against the stretches listed in the cells it covers. Every query gives at least the stretches the whole-drag measure finds in reach, so the marks, the cuts and the smoothed path are the same as before. - The refitted runs of a path are put back from its end without moving the rest of the anchor list for each run. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801. --- crates/engine/src/cmd/draw2/smooth.rs | 344 ++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 325 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..5667922907 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use vectorcraft_pathops::addons::pathtools as pt; use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; @@ -421,6 +423,8 @@ fn drag_stretches(pts: &[Point]) -> Vec { /// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both /// axes: every stretch within `radius` of a point in `r`, and perhaps a few more. fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec { + #[cfg(test)] + STRETCH_TESTS.with(|c| c.set(c.get() + of.len())); let r = r.inflate(radius, radius); of.iter() .copied() @@ -432,8 +436,115 @@ fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec = const { std::cell::Cell::new(0) }; +} + +/// Most grid cells [`DragReach`] lists one stretch of the drag in. A stretch whose reach covers more +/// is measured against every point and box instead. +const MAX_STRETCH_CELLS: usize = 64; + +/// Most grid cells across the drag's bounds on each axis in [`DragReach`]. +const MAX_DRAG_CELLS: f64 = 1024.0; + +/// The stretches of a Smooth drag listed by the cells of a grid that their reach covers, so that a +/// point or a piece of path is measured only against the stretches whose reach it is in. Each query +/// gives at least every stretch that measuring against the whole drag finds in reach, so the results +/// are the same as measuring against the whole drag. +struct DragReach<'a> { + pts: &'a [Point], + radius: f64, + /// Every stretch of the drag, in order. + all: Vec, + /// The drag's bounds grown by more than `radius`, with the cell size; `None` when the drag or + /// the reach is not a finite number, and then every query gives every stretch. + grid: Option<(Rect, f64)>, + cells: HashMap<(i64, i64), Vec>, + /// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells. + wide: Vec, +} + +impl<'a> DragReach<'a> { + fn new(pts: &'a [Point], radius: f64) -> Self { + let all = drag_stretches(pts); + let mut reach = DragReach { pts, radius, all, grid: None, cells: HashMap::new(), wide: vec![] }; + if pts.is_empty() || !radius.is_finite() || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return reach; + } + // Enough more than the reach to cover the rounding of each distance and box measured. + let size = pts.iter().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs())); + let pad = radius + 1e-6 * radius.max(1.0) + 1e-9 * size; + let area = poly_bounds(pts, pad); + let cell = pad.max(area.width().max(area.height()) / MAX_DRAG_CELLS); + if !(cell.is_finite() && cell > 0.0 && area.width().is_finite() && area.height().is_finite()) { + return reach; + } + reach.grid = Some((area, cell)); + for &k in &reach.all { + let Some(&a) = pts.get(k) else { continue }; + let b = pts.get(k + 1).copied().unwrap_or(a); + let r = Rect::from_points(a, b).inflate(pad, pad); + let ((x0, y0), (x1, y1)) = (reach.cell_of(Point::new(r.x0, r.y0)), reach.cell_of(Point::new(r.x1, r.y1))); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_STRETCH_CELLS as i64 { + reach.wide.push(k); + continue; + } + for x in x0..=x1 { + for y in y0..=y1 { + reach.cells.entry((x, y)).or_default().push(k); + } + } + } + reach + } + + /// The cell `q` is in, counted from the corner of the grid. + fn cell_of(&self, q: Point) -> (i64, i64) { + let Some((area, cell)) = self.grid else { return (0, 0) }; + (((q.x - area.x0) / cell).floor() as i64, ((q.y - area.y0) / cell).floor() as i64) + } + + /// Whether `q` is within the reach of the drag, and `slack` more. + fn in_reach(&self, q: Point, slack: f64) -> bool { + let limit = self.radius + slack; + let Some((area, _)) = self.grid else { return dist_to_stretches(self.pts, &self.all, q) <= limit }; + if !(q.x >= area.x0 && q.x <= area.x1 && q.y >= area.y0 && q.y <= area.y1) { + return false; + } + let listed = self.cells.get(&self.cell_of(q)).map_or(&[][..], Vec::as_slice); + dist_to_stretches(self.pts, listed, q).min(dist_to_stretches(self.pts, &self.wide, q)) <= limit + } + + /// The stretches, in order, that may come within the reach of `r`: at least every one that + /// [`stretches_near`] gives for `r` from the whole drag. + fn near_rect(&self, r: Rect) -> Vec { + let Some((area, _)) = self.grid else { return self.all.clone() }; + let (x0, x1, y0, y1) = (r.x0.max(area.x0), r.x1.min(area.x1), r.y0.max(area.y0), r.y1.min(area.y1)); + if !(x0 <= x1 && y0 <= y1) { + return vec![]; + } + let ((cx0, cy0), (cx1, cy1)) = (self.cell_of(Point::new(x0, y0)), self.cell_of(Point::new(x1, y1))); + if (cx1 - cx0 + 1).saturating_mul(cy1 - cy0 + 1) > self.all.len() as i64 { + return self.all.clone(); + } + let mut out = self.wide.clone(); + for x in cx0..=cx1 { + for y in cy0..=cy1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + /// The distance from `q` to the nearest of the stretches `of` of the drag `pts`. fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 { + #[cfg(test)] + STRETCH_TESTS.with(|c| c.set(c.get() + of.len())); of.iter() .filter_map(|&k| { let a = *pts.get(k)?; @@ -468,15 +579,18 @@ fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64) best } -/// How many curved segments of `pd` may come within `radius` of the drag `pts`. -fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize { - let all = drag_stretches(pts); +/// How many curved segments of `pd` may come within the reach of the drag. +fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize { pd.subpaths .iter() .map(|sp| { (0..sp.segment_count()) .filter(|&i| { - !vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty() + if vectorcraft_tools::draw2::segment_is_straight(sp, i) { + return false; + } + let b = control_box(sp.segment(i)); + !stretches_near(reach.pts, &reach.near_rect(b), b, reach.radius).is_empty() }) .count() }) @@ -516,26 +630,26 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz reach_samples(c, (mid, t1), (pts, &near), radius, budget, out); } -/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each +/// `sp` cut where the reach of the drag crosses its curved segments, and whether each /// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a /// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor /// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a /// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between /// stay as they are. A segment is searched no more than half the reach apart where it comes within /// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment. -fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec) { - let near = |q: Point| dist_to_polyline(pts, q) <= radius; +fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec) { + let (pts, radius) = (reach.pts, reach.radius); let n = sp.anchors.len(); - let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); + let marked: Vec = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect(); let mut places = vec![]; - let all = drag_stretches(pts); for i in 0..sp.segment_count() { if vectorcraft_tools::draw2::segment_is_straight(sp, i) { continue; } let c = sp.segment(i); let (mut samples, mut budget) = (vec![], share); - reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples); + let near = reach.near_rect(control_box(c.subsegment(0.0..1.0))); + reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples); // Stretches of samples alike, in order: (in reach, first, last). let mut runs: Vec<(bool, usize, usize)> = vec![]; for (k, s) in samples.iter().enumerate() { @@ -573,7 +687,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP .anchors .iter() .enumerate() - .map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) }) + .map(|(j, a)| if added.contains(&j) { reach.in_reach(a.p, 1e-9 * radius.max(1.0)) } else { kept.next().unwrap_or(false) }) .collect(); (out, marked) } @@ -581,13 +695,14 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP /// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. /// A closed path whose first anchor is in reach starts at the point of the refitted path nearest /// that anchor's place (VectorCraft's own rule). -fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { +fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; } - let near = &|q: Point| dist_to_polyline(pts, q) <= radius; + let radius = reach.radius; + let near = &|q: Point| reach.in_reach(q, 0.0); // A drag along a segment smooths it even when its anchors are out of reach. - let (sp, marked) = mark_reached(sp, pts, radius, share); + let (sp, marked) = mark_reached(sp, reach, share); let sp = &sp; if !marked.iter().any(|m| *m) { return None; @@ -693,14 +808,15 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool } i += 1; } - let mut out = anchors.to_vec(); + let mut out = EditsFromEnd::new(anchors.to_vec()); for (a, b) in runs.into_iter().rev() { let lo = a.saturating_sub(1); let hi = (b + 1).min(n - 1); if hi == lo { continue; } - let mut piece = out[lo..=hi].to_vec(); + let Some(piece) = out.get(lo, hi) else { continue }; + let mut piece = piece.to_vec(); // The anchors outside the reach, kept with the part of their segment that is outside. let (mut head, mut tail) = (None, None); if hi > b @@ -725,9 +841,49 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool if same_anchors(&new, &piece) { continue; } - out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); + out.replace(lo, hi, head.into_iter().chain(new).chain(tail)); + } + out.finish() +} + +/// A list edited by replacing stretches of it, each one ending no later than where the one before +/// started, in time proportional to the items replaced and moved rather than to the list's length +/// for each edit. +struct EditsFromEnd { + /// The start of the list. + head: Vec, + /// The rest of the list, last item first. + rest: Vec, +} + +impl EditsFromEnd { + fn new(items: Vec) -> Self { + EditsFromEnd { head: items, rest: vec![] } + } + + /// The items `lo` to `hi` of the list, `None` when it is shorter. + fn get(&mut self, lo: usize, hi: usize) -> Option<&[T]> { + while self.head.len() <= hi { + self.head.push(self.rest.pop()?); + } + self.head.get(lo..=hi) + } + + /// The list with the items `lo` to `hi` replaced by `with`, as [`Vec::splice`] gives it. Leaves + /// the list as it is when it is shorter. + fn replace(&mut self, lo: usize, hi: usize, with: impl IntoIterator) { + if lo > hi || self.get(lo, hi).is_none() { + return; + } + self.rest.extend(self.head.drain(hi + 1..).rev()); + self.head.truncate(lo); + self.head.extend(with); + } + + fn finish(mut self) -> Vec { + self.head.extend(self.rest.into_iter().rev()); + self.head } - out } pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { @@ -743,15 +899,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { paths.push((id, path_of(&st.doc, id)?.0)); } + let reach = DragReach::new(&pts, radius); // Each curved segment in reach gets the same share of the search, whatever order they come in. - let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum(); + let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum(); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); for (id, pd) in paths { let mut changed = false; let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) { + .map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -1127,6 +1284,153 @@ mod tests { pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect() } + /// A path of `n` smooth anchors 1 pt apart, along x and up and down by 3 pt, every segment + /// curved; closed, the anchors go round a circle `n` pt long instead. + fn wave(n: usize, closed: bool) -> SubPath { + let anchors = (0..n) + .map(|i| { + let f = i as f64; + if closed { + let r = n as f64 / std::f64::consts::TAU + f64::from(u8::from(i % 2 == 1)) * 3.0; + let a = f / n as f64 * std::f64::consts::TAU; + let (p, t) = (Point::new(r * a.cos(), r * a.sin()), kurbo::Vec2::new(-a.sin(), a.cos()) * 0.4); + Anchor::with_handles(p, p - t, p + t) + } else { + let p = Point::new(f, f64::from(u8::from(i % 2 == 1)) * 3.0); + Anchor::with_handles(p, p - kurbo::Vec2::new(0.4, 0.0), p + kurbo::Vec2::new(0.4, 0.0)) + } + }) + .collect(); + SubPath::new(anchors, closed) + } + + /// The same drag measured against all of its stretches for every point and box. + fn linear<'a>(pts: &'a [Point], radius: f64) -> DragReach<'a> { + DragReach { grid: None, ..DragReach::new(pts, radius) } + } + + /// How many stretch measures `f` made on this thread. + fn stretch_tests(f: impl FnOnce()) -> usize { + STRETCH_TESTS.with(|c| c.set(0)); + f(); + STRETCH_TESTS.with(std::cell::Cell::get) + } + + /// A drag of 200 points over 200 pt of a curved path of 100,000 anchors measures the anchors + /// and segments near the drag against the stretches near them, not every anchor and segment + /// against every stretch (about 40 million measures), and smooths the path as measuring + /// everything does. + #[test] + fn a_drag_over_a_long_path_measures_only_what_is_near_it() { + let sp = wave(100_000, false); + let pts: Vec = (0..200).map(|i| Point::new(50_000.0 + f64::from(i), 1.5)).collect(); + let reach = DragReach::new(&pts, 12.0); + let pd = PathData::single(sp.clone()); + let mut in_reach = 0; + let boxes = stretch_tests(|| in_reach = segments_in_reach(&pd, &reach)); + assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures"); + let share = (MAX_REACH_PIECES / in_reach).max(1); + let mut got = None; + let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share))); + assert!(marks < 100_000, "{marks} measures"); + let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0); + assert!(smoothed.is_some()); + let all = linear(&pts, 12.0); + assert_eq!(segments_in_reach(&pd, &all), in_reach); + assert_eq!(Some(mark_reached(&sp, &all, share)), got); + assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed); + } + + /// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer + /// than the grid lists by cell, one with a point that is not a number, and reaches of 0 to 50 pt: + /// the grid gives the same segments in reach, the same marks and the same smoothed path as + /// measuring against the whole drag. + #[test] + fn the_drag_grid_gives_the_results_of_measuring_the_whole_drag() { + let far = Point::new(1e7, -1e7); + let paths = [ + ring(), + wave(1500, false), + wave(1500, true), + SubPath::polyline(&(0..500).map(|i| Point::new(f64::from(i) * 2.0, f64::from(i % 3) * 4.0)).collect::>(), false), + SubPath::new( + vec![Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(3e5, 4e5)), Anchor::corner(Point::new(1e6, 0.0))], + false, + ), + SubPath::new( + wave(200, true) + .anchors + .iter() + .map(|a| Anchor::with_handles(a.p + far.to_vec2(), a.h_in + far.to_vec2(), a.h_out + far.to_vec2())) + .collect(), + true, + ), + ]; + let line = |from: (f64, f64), to: (f64, f64), n: u32| -> Vec { + (0..=n).map(|i| Point::new(from.0, from.1).lerp(Point::new(to.0, to.1), f64::from(i) / f64::from(n))).collect() + }; + let mut loop_drag: Vec = + (0..400).map(|i| Point::new(100.0 + 120.0 * (f64::from(i) * 0.05).cos(), 120.0 * (f64::from(i) * 0.05).sin())).collect(); + loop_drag.extend(line((0.0, 0.0), (1500.0, 2.0), 50)); + let drags = [ + vec![Point::new(150.0, 100.0)], + line((40.0, 90.0), (160.0, 110.0), 30), + line((-100.0, 1.0), (1600.0, 2.0), 1500), + loop_drag, + line((5e6, 5e6), (5e6 + 10.0, 5e6), 5), + vec![Point::new(0.0, 0.0), Point::new(1500.0, 3.0), Point::new(1500.0, 3.2), Point::new(10.0, 0.5)], + vec![Point::new(10.0, 1.0), Point::new(f64::NAN, 0.0), Point::new(12.0, 1.0)], + (0..1000).map(|i| Point::new(f64::from(i) * 0.01, 1.0)).collect(), + line((far.x, far.y), (far.x + 300.0, far.y + 40.0), 80), + ]; + for pts in &drags { + for radius in [0.0, 0.5, 12.0, 50.0] { + let (grid, all) = (DragReach::new(pts, radius), linear(pts, radius)); + for (k, sp) in paths.iter().enumerate() { + let pd = PathData::single(sp.clone()); + let in_reach = segments_in_reach(&pd, &all); + assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first()); + let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); + assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first()); + let sigma = radius * SMOOTH_SPREAD; + let want = smooth_subpath(sp, &all, share, 2.5, sigma); + assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first()); + } + } + } + } + + /// Replacing stretches of a list from its end, each one ending no later than where the one + /// before started (sometimes on that item, sometimes with nothing or with more items), gives the + /// list that [`Vec::splice`] gives. + #[test] + fn edits_from_the_end_match_splicing() { + let mut seed = 0x2545_f491_u64; + let mut next = |m: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % m.max(1) + }; + for round in 0..200 { + let items: Vec = (0..next(60) + 1).collect(); + let (mut want, mut got) = (items.clone(), EditsFromEnd::new(items.clone())); + let mut end = items.len() - 1; + loop { + let hi = end.saturating_sub(next(3)); + let lo = hi.saturating_sub(next(6)); + let with: Vec = (0..next(5)).map(|j| 1000 * (round + 1) + j).collect(); + let Some(stretch) = want.get(lo..=hi).map(<[usize]>::to_vec) else { break }; + assert_eq!(got.get(lo, hi).map(<[usize]>::to_vec), Some(stretch), "round {round}"); + want.splice(lo..=hi, with.clone()); + got.replace(lo, hi, with); + if lo == 0 { + break; + } + end = lo; + } + assert_eq!(got.finish(), want, "round {round}"); + } + } + /// Anchors on one point, anchors that are not numbers or are too far out to measure, and a /// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors /// are its corners, and an open path's ends never are. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..bfa156bd1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,6 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it, so the work of a release on a long path follows the part of the path under the drag rather than the whole path's length. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 5a26a9abd58acd69b6f21afbf1fc04752f3f2248 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:32:14 -0800 Subject: [PATCH 026/145] Dimension tool: Alt over a path places its overall width or height With the Linear Dimension tool and Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), with its width and height beside the pointer when Measurement Labels are on. A click on the path, then a placing click, or a drag out from it, places a dimension of the whole path. With the pointer above or below the path it measures the width, between the leftmost and rightmost points; beside the path it measures the height, between the topmost and bottommost points. The linear dimensions help page describes the Alt hover; which side gives which measure is VectorCraft's own rule. dimension.create takes a new source, {kind: extent, node}, for linear dimensions. Its points are the outermost points of the segments the path draws, curves included, and are read again whenever the path changes, so a turned path shows its new overall width or height. The line keeps its distance from the whole path when the path changes or is reflected, and when dimension.update changes the orientation, which now reads the other pair of points. When the box through the path's outermost points stays where it was, as after Reverse Path Direction, the line stays on its side. A version without the extent source does not open a file that holds one. The measurement label beside the pointer while two points are picked now keeps its distance in screen pixels at any zoom. The Help Bar hint names Alt+Click. Docs: docs/dimensions.md and docs/target-app-parity.md. --- crates/doc/src/dimension.rs | 185 +++++++++++++++++++++--- crates/engine/src/cmd/dimension.rs | 19 ++- crates/engine/tests/it/dimensions.rs | 132 +++++++++++++++++ crates/tools/src/dimension.rs | 204 +++++++++++++++++++++++++-- crates/ui-egui/src/chrome/hints.rs | 2 + docs/dimensions.md | 29 +++- docs/target-app-parity.md | 1 + 7 files changed, 530 insertions(+), 42 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 4d66f5d74c..0b50358622 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -389,6 +389,12 @@ pub enum DimensionSource { #[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")] free_b: Option, }, + /// A whole path, measured between its outermost points ([`extent`]): the leftmost and the + /// rightmost while the dimension is horizontal or aligned, the topmost and the bottommost while + /// it is vertical. Versions without this source do not open the file. + Extent { + node: NodeId, + }, } impl DimensionSource { @@ -396,7 +402,7 @@ impl DimensionSource { match self { Self::Segment { edge } | Self::Arc { edge } => vec![edge.node], Self::Angle { first, second } => vec![first.node, second.node], - Self::Circle { node } => vec![*node], + Self::Circle { node } | Self::Extent { node } => vec![*node], Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex] .into_iter() .filter_map(|p| p.as_ref().map(|r| r.node)) @@ -407,7 +413,7 @@ impl DimensionSource { /// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle /// edits keep their topology and remain linked. pub fn topology_changed(&self, before: &Document, after: &Document) -> bool { - if matches!(self, Self::Circle { .. }) { + if matches!(self, Self::Circle { .. } | Self::Extent { .. }) { return false; } self.nodes().iter().any(|id| { @@ -418,9 +424,18 @@ impl DimensionSource { old.is_some() && old != counts(after) }) } + /// Whether a path it measures differs between `before` and `after`, or is in only one of them. + pub fn art_changed(&self, before: &Document, after: &Document) -> bool { + self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { + (Some(old), Some(new)) => !std::ptr::eq(old, new) && old.path_data() != new.path_data(), + (old, new) => old.is_some() != new.is_some(), + }) + } /// The map that took the measured art from `before` to `after`, when every path it measures /// went through one [`art_transform`] that reflects it (a negative determinant). None when a - /// measured path is unchanged, or when two of them went through different maps. + /// measured path is unchanged, or when two of them went through different maps. None for a + /// dimension of a whole path whose path's box through its outermost points stays where it + /// was, as after its direction is reversed. pub fn reflection(&self, before: &Document, after: &Document) -> Option { let mut first: Option = None; for id in self.nodes() { @@ -429,6 +444,9 @@ impl DimensionSource { return None; } let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?; + if matches!(self, Self::Extent { .. }) && same_extents(before, after, id) { + return None; + } match first { None => first = Some(xf), Some(f) => { @@ -759,19 +777,22 @@ impl Dimension { /// outside them as it was, on the same side: the gap is measured from the outermost point /// on the line's side, so the line stays clear of art that turns. A line that lay between /// the two points keeps its distance from the first point. - pub fn keep_gap(&mut self, old: &Dimension) { + /// With `docs`, the documents `old` and this dimension were read from, the gap of a dimension of + /// a whole path is measured from the whole path ([`Self::span`]), also when only parts of the + /// path other than its measured points moved, and also when the dimension is aligned (each + /// along its own normal). + pub fn keep_gap(&mut self, old: &Dimension, docs: Option<(&Document, &Document)>) { + let whole = docs.is_some() && matches!(self.source, Some(DimensionSource::Extent { .. })); if self.mode != DimensionMode::Linear - || self.orientation == Orientation::Aligned + || (self.orientation == Orientation::Aligned && !whole) || old.orientation != self.orientation - || (self.a, self.b) == (old.a, old.b) + || ((self.a, self.b) == (old.a, old.b) && !whole) { return; } - let n = self.normal(); - let across = |p: Point| p.to_vec2().dot(n); - let line = across(old.a) + old.offset; - let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b))); - let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let line = old.a.to_vec2().dot(old.normal()) + old.offset; + let (low, high) = old.span(docs.map(|(before, _)| before)); + let (new_low, new_high) = self.span(docs.map(|(_, after)| after)); let at = if line >= high { new_high + (line - high) } else if line <= low { @@ -779,7 +800,7 @@ impl Dimension { } else { return; }; - let offset = at - across(self.a); + let offset = at - self.a.to_vec2().dot(self.normal()); if offset.is_finite() && offset.abs() <= 1e6 { self.offset = offset; } @@ -787,8 +808,9 @@ impl Dimension { /// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes /// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far /// past the outermost point on that side as `old`'s line was. A line that lay between the two - /// points is left as it is. - pub fn mirror_line(&mut self, old: &Dimension, image: Point) { + /// points is left as it is. With `docs`, as in [`Self::keep_gap`], a dimension of a whole path + /// measures from the whole path. + pub fn mirror_line(&mut self, old: &Dimension, image: Point, docs: Option<(&Document, &Document)>) { if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear { return; } @@ -796,7 +818,7 @@ impl Dimension { let n = old.normal(); let across = |p: Point| p.to_vec2().dot(n); let line = across(old.a) + old.offset; - let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b))); + let (low, high) = old.span(docs.map(|(before, _)| before)); if line >= high { line - high } else if line <= low { @@ -807,13 +829,25 @@ impl Dimension { }; let n = self.normal(); let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let (low, high) = self.span(docs.map(|(_, after)| after)); let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap }; let offset = at - across(self.a); if offset.is_finite() && offset.abs() <= 1e6 { self.offset = offset; } } + /// Where a linear dimension's art lies along its normal, lowest and highest: its two points, + /// or, for a dimension of a whole path read from `doc`, the whole path ([`reach`]), so that + /// the whole path is on one side of a line outside the span. + fn span(&self, doc: Option<&Document>) -> (f64, f64) { + let n = self.normal(); + let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n)); + let (low, high) = (a.min(b), a.max(b)); + match (doc, &self.source) { + (Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))), + _ => (low, high), + } + } /// Whether a linear dimension's line lies strictly between its two points along the normal. fn line_between_points(&self) -> bool { let n = self.normal(); @@ -824,19 +858,36 @@ impl Dimension { /// Makes a linear dimension measure in `orientation`, with its line on the side of the points /// it was on. The line goes through the middle of the old line when that point lies outside /// the two points along the new normal; otherwise it lies as far past the outermost point on - /// that side as the old line lay from its points. - pub fn set_orientation(&mut self, orientation: Orientation) { + /// that side as the old line lay from its points. A dimension of a whole path + /// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the + /// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on + /// the side the middle of the old line is on. + pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> { if self.mode != DimensionMode::Linear || self.orientation == orientation { self.orientation = orientation; - return; + return Ok(()); + } + let (handle, mut gap) = (self.handle(), self.offset.abs()); + if let Some(DimensionSource::Extent { .. }) = &self.source { + // Measured from the whole path. + let (low, high) = self.span(Some(doc)); + let line = self.a.to_vec2().dot(self.normal()) + self.offset; + gap = if line >= high { line - high } else { (low - line).max(0.0) }; } - let (handle, gap) = (self.handle(), self.offset.abs()); self.orientation = orientation; + if let Some(DimensionSource::Extent { node }) = &self.source { + (self.a, self.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + } let n = self.normal(); let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let (low, high) = self.span(Some(doc)); let h = across(handle); - let at = if h >= high || h <= low { + let whole = matches!(self.source, Some(DimensionSource::Extent { .. })); + let at = if whole && h >= high { + high + gap + } else if whole && h <= low { + low - gap + } else if h >= high || h <= low { h } else if 2.0 * h >= low + high { high + gap @@ -848,6 +899,7 @@ impl Dimension { self.offset = offset; } self.length = self.measured(); + Ok(()) } fn bisector(&self) -> Vec2 { let start = (self.a - self.vertex).atan2(); @@ -889,7 +941,7 @@ impl Dimension { self.offset = offset; } if self.line_between_points() && !old.line_between_points() { - self.keep_gap(&old); + self.keep_gap(&old, None); } } else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 { // A reflection turns the left normal of a → b to the other side, so an aligned @@ -948,6 +1000,12 @@ impl Dimension { let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?; self.set_radial(center, radius); } + Some(DimensionSource::Extent { node }) => { + let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + self.a = a; + self.b = b; + self.length = self.measured(); + } None => {} } self.validate() @@ -1048,6 +1106,87 @@ pub fn arc(doc: &Document, edge: &SegmentRef) -> Option<(Point, f64)> { Some((center, radius)) } +/// The outermost points of a path's outline, read from its segments (an anchor that starts no +/// segment is not part of it): the leftmost and the rightmost, then the topmost and the +/// bottommost. Of points level with each other, the first point is the topmost or leftmost of +/// them and the second the bottommost or rightmost, so a straight vertical line has two points +/// across its width too. None for a node without a path or without segments. +pub fn extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema}; + let path = doc.node(id)?.path_data()?; + let before = |p: Point, q: Point, vertical: bool| { + let key = |p: Point| if vertical { (p.y, p.x) } else { (p.x, p.y) }; + let (a, b) = (key(p), key(q)); + a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)).is_lt() + }; + let mut ends: Option<[(Point, Point); 2]> = None; + let mut take = |p: Point| { + let ends = ends.get_or_insert([(p, p); 2]); + for (axis, (low, high)) in ends.iter_mut().enumerate() { + if before(p, *low, axis == 1) { + *low = p; + } + if before(*high, p, axis == 1) { + *high = p; + } + } + }; + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + take(seg.p0); + take(seg.p3); + for t in seg.extrema() { + take(seg.eval(t)); + } + } + } + ends +} + +/// Whether the box through a path's outermost points ([`extents`]) is where it was in `before`, +/// each side to within rounding against the larger coordinate on its axis. +fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool { + let sides = |doc: &Document| extents(doc, id).map(|[(left, right), (top, bottom)]| [left.x, right.x, top.y, bottom.y]); + let (Some(old), Some(new)) = (sides(before), sides(after)) else { return false }; + [0, 2].into_iter().all(|i| { + let scale = old[i].abs().max(old[i + 1].abs()).max(1.0); + (i..i + 2).all(|j| (old[j] - new[j]).abs() <= 1e-12 * scale) + }) +} + +/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the +/// topmost and the bottommost. +pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> { + extents(doc, id).map(|ends| ends[usize::from(vertical)]) +} + +/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest +/// `p · u` over the points of its segments. None for a node without a path or without segments. +pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema}; + let path = doc.node(id)?.path_data()?; + // Turns `u` onto the x axis, so the turned curve's extrema include those along `u`. + let turn = Affine::new([u.x, -u.y, u.y, u.x, 0.0, 0.0]); + let mut span: Option<(f64, f64)> = None; + let mut take = |p: Point| { + let v = p.to_vec2().dot(u); + let (low, high) = span.get_or_insert((v, v)); + (*low, *high) = (low.min(v), high.max(v)); + }; + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + take(seg.p0); + take(seg.p3); + for t in (turn * seg).extrema() { + take(seg.eval(t)); + } + } + } + span +} + /// The two straight segments that meet at a corner anchor, if both are straight. pub fn corner(doc: &Document, node: NodeId, subpath: usize, anchor: usize) -> Option<(SegmentRef, SegmentRef)> { let sp = doc.node(node)?.path_data()?.subpaths.get(subpath)?; diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e38f8f99bb..27e1d81ae8 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -14,7 +14,7 @@ pub fn specs() -> Vec { "Create Dimension", [], None, - "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", + "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", has_doc, create ), @@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result { | (DimensionMode::Angular, DimensionSource::Angle { .. }) | (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. }) | (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. }) + | (DimensionMode::Linear, DimensionSource::Extent { .. }) ); if !compatible { return Err(error("Dimension mode does not match its source")); @@ -174,7 +175,7 @@ fn update(s: &mut Session, p: &Value) -> Result { dim.options = o.clone(); } if let Some(orientation) = orientation(p, dim.mode)? { - dim.set_orientation(orientation); + dim.set_orientation(orientation, doc).map_err(error)?; } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; @@ -452,7 +453,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { for (id, old) in dimensions { let mut next = old.clone(); let moved = next.moved.take(); - if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() { + // Whether the path a dimension of a whole path measures changed: when it did not, the + // dimension keeps its points without reading the path again, and is only checked. + let whole_changed = match &next.source { + Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)), + _ => None, + }; + let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() }; + if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable { // The art it measured was deleted, or rebuilt with other anchors, or no longer fits // (an ellipse that was a circle): it stays where it was, no longer linked, in this // same undo step, rather than attaching to a different edge. @@ -465,13 +473,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { changed = true; continue; } - next.keep_gap(&old); + next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc))); if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) { - next.mirror_line(&old, xf * old.handle()); + next.mirror_line(&old, xf * old.handle(), Some((before, doc))); } // Moved on its own (the art it measures stayed put): it keeps its new place. if let Some(v) = moved && (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex) + && whole_changed != Some(true) { next.place(old.handle() + v); if next.resolve(doc).is_err() { diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..2cbd61de92 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -466,6 +466,138 @@ fn turned_horizontal_dimensions_stay_horizontal() { assert_eq!(text(&s, id), "100.00 pt"); } +/// A dimension of a whole path measures the path's overall width, or its height when vertical, +/// between its outermost points, and follows the path when it turns. Turned 30°, a 100 × 60 +/// rectangle is 100 cos 30° + 60 sin 30° wide, more than either side; a turned ellipse is measured +/// at the outermost points of its curves, which are not anchors. +#[test] +fn a_dimension_of_a_whole_path_measures_its_overall_width_and_height() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":rect}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":"horizontal","offset":-30}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "100.00 pt"); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&s, id) - wide).abs() < 0.01, "{} against {wide}", text(&s, id)); + // The rectangle's box: left, top, right, bottom. + let bounds = |s: &Session| { + let anchors = s.doc().unwrap().doc.node(NodeId(rect)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let (xs, ys): (Vec, Vec) = anchors.iter().map(|a| (a.p.x, a.p.y)).unzip(); + let low = |v: &[f64]| v.iter().copied().fold(f64::INFINITY, f64::min); + let high = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + (low(&xs), low(&ys), high(&xs), high(&ys)) + }; + // The line stays 30 pt above the turned rectangle's topmost corner, clear of the art. + let (left, top, right, _) = bounds(&s); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - (top - 30.0)).abs() < 0.01, "line at y = {line}, top at {top}"); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let tall = 100.0 * 30f64.to_radians().sin() + 60.0 * 30f64.to_radians().cos(); + assert!((value(&s, id) - tall).abs() < 0.01, "{} against {tall}", text(&s, id)); + let d = recipe(&s, id); + let (top, bottom) = (d.a.y.min(d.b.y), d.a.y.max(d.b.y)); + assert!(((bottom - top) - tall).abs() < 0.01, "the points are the topmost and bottommost: {:?} {:?}", d.a, d.b); + // The line was 30 pt above the path; turned, it is 30 pt beside it. + let line = d.line_ends().0.x; + assert!((line - (left - 30.0)).abs() < 0.01 || (line - (right + 30.0)).abs() < 0.01, "line at x = {line}, path from {left} to {right}"); + run(&mut s, "edit.undo", json!({})); + assert!((value(&s, id) - wide).abs() < 0.01, "{}", text(&s, id)); + // A linear dimension only. + assert!(s.execute("dimension.create", &json!({"mode":"angular","source":source})).is_err()); + + let ellipse = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":100,"height":50}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":ellipse},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[ellipse]})); + run(&mut s, "object.rotate", json!({"angle":45})); + let anchors = s.doc().unwrap().doc.node(NodeId(ellipse)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let between_anchors = anchors.iter().map(|a| a.p.x).fold(f64::MIN, f64::max) - anchors.iter().map(|a| a.p.x).fold(f64::MAX, f64::min); + // 2 √(50² cos² 45° + 25² sin² 45°) + let across = 2.0 * (2500.0f64 * 0.5 + 625.0 * 0.5).sqrt(); + assert!(value(&s, id) > between_anchors + 1.0, "{} against the anchors' {between_anchors}", text(&s, id)); + assert!((value(&s, id) - across).abs() < 0.1, "{} against {across}", text(&s, id)); +} + +/// A dimension of a whole path measures the segments the path draws: an anchor that starts no +/// segment does not widen it. Its line stays clear of the whole path when only parts other than +/// its measured points move, also when it is aligned or is scaled together with the path, when the +/// path's direction is reversed or the path is reflected onto itself, and when it becomes aligned. +/// A reflection that moves the path puts the line on the reflected side. +#[test] +fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() { + let mut s = session(); + let lone = run(&mut s, "path.create", json!({"d":"M100 300 L110 300 M200 400","closed":false}))["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().doc.node(NodeId(lone)).unwrap().path_data().unwrap().subpaths.len(), 2, "the lone anchor is kept"); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":lone},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "10.00 pt"); + + // A triangle whose top rises while its leftmost and rightmost points stay: the line stays + // 30 pt above the top. + let tri = run(&mut s, "path.create", json!({"d":"M100 200 L150 120 L200 200 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 90.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[150,200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "line at y = {line}"); + // The same for an aligned dimension, and for a dimension scaled together with its path. + for (x, orientation, with_dimension) in [(300.0, "aligned", false), (500.0, "horizontal", true)] { + let d = format!("M{x} 200 L{} 120 L{} 200 Z", x + 50.0, x + 100.0); + let tri = run(&mut s, "path.create", json!({"d":d,"closed":true}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":tri}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-110}))["id"].as_u64().unwrap(); + let ids = if with_dimension { vec![tri, id] } else { vec![tri] }; + run(&mut s, "select.set", json!({"ids":ids})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[x + 50.0, 200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "{orientation}: line at y = {line}"); + } + // Reversing the path's direction draws the same outline: the line stays above it. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":400,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "path.reverse", json!({"ids":[rect]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 370.0).abs() < 1e-6, "line at y = {line}"); + // So does a reflection onto itself whose coordinates do not come out exactly, while a + // reflection that moves the art puts the line on the reflected side. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":500.2,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,530.2]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 470.2).abs() < 1e-6, "line at y = {line}"); + let tri = run(&mut s, "path.create", json!({"d":"M100 700 L150 620 L200 700 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,700]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 810.0).abs() < 1e-6, "line at y = {line}"); + + // Made aligned, the line runs from the leftmost to the rightmost point, with every corner of + // the rectangle on one side of it and 40 pt from the nearest, as it was 40 pt above the top. + let rect = run(&mut s, "shape.rectangle", json!({"x":300,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-40}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"})); + let (a, b) = recipe(&s, id).line_ends(); + let side = |x: f64, y: f64| (b - a).cross(vectorcraft_geom::Point::new(x, y) - a) / (b - a).hypot(); + let sides = [side(300.0, 100.0), side(400.0, 100.0), side(400.0, 160.0), side(300.0, 160.0)]; + assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}"); + let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min); + assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line"); +} + /// The line of a linked horizontal dimension keeps its gap from the outermost point on its side /// when the art turns, so it stays clear of the art: after a half turn the line is still 50 pt /// above the upper point, which is now the other anchor. diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index dffe13a378..f5a9ca880c 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -1,7 +1,9 @@ //! The Dimension tool. Hover a segment (linear), a corner (angular) or a circle or perfect arc //! (radial) and drag outwards: releasing places the linked dimension. Plain clicks pick what to //! measure instead: two points (linear) or two straight lines (angular), then a click places it; -//! a click on a circle or arc gives its radius. Escape cancels without leaving any artwork. +//! a click on a circle or arc gives its radius. With Alt (Option on macOS) held, a Linear click or +//! drag on a path measures the whole path's width or height instead. Escape cancels without +//! leaving any artwork. use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use serde_json::{Value, json}; use std::collections::HashMap; @@ -39,12 +41,26 @@ impl Kind { } } -/// What the pointer is over. +/// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height. #[derive(Clone, Debug, PartialEq)] enum Target { Segment(SegmentRef), Corner { first: SegmentRef, second: SegmentRef, at: Point }, Radial { source: DimensionSource, center: Point, radius: f64 }, + Extent { node: NodeId }, +} + +/// A path and the document its outermost points ([`dimension::extents`]) were read from +/// ([`whole_box_source`]), with the points. +type WholeBox = ((NodeId, (u64, u64, usize)), Option<[(Point, Point); 2]>); + +/// The document a path's box is read from, with what identifies it: while an interaction is in +/// progress, the document as it began; otherwise the document `cx` shows, at its revision. +fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, (NodeId, (u64, u64, usize))) { + match cx.interaction_doc { + Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), + None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))), + } } #[derive(Default)] @@ -106,6 +122,9 @@ pub struct DimensionTool { /// The document's next object id at the dimension's first preview: the id its preview takes /// (`dimension.create` gives the dimension the next id). The preview is not a level. preview_id: u64, + /// A path's outermost points, for the path and the document they were read from: a path + /// hovered with Alt held, or a dimension of a whole path being placed. + whole_box: Option, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -140,6 +159,37 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { .map_or(Orientation::Aligned, |(_, orientation)| orientation) } +/// The box through a path's outermost points ([`dimension::extents`]): left, top, right and +/// bottom. +fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect { + Rect::new(left.x, top.y, right.x, bottom.y) +} + +/// What a dimension of a whole path whose outermost points span `b` ([`extent_box`]) measures +/// with the pointer at `p` while it is placed (VectorCraft's own rule): above or below the box, +/// the path's width (horizontal); to the left or right of it, its height (vertical); past a +/// corner, the side the pointer is farther out on. Inside the box, or as far out on both sides, +/// it keeps `current`. A path with no height gives its width, and one with no width its height. +fn extent_orientation(b: Option, p: Point, current: Orientation) -> Orientation { + let current = if current == Orientation::Aligned { Orientation::Horizontal } else { current }; + let Some(b) = b else { return current }; + match (b.width() > 1e-9, b.height() > 1e-9) { + (true, false) => return Orientation::Horizontal, + (false, true) => return Orientation::Vertical, + (false, false) => return current, + (true, true) => {} + } + let out_x = (b.x0 - p.x).max(p.x - b.x1).max(0.0); + let out_y = (b.y0 - p.y).max(p.y - b.y1).max(0.0); + if out_x > out_y { + Orientation::Vertical + } else if out_y > out_x { + Orientation::Horizontal + } else { + current + } +} + /// How near an anchor (screen pixels) a pick snaps to it. const ANCHOR_REACH: f64 = 8.0; @@ -747,9 +797,27 @@ impl DimensionTool { }; Some(now.or(self.first_pick).unwrap_or(*at)) } - fn target(&self, cx: &ToolContext, p: Point) -> Option { + /// The outermost points of `node` ([`dimension::extents`]), read again only when the path or + /// the document changes. While an interaction is in progress they are read from the document + /// as the interaction began, which each preview starts again from (as the levels in + /// [`Self::preview`] are), so the previews themselves do not make the tool read the path again. + fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> { + let (from, key) = whole_box_source(cx, node); + if let Some((kept, ends)) = self.whole_box + && kept == key + { + return ends; + } + let ends = dimension::extents(from, node); + self.whole_box = Some((key, ends)); + ends + } + /// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point + /// is picked, is the whole path. + fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option { let edge = pick(cx, p)?; match self.kind { + Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }), Kind::Linear => Some(Target::Segment(edge)), Kind::Angular => { let (anchor, at) = anchor_near(cx, &edge, p)?; @@ -801,6 +869,12 @@ impl DimensionTool { let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; self.recipe(mode, *center, p, Point::ZERO, Some(source.clone())) } + Target::Extent { node } => { + let mut d = + self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(DimensionSource::Extent { node: *node })); + d.orientation = Orientation::Horizontal; + d + } }; d.offset = 30.0; Some(d) @@ -817,13 +891,19 @@ impl DimensionTool { } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { self.level_guide = None; + let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) { + Some(DimensionSource::Extent { node }) => Some(self.whole_box(cx, *node)), + _ => None, + }; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) && let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref()) { d.mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; } - if d.mode == DimensionMode::Linear { + if let Some(ends) = whole { + d.orientation = extent_orientation(ends.map(extent_box), p, d.orientation); + } else if d.mode == DimensionMode::Linear { // The points the dimension measures: a dragged segment's ends, read from the art. let ends = match &d.source { Some(DimensionSource::Segment { edge }) => edge.endpoints(cx.doc), @@ -841,7 +921,17 @@ impl DimensionTool { if !matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) { d.offset = 0.0; } - if d.resolve(cx.doc).is_err() { + // A dimension of a whole path takes the outermost points already read for it. + let read = match whole { + Some(Some(ends)) => { + (d.a, d.b) = ends[usize::from(d.orientation == Orientation::Vertical)]; + d.length = d.measured(); + d.validate() + } + Some(None) => Err(String::new()), + None => d.resolve(cx.doc), + }; + if read.is_err() { return vec![]; } // With Smart Guides on, a linear dimension's line lands on the level of a parallel @@ -906,11 +996,20 @@ impl DimensionTool { self.second = None; self.level_guide = None; self.levels.clear(); + // Alt may no longer be held: the box shows again only when the next move finds it is. + if matches!(self.hover, Some(Target::Extent { .. })) { + self.hover = None; + } } - /// A plain click: picks a point or a line, or measures a circle's radius. + /// A plain click: picks a point or a line, or measures a circle's radius. A click on a path + /// that Alt made the whole path starts placing its width or height. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { match self.kind { Kind::Linear => { + if let Some(target @ Target::Extent { .. }) = target { + self.pending = self.dimension_for(&target, p).filter(|d| d.clone().resolve(cx.doc).is_ok()); + return vec![]; + } let (mut at, mut reference) = self.snap_linear(cx, p); let mut corner = self.corner; if mods.shift @@ -1018,8 +1117,15 @@ impl Tool for DimensionTool { self.snapped = None; return self.preview(cx, ev.pos); } - self.hover = self.target(cx, ev.pos); - self.snapped = (self.kind == Kind::Linear && self.lines.is_empty()).then(|| self.snap_linear(cx, ev.pos)); + self.hover = self.target(cx, ev.pos, ev.mods.alt); + let whole = match self.hover { + Some(Target::Extent { node }) => { + self.whole_box(cx, node); + true + } + _ => false, + }; + self.snapped = (self.kind == Kind::Linear && self.lines.is_empty() && !whole).then(|| self.snap_linear(cx, ev.pos)); if self.snapped.is_none() { self.snap.clear(); } @@ -1038,7 +1144,7 @@ impl Tool for DimensionTool { && (anchor_under(cx, ev.pos).is_some() || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); - self.press = Some((ev.pos, self.target(cx, ev.pos))); + self.press = Some((ev.pos, self.target(cx, ev.pos, ev.mods.alt))); vec![] } PointerKind::Drag => { @@ -1122,7 +1228,7 @@ impl Tool for DimensionTool { if cx.measurement_labels && let Ok(text) = self.style.label(a.distance(b), false) { - out.push(Overlay::Measure { p: self.at + Vec2::new(12.0, 12.0), text }); + out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text }); } } } @@ -1138,6 +1244,29 @@ impl Tool for DimensionTool { out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true }); } } + Some(Target::Extent { node }) => { + // The box through the path's outermost points: a Smart Guide, or with Smart + // Guides off a line in the tool's own color. + // Read again when the path changed since the pointer last moved. + let (from, at) = whole_box_source(cx, *node); + let b = match self.whole_box { + Some((key, ends)) if key == at => ends, + _ => dimension::extents(from, *node), + } + .map(extent_box); + if let Some(b) = b { + let line = if cx.smart_guides { cx.smart_guide_color } else { color }; + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + for (i, a) in corners.iter().enumerate() { + out.push(Overlay::Line { a: *a, b: corners[(i + 1) % 4], color: line, dashed: false }); + } + if cx.measurement_labels + && let (Ok(w), Ok(h)) = (self.style.label(b.width(), false), self.style.label(b.height(), false)) + { + out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("W: {w}\nH: {h}") }); + } + } + } None => {} } } @@ -2201,6 +2330,61 @@ mod tests { } } + /// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide, + /// and a click starts placing a dimension of the whole path: above or below it, its width; + /// beside it, its height. A drag places it on release. Without Alt the same click picks a point. + #[test] + fn an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(alt); + let preview = |acts: Vec| match acts.last() { + Some(Action::Preview(_, params)) => params.clone(), + other => panic!("{other:?}"), + }; + let mut t = DimensionTool::default(); + t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); + assert_eq!(t.hover, Some(Target::Extent { node: id })); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); + // With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by + // the pointer. + let mut zoomed = cx(&d, &s, &p); + (zoomed.smart_guides, zoomed.measurement_labels, zoomed.zoom) = (false, true, 16.0); + let o = t.overlays(&zoomed); + assert!( + o.iter().any(|o| matches!(o, Overlay::Line { .. })) + && !o.iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color)) + ); + let near = |o: &Overlay| matches!(o, Overlay::Measure { p, text } if p.distance(Point::new(150.0, 100.0)) < zoomed.tol(20.0) && text.starts_with("W: ")); + assert!(o.iter().any(near), "{o:?}"); + t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0)); + t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); + assert!(t.pending.is_some() && t.points.is_empty()); + let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); + assert_eq!(above["source"], json!({"kind":"extent","node":id})); + assert_eq!(above["orientation"], json!("horizontal")); + let beside = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 260.0, 150.0))); + assert_eq!(beside["orientation"], json!("vertical")); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 260.0, 150.0)); + let placed = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 260.0, 150.0)); + assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}"); + // Placed with Alt let go: the box does not show again. + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); + + let mut t = DimensionTool::default(); + t.pointer(&c, &held(PointerKind::Down, 200.0, 150.0)); + let dragged = preview(t.pointer(&c, &held(PointerKind::Drag, 150.0, 240.0))); + assert_eq!((dragged["source"]["kind"].clone(), dragged["orientation"].clone()), (json!("extent"), json!("horizontal"))); + assert!(matches!(t.pointer(&c, &held(PointerKind::Up, 150.0, 240.0)).last(), Some(Action::Commit))); + + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); + assert!(t.pending.is_none() && t.points.len() == 1, "a plain click picks a point"); + } + /// A point that Smart Guides leave where the pointer already is (the pointer right in line /// with a target) stays on the guide the overlays show. It does not move to the nearest point /// of a segment within the pick's reach. Off the guides, a point near a segment still lands diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 2c679c72a1..b435cf00ed 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -8,6 +8,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { (" out from a highlighted edge to place its dimension | ", false), ("Click", true), (" two points, then move and click to place an aligned, horizontal or vertical dimension | ", false), + ("Alt+Click", true), + (" a path, then move and click to place its overall width or height | ", false), ("Esc", true), (" cancels | Double-click the tool for options", false), ], diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..ba1fd687df 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -82,6 +82,22 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers VectorCraft's own rule. With Alignment Guides on, a guide runs along the level across both lines while the dimension is placed. + The + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes plotting an object's overall horizontal and vertical dimensions by holding Alt + (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's + outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when + they are off, with its width and height beside the pointer when Measurement Labels are on. + Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out + from the path places it on release. The rest is VectorCraft's own rule. With + the pointer above or below the box the dimension measures the path's width, between its + leftmost and rightmost points; to the left or right of the box it measures the height, between + the topmost and bottommost points; past a corner, the side the pointer is farther out on + decides. The points are read from the segments the path draws, curves included, and an anchor + that starts no segment is left out. They are read again whenever the path changes, so a turned + path shows its new overall width or height rather than that of its bounding box before the + turn. The line keeps its distance from the whole path when the path changes or the dimension + changes orientation. Alt has this effect only before the first point is clicked. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -112,7 +128,9 @@ Measurements follow the art they measure through moves, scaling and anchor and h undo and redo included. When the art is reflected, the line of a linked linear dimension goes to the reflected side, as far past the outermost point as before. This does not happen for art whose anchors and handles all lie on one line, such as a straight line, which a half turn puts in the -same place as a reflection. An unlinked aligned dimension that is reflected, or scaled by a +same place as a reflection, nor for a dimension of a whole path whose box through the path's +outermost points stays where it was, as after Reverse Path Direction or a reflection across the +middle of that box. An unlinked aligned dimension that is reflected, or scaled by a negative factor, has its line on the reflected side of its points. Deleting the art, changing its number of anchors or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves its dimensions where they were, no longer linked, in the same undo step, rather than @@ -150,9 +168,12 @@ another document. ## Commands -- `dimension.create`: two points, or a source (segment, angle, circle, arc, points), the mode, - the orientation of a linear dimension (`aligned`, the default, `horizontal` or `vertical`), - offset and style; returns the group id and label. `offset` is the distance of the dimension +- `dimension.create`: two points, or a source (segment, angle, circle, arc, points, extent), the + mode, the orientation of a linear dimension (`aligned`, the default, `horizontal` or + `vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":}` + measures a whole path, linear only: between its leftmost and rightmost points when horizontal + or aligned, and its topmost and bottommost points when vertical. A version without the extent + source does not open a file that holds one. `offset` is the distance of the dimension line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..7e35dd9151 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -684,6 +684,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. +**Drawing tools, Dimension tool overall width and height of a path (#5590):** With Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), and a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes; by VectorCraft's own rule the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height` and `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From 49fd8652b13adf31eea13819a5ffa4162a8d6312 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:49:54 -0800 Subject: [PATCH 027/145] Dimension tool: a geometry effect on any part keeps a dimension in place A press on one part of a dimension now also checks its other parts for a geometry effect, so an effect on an extension line keeps the drag from moving the dimension (and from drawing the parts again without the effect). In isolation mode, only art inside the isolated object is compared with the dimension when the press decides between them. --- crates/engine/tests/it/dimensions.rs | 44 ++++++++++++++++++++++++++++ crates/tools/src/dimension.rs | 32 ++++++++++++++++---- 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index c92390feec..9d9446fa90 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2352,6 +2352,50 @@ fn a_dimension_is_dragged_only_where_the_canvas_hits_it() { assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}"); } +/// A geometry effect on a part of a dimension other than the one pressed keeps the Dimension tool +/// from dragging it, and the effect stays on that part. +#[test] +fn a_geometry_effect_on_another_part_keeps_the_dimension_in_place() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let extension = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The extension line at x = 100, which the press below on the dimension line misses. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x1 < 101.0 && r.height() > 10.0)); + line.unwrap().id.0 + }; + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[extension],"params":{"moveH":-60}})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let kept = s.doc().unwrap().doc.node(NodeId(extension)).is_some_and(|n| !n.appearance.effects.is_empty()); + assert!(kept, "the extension line keeps its effect"); +} + +/// In isolation mode, art outside the isolated group does not take a press on a dimension inside +/// it: the drag moves the dimension. +#[test] +fn art_outside_isolation_does_not_take_the_press_on_a_dimension() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + // A line across the dimension line, outside the group isolated below. The press, a point below + // the dimension line, is nearer to it than to the dimension line. + run(&mut s, "path.create", json!({"d": "M150 100 L150 250"})); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 171.0), (PointerKind::Down, 171.0), (PointerKind::Drag, 131.0), (PointerKind::Up, 131.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + /// A dimension pasted into a document that had none is dragged with the Dimension tool like one /// drawn there. #[test] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 081703bb13..9e770fbe68 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -157,6 +157,11 @@ fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point { /// Nearest editable segment, with bounded work and no snapping to dimension artwork itself. pub fn pick(cx: &ToolContext, p: Point) -> Option { + pick_among(cx, p, cx.doc.layers.iter().rev().map(|n| n.as_ref())) +} + +/// [`pick`] among `roots`, topmost first, and what they hold. +fn pick_among<'a>(cx: &ToolContext, p: Point, roots: impl Iterator) -> Option { let mut best = None; let mut dist = cx.tol(8.0); let mut budget = 20_000usize; @@ -186,7 +191,7 @@ pub fn pick(cx: &ToolContext, p: Point) -> Option { } } } - for n in cx.doc.layers.iter().rev() { + for n in roots { visit(n, p, &mut budget, &mut dist, &mut best); } best @@ -601,11 +606,21 @@ fn dimension_under(cx: &ToolContext, p: Point) -> Option<(NodeId, f64)> { let nodes: Vec<&Node> = chain.iter().filter_map(|id| cx.doc.node(*id)).collect(); let below = scope_at.map_or(0, |i| i + 1); let outline = opt.outline || nodes.iter().skip(below).any(|n| matches!(n.kind, NodeKind::Layer { preview: false, .. })); - let displaced = nodes.iter().enumerate().any(|(i, n)| { - vectorcraft_effects::has_geometry(&n.appearance.effects) - || (i >= at && n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects()))) + let item_geometry = |n: &Node| n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects())); + let displaced = nodes.iter().enumerate().any(|(i, n)| vectorcraft_effects::has_geometry(&n.appearance.effects) || (i >= at && item_geometry(n))); + // The parts of the dimension the press did not land on count too: a geometry effect on any of + // them is drawn elsewhere as well. + let parts_displaced = cx.doc.node(id).is_some_and(|d| { + d.try_walk(&mut |n| { + if vectorcraft_effects::has_geometry(&n.appearance.effects) || item_geometry(n) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + }) + .is_break() }); - if !outline && displaced { + if !outline && (displaced || parts_displaced) { return None; } let n = cx.doc.node(id).filter(|_| cx.doc.is_editable(id))?; @@ -1199,7 +1214,12 @@ impl Tool for DimensionTool { && self.lines.is_empty() && let Some((id, d)) = dimension_under(cx, ev.pos) { - let art = pick(cx, ev.pos).and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); + // In isolation mode only art inside the isolated object competes for the press. + let edge = match cx.hit_options().scope.and_then(|s| cx.doc.node(s)) { + Some(isolated) => pick_among(cx, ev.pos, std::iter::once(isolated)), + None => pick(cx, ev.pos), + }; + let art = edge.and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); if art.is_none_or(|a| d < a) { self.grab = Some(id); } From 9758ece7efae40e3b7cd20e537b3abb8f4962afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:07:34 -0800 Subject: [PATCH 028/145] Scripts: vc.run export of an open document reads its own linked files A command a script runs with vc.run could read only the script's own places and the open documents' own files, so an export, save, print or package of a document whose linked images or placed files sit elsewhere fell back to the saved previews. The script gate now also reads, and never writes, the files that the documents open when the run began link to: linked images, placed files, the plate files of a DCS image and the images their data sets name. The list is taken once, at the run's first vc.run, from those documents as they were when the run began, and holds real paths, so a path that leads to another file later is refused. A link the script adds or re-points, a path it names itself and a document it opens give it no further file to read, a document it opens from one of these files is not saved over it, and the automation read roots and the name and traversal rules still apply first. --- crates/engine/src/cmd/links.rs | 29 +++++- crates/engine/src/file_access.rs | 128 ++++++++++++++++++++++++-- crates/engine/src/script/files.rs | 15 +-- crates/engine/src/script/mod.rs | 40 +++++++- crates/engine/src/tests/script_run.rs | 62 +++++++++++++ docs/mcp.md | 7 ++ docs/target-app-parity.md | 3 +- 7 files changed, 267 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..9f1e7c3d79 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> { /// The open document `st`'s. One with no file of its own looks beside the file it was read from. pub(crate) fn of(st: &'a crate::DocState) -> Self { - let (path, from) = (st.path.as_deref(), st.links_from.as_deref()); + Self::of_files(st.path.as_deref(), st.links_from.as_deref()) + } + + /// An open document's, by its own file `path` and the file it was read from, `from` + /// ([`crate::DocState::links_from`]), as [`Self::of`] gives them. + pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self { Self { doc: path.or(from), relative: from.or(path) } } } @@ -401,6 +406,28 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] +/// finds each linked image's and placed document's file from `base` and from no document (as +/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from +/// DCS files, and the image files its data sets name. The commands a script runs may read these +/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + for from in [base, LinkBase::default()] { + let Some(f) = locate(&g.link, from) else { continue }; + out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name))); + out.push(f.path); + } + } + let values = d.variables.datasets.iter().flat_map(|set| set.values.values()); + out.extend(values.filter_map(|v| match v { + DataValue::Image(path) => fileio::document_path(path, base.doc).ok(), + _ => None, + })); + out +} + /// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows /// it, when it also follows that place from the document's own file `doc`: a network share the /// document is no longer on is refused. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..525094a990 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -27,7 +27,8 @@ //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the -//! files of the open documents. +//! files of the open documents, and for reading, the files the documents open when the run began +//! link to. use std::cell::RefCell; use std::ffi::OsString; @@ -276,19 +277,53 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. The automation roots apply as well. A path refused by its name -/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to. Reading, and only reading, the files the documents open when the +/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as +/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// The real paths of the files the documents open when the run began link to, as they were + /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. + /// A path that leads to another file now is not one of them. + pub(crate) linked: Arc<[PathBuf]>, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } impl ScriptGate { + /// The real paths of the files at `paths` that are files now, each once, for + /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, + /// is left out. + pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + let mut real: Vec = paths + .into_iter() + .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) + .filter_map(|p| resolve(&p).ok()) + .filter(|p| p.is_file()) + .collect(); + real.sort(); + real.dedup(); + real.into() + } + + /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless + /// they are among `before`, the files of the documents open when the run began: a document the + /// run opened from such a file is read, never written. + pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { + let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; + let linked = self.linked.clone(); + let only_linked = |d: &String| { + let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; + real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + }; + self.documents.retain(|d| before.contains(d) || !only_linked(d)); + self + } + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every /// gate already in the chain as well as `next`. fn followed_by(&self, next: Arc) -> ScriptGate { @@ -307,7 +342,7 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), Access::Write => self.write.allows(&real), }; scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) @@ -918,8 +953,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -942,7 +982,13 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &Path| ScriptGate { + read: ScriptScope::of_folder(dir), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -957,6 +1003,74 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A file an open document linked to when the run began is readable through the gate; its path + /// written with `..`, writing it, a file next to it and a file that was not there when the gate + /// was made are not allowed, and the automation roots still apply. + #[test] + fn a_gate_reads_only_the_linked_files_it_was_given() { + let (base, roots) = folders("linked"); + let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg")); + std::fs::write(&other, "").unwrap(); + let later = base.join("outside/later.svg"); + let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); + assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + let gate = + ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; + std::fs::write(&later, "").unwrap(); + let (read, write) = + (|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok()); + assert!(read(&secret)); + assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name"); + assert!(!write(&secret), "linked files are not written"); + assert!(!read(&other), "a file next to a linked one"); + assert!(!read(&later), "a file made after the gate"); + assert!(!read(&base.join("outside")), "the linked file's folder"); + let g = gate.clone(); + assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document the run opened from a file only the linked files let it read is not written + /// through the document-file rule; one open when the run began, and one in the script's own + /// places, still is. + #[test] + fn a_document_opened_from_a_linked_file_stays_read_only() { + let (base, _) = folders("linked-doc"); + let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); + let gate = ScriptGate { + read: ScriptScope::of_folder(&base.join("in")), + write: ScriptScope::of_folder(&base.join("in")), + documents: vec![secret.clone(), own.clone()], + linked: ScriptGate::real_files([secret.clone(), own.clone()]), + also: None, + }; + let opened = gate.clone().keeping_linked_read_only(&[]); + assert!(opened.check(&secret, Access::Read).is_ok()); + assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); + assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); + let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); + assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); + let _ = std::fs::remove_dir_all(base); + } + + /// A link to a linked file read through the gate counts only while it leads to that file. + #[cfg(unix)] + #[test] + fn a_gate_refuses_a_link_that_now_leads_elsewhere() { + let (base, _) = folders("linked-moved"); + let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg")); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + let linked = ScriptGate::real_files([s(link.clone())]); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None }; + assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok()); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now"); + assert!(gate.check(&s(other), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..34179a55b5 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,7 +54,8 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that +//! the documents open when the run began link to, as those links were then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -72,8 +73,9 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::rc::Rc; +use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -454,10 +456,11 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. - pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + /// The gate for a command the script runs: the places it reads and writes now, the files of the + /// open documents, `documents`, and the files it may only read because the documents open when + /// the run began link to them, `linked`. + pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..62dc11df23 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,6 +799,36 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The documents open when the run began, each with its own file and the file it was read from + /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// they link to from them ([`Host::linked`]). + run_docs: RefCell>, + /// The files of the documents open when the run began + /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). + opened_before: Vec, + /// The real paths of the files the documents open when the run began link to + /// ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell>, +} + +/// A document open when a run began, with its own file and the file it was read from. +type RunDoc = (Arc, Option, Option); + +impl Host { + /// The files the commands the run runs may read because the documents open when the run began + /// link to them, found once, from those documents as they were then: a link the run adds or + /// changes, and a document it opens, give it no file to read. + fn linked(&self) -> Arc<[std::path::PathBuf]> { + self.linked + .get_or_init(|| { + let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); + let files = docs.iter().flat_map(|(d, path, from)| { + crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref())) + }); + crate::file_access::ScriptGate::real_files(files.collect::>()) + }) + .clone() + } } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1238,8 +1268,11 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files. - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + // The command reads and writes only where the script's own files may, and the open documents' files; + // it also reads the files the documents open when the run began link to, and does not write a document + // the run opened from one of those. + let linked = host.linked(); + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); @@ -2040,6 +2073,9 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), + opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..d0a9723f3e 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -417,6 +417,68 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let _ = std::fs::remove_dir_all(&dir); } +/// The color at the middle of the PNG at `path`. +fn middle_color(path: &std::path::Path) -> [u8; 3] { + let img = craft_image_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + let (w, h) = img.dimensions(); + let rgba = img.to_rgba8(); + let i = ((h / 2 * w + w / 2) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] +} + +/// A script's export of a document open when the run began draws the file its image links to, +/// also outside the script's places. A file the script names itself, a link it points at such a +/// file, writing to the linked file and the links of a document the script opens are refused all +/// the same. +#[test] +fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { + use crate::tests_links::{BLUE, RED, near, open, place, png, save, session, write}; + let dir = fresh_folder("gate-links"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, secret, poster, other) = + (p(art.join("photo.png")), p(art.join("secret.png")), p(art.join("poster.vectorcraft")), p(inside.join("other.vectorcraft"))); + write(&pic, &png(600, 300, RED)); + write(&secret, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &secret); + save(&mut s, &other); + s.execute("file.close", &json!({})).unwrap(); + // The files change after the saves: each document holds only the red preview of its image. + write(&pic, &png(600, 300, BLUE)); + write(&secret, &png(600, 300, BLUE)); + open(&mut s, &poster); + let (first, second) = (inside.join("first.png"), inside.join("second.png")); + let call = |id: &str, params: String| { + format!( + "try {{ var r = vc.run('{id}', {params}); vc.log(r.warnings ? r.warnings.length : 0); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let export = |to: &std::path::Path| format!("{{path: {:?}, format: 'png', background: 'white'}}", p(to.to_path_buf())); + let source = [ + call("document.export", export(&first)), + call("file.place", format!("{{path: {secret:?}, at: [200, 150]}}")), + "vc.run('select.all', {});\n".to_string(), + call("links.relink", format!("{{path: {secret:?}}}")), + call("document.export", format!("{{path: {pic:?}, format: 'png'}}")), + call("document.open", format!("{{path: {other:?}}}")), + call("document.export", export(&second)), + ] + .concat(); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!([0, "denied", "denied", "denied", 0, 1]), "{r}"); + assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); + assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); + assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9a1f57c42f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,6 +3020,13 @@ VectorCraft writes files by these rules of its own: `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in its `Folder.temp` and `Folder.userData` and to the open documents' own files. + Such a command also reads, and does not write, the files that the documents open when the run began link to + (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, + save, print or package of them includes the linked art. A document the script opens from such a file is not + saved over it. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points + elsewhere, and a document it opens, does not let it read any file it could not read before. The automation + read roots still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..37b87a97d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1039,7 +1039,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 239a7d61d0fa337f1023e8640fe651d4dbf7dfe4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:15:55 -0800 Subject: [PATCH 029/145] Smooth: the dashed band shows the radius its release sends at the lowest zooms The band a smoothing drag shows took the Smooth radius in points without the 1,000 pt bound the release applies, so below 1.2% zoom it drew wider than the region path.smoothRegion smooths. It now uses the same bound. --- crates/tools/src/draw2/gesture.rs | 2 +- crates/tools/src/draw2/gesture/tests.rs | 32 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index ab88d16436..a34c819761 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1920,7 +1920,7 @@ impl Tool for GestureTool { // release smooths. if (self.id == "smooth" || self.smoothing) && has_selected_smooth_path(cx) - && let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS)) + && let Some(path) = self.smooth_band(reach(cx, SMOOTH_RADIUS)) { o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) }); } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index dbbbb53a78..00f0ebc93e 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1641,6 +1641,38 @@ fn smoothing_band_shows_no_seam_where_it_turns_across_a_square_side() { } } +/// Zoomed out far enough that the Smooth tool's radius in points passes the top of +/// [`crate::draw2::REACH_RANGE`], the band a smoothing drag shows has the radius its release sends. +#[test] +fn smoothing_band_at_the_lowest_zoom_has_the_radius_the_release_sends() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.zoom = 0.005; + let r = crate::draw2::REACH_RANGE.1; + assert!(cx.tol(SMOOTH_RADIUS) > r, "the radius on screen is past the range at {}x", cx.zoom); + let ends = [Point::new(1000.0, 1000.0), Point::new(5000.0, 1000.0)]; + let mut t = GestureTool::new("smooth"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, ends[0].x, ends[0].y)); + for i in 1..=20 { + let q = ends[0].lerp(ends[1], f64::from(i) / 20.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)); + } + let mut frames = 0; + while t.overlays_pending() { + assert!(frames < 10_000, "the band reaches the whole drag"); + bands(&t, &cx); + frames += 1; + } + check_band(&t, &cx, r); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, ends[1].x, ends[1].y)); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("expected a command, got {acts:?}") }; + assert_eq!((c.as_str(), v["radius"].as_f64()), ("path.smoothRegion", Some(r)), "{v}"); +} + /// One straight piece of a square's outline along a side, where the band goes on across only part /// of it, shows only the part with nothing across. #[test] From 4367a9ce68b9b1cba848dd06c1a573369096ac8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:22:58 -0800 Subject: [PATCH 030/145] Smooth: the progress line says every anchor and segment is still looked up A release still looks up every anchor and curved segment of a path in the drag's grid, so that work grows with the path's length. The line now says the grid reduces the stretch measures, and that the 7,533 and 19,899,801 figures count stretch measures. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfa156bd1c..bce51bbfb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,7 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. - A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it, so the work of a release on a long path follows the part of the path under the drag rather than the whole path's length. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). + A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it. A release still looks up every anchor and curved segment of a path in the drag's grid, so the lookups still grow with the path's length. The grid reduces the number of stretch measures. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 stretch measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 38e36aeb819c32de4cde8d3f90c7900b2a180931 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:53:49 -0800 Subject: [PATCH 031/145] Paths: Object > Path > Simplify and Smooth keep a closed path's start Simplify and Smooth refit a closed path from its first corner and kept that order, so the path's first anchor moved and its dashes started somewhere else. A refit now starts at the old first anchor when it keeps one there, otherwise at a new anchor where the refit passes nearest that point while the result still has fewer anchors than the path had, and otherwise at the refit's nearest anchor. Its direction stays the same. A direct-selected run across the start follows the same rule; before, the path started at the run's end anchor. The Smooth tool's start_nearest moves into vectorcraft-pathops, and both commands call it with the limit on anchor count above. --- crates/engine/src/cmd/draw2/smooth.rs | 81 +------------ crates/engine/src/tests/simplify_part.rs | 81 ++++++++++--- crates/pathops/src/edit.rs | 147 +++++++++++++++++++++-- crates/pathops/src/lib.rs | 6 +- crates/pathops/tests/it/ops.rs | 68 +++++++++++ docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 7 files changed, 287 insertions(+), 107 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..e730401b60 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,4 +1,5 @@ use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_pathops::start_nearest; use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; use super::{ @@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { - let mut best: Option<(f64, usize, f64)> = None; - for j in 0..orig.anchors.len() { - let hit = orig.segment(j).nearest(p, 1e-9); - if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { - best = Some((hit.distance_sq, j, hit.t)); - } - } - best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) -} - -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, -/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, -/// is returned as it is. -fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - let n = sp.anchors.len(); - if !sp.closed || n < 2 { - return sp; - } - // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) - type Best = (f64, Option<(usize, f64)>, usize, f64); - let mut best: Option = None; - for i in 0..n { - let c = sp.segment(i); - let hit = c.nearest(start, 1e-9); - if !hit.distance_sq.is_finite() || !hit.t.is_finite() { - continue; - } - let d = hit.distance_sq.sqrt(); - match &mut best { - None => best = Some((d, None, i, hit.t)), - Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); - let place = place_along(orig, c.eval(hit.t)); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), i, hit.t)); - } - } - Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), - Some(_) => {} - } - } - let Some((_, _, i, t)) = best else { return sp }; - let c = sp.segment(i); - let at = c.eval(t); - let first = if at.distance(c.p0) <= START_SNAP { - i - } else if at.distance(c.p3) <= START_SNAP { - (i + 1) % n - } else { - let mid = if sp.segment_is_line(i) { - Anchor::corner(at) - } else { - let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); - sp.anchors[i].h_out = l.p1; - sp.anchors[(i + 1) % n].h_in = r.p2; - Anchor::with_handles(at, l.p2, r.p1) - }; - sp.anchors.insert(i + 1, mid); - i + 1 - }; - sp.anchors.rotate_left(first); - sp -} - /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments /// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, /// each of which gets at least one: enough to search 300,000 pt of curve within the default reach @@ -1009,6 +932,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { + use vectorcraft_pathops::START_SNAP; + use super::*; /// A closed ring of four smooth anchors round (100, 100) with radius 50. diff --git a/crates/engine/src/tests/simplify_part.rs b/crates/engine/src/tests/simplify_part.rs index f3ab93f274..82f6cdc628 100644 --- a/crates/engine/src/tests/simplify_part.rs +++ b/crates/engine/src/tests/simplify_part.rs @@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300). +fn eighty_gon() -> Vec<(f64, f64)> { + (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect() +} + /// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one -/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10), -/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed. +/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest +/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their +/// outer handles, the path stays closed, and the refitted run stays direct-selected. #[test] fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() { let mut s = session(); - let pts: Vec<(f64, f64)> = - (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect(); - let id = polyline(&mut s, &pts, true); + let id = polyline(&mut s, &eighty_gon(), true); let original = path_of(&s, id).subpaths[0].clone(); select_anchors(&mut s, id, &[(70, 79), (0, 10)]); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); let sp = path_of(&s, id).subpaths[0].clone(); assert!(sp.closed); assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len()); - assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run"); - assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); - assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); - assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); - for i in 0..60 { - assert_eq!(sp.segment(i), original.segment(10 + i)); - } + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt"); let n = sp.anchors.len(); - assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6); - let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect(); + let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap(); + let mut turned = sp.clone(); + turned.anchors.rotate_left(k); + assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); + assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); + assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); + for i in 0..60 { + assert_eq!(turned.segment(i), original.segment(10 + i)); + } + assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6); + let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect(); assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it +/// started too, with fewer anchors. +#[test] +fn smoothing_a_run_across_the_start_keeps_the_start() { + let mut s = session(); + let id = polyline(&mut s, &eighty_gon(), true); + let original = path_of(&s, id).subpaths[0].clone(); + select_anchors(&mut s, id, &[(70, 79), (0, 10)]); + s.execute("object.path.smooth", &json!({"level": 50})).unwrap(); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p); +} + +/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through +/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far +/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step. +#[test] +fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() { + let mut s = session(); + let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin()); + let pts: Vec<(f64, f64)> = + (0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect(); + let id = polyline(&mut s, &pts, true); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap(); + let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + let style = stroke(&s); + let original = path_of(&s, id).subpaths[0].clone(); + // (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance) + let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)]; + for (command, params, limit) in commands { + let steps = undo_len(&s); + s.execute(command, ¶ms).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{command}"); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p); + assert_eq!(stroke(&s), style, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id).subpaths[0], original, "{command}"); + } +} + /// Segments picked with the Direct Selection tool simplify the same way, and stay picked as /// segments. #[test] diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 3ad1281eb2..a26da95828 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -97,7 +97,10 @@ fn turn_deg(a: &Seg, b: &Seg) -> f64 { d.acos().to_degrees() } -/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. +/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. A closed +/// subpath starts where it did: at its first anchor when the refit keeps an anchor there, otherwise +/// at a new anchor split into the refit at its point nearest there when the refit still has fewer +/// anchors than the subpath with that one, and otherwise at the refit's anchor nearest there. pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { let mut out = Vec::new(); for sp in &path.subpaths { @@ -108,15 +111,132 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { PathData::new(out) } -/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath -/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the -/// point farthest from its start, or in three when two still give that. When three parts still give -/// no area, straight lines follow the subpath within the tolerance, and without straight lines it +/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit +/// starts where the subpath started ([`keep_start`]). +fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { + refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) +} + +/// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] +/// starts at that anchor instead of at a new one split in beside it. +pub const START_SNAP: f64 = 1e-3; + +/// Distance (points) within which two points of a closed path count as equally near its old start. +const START_TIE: f64 = 1e-6; + +/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of +/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place +/// when there is none. +fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: +/// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from +/// its first anchor, then the first given. +fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { + // (distance, place along `orig` once a tie needs it, point, value) + type Best = (f64, Option<(usize, f64)>, Point, T); + let mut best: Option> = None; + for (d, p, x) in candidates { + if !d.is_finite() { + continue; + } + match &mut best { + None => best = Some((d, None, p, x)), + Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); + let place = place_along(orig, p); + if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { + best = Some((d, Some(place), p, x)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), + Some(_) => {} + } + } + best.map(|(.., x)| x) +} + +/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new +/// anchor split into the segment there, which leaves the outline as it is. Of points equally near +/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is +/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// point, is returned as it is. +pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + start_near(sp, start, orig, true).0 +} + +/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies +/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → +/// (the path, the segment split when one was, where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return (sp, None, 0); + } + let hits = (0..n).map(|i| { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; + (d, c.eval(hit.t), (i, hit.t)) + }); + let Some((i, t)) = earliest_nearest(hits, orig) else { return (sp, None, 0) }; + let c = sp.segment(i); + let at = c.eval(t); + let (first, cut) = if at.distance(c.p0) <= START_SNAP { + (i, None) + } else if at.distance(c.p3) <= START_SNAP { + ((i + 1) % n, None) + } else if split { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + (i + 1, Some(i)) + } else { + let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + (earliest_nearest(near, orig).unwrap_or(0), None) + }; + sp.anchors.rotate_left(first); + (sp, cut, first) +} + +/// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at +/// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An +/// open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { + match orig.anchors.first() { + Some(a) if orig.closed => { + let split = fit.anchors.len() + 1 < orig.anchors.len(); + start_near(fit, a.p, orig, split) + } + _ => (fit, None, 0), + } +} + +/// [`simplify_subpath`] before the start is put back: a closed subpath whose refit is one segment, +/// or lines that enclose no area, is refitted in two parts, cut at the point farthest from its +/// start, or in three when two still give that. When three parts still give no area, straight lines +/// follow the subpath within the tolerance, and without straight lines it /// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose /// an area, it stays as it is, or with straight lines follows the lines between samples of each /// curved segment when the limits leave room for lines within the tolerance; one that is all in line /// keeps the refit. -fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { +fn refit_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); if n == 0 || sp.closed && n < 2 { @@ -694,7 +814,8 @@ pub struct SimplifiedPart { /// two end anchors, which stay where they are with their handles on the side away from the run. /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more -/// segments than it had is left as it is (except with Convert to Straight Lines). +/// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -782,7 +903,17 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - (SubPath::new(anchors, sp.closed), runs, kept) + // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + let len = out.anchors.len(); + if (cut, first) == (None, 0) || len == 0 { + return (out, runs, kept); + } + let turned = |i: usize| (i + len - first) % len; + let after_cut = |i: usize| i + usize::from(cut.is_some_and(|c| i > c)); + let runs = runs.into_iter().flat_map(|s| if cut == Some(s) { vec![s, s + 1] } else { vec![after_cut(s)] }).map(turned).collect(); + let kept = kept.into_iter().map(|(old, new)| (old, turned(after_cut(new)))).collect(); + (out, runs, kept) } /// `a` with its out (`out`) or in handle at `h` and the other as it is: still smooth when it was diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d500182401..0ff1b82594 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -22,9 +22,9 @@ pub use boolean::{ try_unite_all_with, unite_all, unite_all_with, }; pub use edit::{ - AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, - smooth_options, split_into_grid, + AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, START_SNAP, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, + join, remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, + smooth_level, smooth_options, split_into_grid, start_nearest, }; pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index a31c9af2e4..60410a0d5d 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -742,6 +742,74 @@ fn smooth_level_0_keeps_a_closed_paths_start_corner_within_tolerance() { assert!(moved <= limit, "level 0 moved the path by {moved} pt, more than {limit} pt: {:?}", s.subpaths[0].anchors[0]); } +/// Twice the area `sp` encloses, from 16 points along each segment: positive when it runs +/// counterclockwise in y-up terms. +fn signed_area(sp: &SubPath) -> f64 { + let pts: Vec = (0..sp.segment_count()).flat_map(|i| (0..16).map(move |k| sp.segment(i).eval(f64::from(k) / 16.0))).collect(); + (0..pts.len()).map(|i| pts[i].to_vec2().cross(pts[(i + 1) % pts.len()].to_vec2())).sum() +} + +/// A D of 41 corner points round (0, 0): the arc of radius 100 from (100, 0) up to (0, 100), the +/// straight side down to (0, -100), and the arc back. It starts in the middle of its arc, and its +/// first corner is at the top. +fn d_shape() -> SubPath { + let at = |deg: f64| Point::new(100.0 * deg.to_radians().cos(), 100.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20).map(|i| at(4.5 * f64::from(i))).chain((0..20).map(|i| at(-90.0 + 4.5 * f64::from(i)))).collect(); + SubPath::polyline(&pts, true) +} + +/// Object › Path › Simplify starts a closed path where it started, though the refit runs from the +/// first corner: on the D, the refit starts within the tolerance of the old start, runs the same way +/// round, and has fewer anchors. +#[test] +fn simplify_keeps_a_closed_paths_start() { + let sp = d_shape(); + let path = PathData::single(sp.clone()); + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); + assert!(one_way_distance(&path, &s).max(one_way_distance(&s, &path)) <= 1.0 + 1e-6); +} + +/// Object › Path › Smooth starts a closed path near where it started, though the refit runs from the +/// point where the path turns back: a round loop of radius 50 with a needle out to (250, 0), which +/// starts on the far side of the loop at (-50, 0). +#[test] +fn smooth_keeps_a_closed_paths_start() { + let at = |deg: f64| Point::new(50.0 * deg.to_radians().cos(), 50.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20) + .map(|i| at(180.0 + 8.95 * f64::from(i))) + .chain([Point::new(250.0, 0.0)]) + .chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))) + .collect(); + let sp = SubPath::polyline(&pts, true); + let path = PathData::single(sp.clone()); + let s = smooth_level(&path, SMOOTH_AUTO_LEVEL); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); +} + +/// A refit with only one anchor fewer than the closed path gets no anchor split in to keep its +/// start: it starts at its anchor nearest the old start. A rectangle with a straight point at +/// (30, 0) simplifies to its four corners, starting at (0, 0). +#[test] +fn simplify_starts_at_the_nearest_anchor_rather_than_add_one_back() { + let pts = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(|(x, y)| Point::new(x, y)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, straight_lines, ..Default::default() }); + let got: Vec = s.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(got, want, "straight_lines {straight_lines}"); + } +} + #[test] fn remove_redundant_collinear_and_curve() { let p = PathData::single(SubPath::polyline( diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9ca5ab7c48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7113,8 +7113,10 @@ result and the original path stay within `tolerance` of each other, except that is dropped, so a small circle in a compound path can be removed at a large `tolerance`. A segment that would need more than 65,536 samples at that tolerance stays as it is, and so does a segment after a run's first 16,777,216 samples or 2,097,152 result segments. With `straightLines`, such a segment becomes evenly spaced lines, up to 65,536, and past those -limits the lines can be farther than `tolerance` from the segment. With `level` or `auto`, the reply also has the `level` -used: +limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes +begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit +passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at +the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} @@ -7123,7 +7125,7 @@ used: With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then starts at the run's end anchor. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: @@ -7151,7 +7153,7 @@ side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the its length (by up to 5% of its longer side; none at level 0) and refitted with curves within 0.1% to 2.5% of it, keeping a corner only where it turns back on itself, so bumps, jags and kinks become one curve; with anchor points or segments of a path direct-selected (and no `ids`), only the sections between them are smoothed, as Simplify does. A refit never has more anchor points than the path had, so a shape whose corners the tolerance can't -round, such as a rectangle, stays as it is. Closed paths stay closed and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: +round, such as a rectangle, stays as it is. Closed paths stay closed and keep their start as Simplify keeps it, and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.smooth","params":{"level":80}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3af61d620e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,6 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From bab25d02487c087f44d143d0000ea33fb0de2660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:32:08 -0800 Subject: [PATCH 032/145] Scripts: a document opened from a linked file stays read-only when its path changes The gate now records each path a script's command reads only because it led to a file the open documents link to. A document whose file is such a path is taken out of the open documents' files for the rest of the run, without looking at where the path leads now or what the script may read now. Before, the gate decided that again for each command from the path's current target, so a path pointed at another file by a link, or a read grant given later, let the run read and write through the document. --- crates/engine/src/file_access.rs | 139 ++++++++++++++++++++++++++---- crates/engine/src/script/files.rs | 5 +- crates/engine/src/script/mod.rs | 11 +-- docs/mcp.md | 4 +- 4 files changed, 135 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 525094a990..890be26fb9 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -286,19 +286,52 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, - /// The real paths of the files the documents open when the run began link to, as they were - /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. - /// A path that leads to another file now is not one of them. - pub(crate) linked: Arc<[PathBuf]>, + /// The files the documents open when the run began link to: readable, not writable. + pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } +/// The files the commands a script runs may only read because the documents open when the run +/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. +/// Clones share the record of those paths. +#[derive(Clone, Debug, Default)] +pub(crate) struct LinkedFiles { + /// The real paths of the files, as they were when the run's first command was run, sorted. A + /// path that leads to another file now is not one of them. + files: Arc<[PathBuf]>, + /// The paths, absolute as a document holds its file, that a command read only because they led + /// to one of `files` when it read them. A document opened from one of them stays read-only for + /// the rest of the run, wherever the path leads later. + read: Arc>>, +} + +impl LinkedFiles { + /// Is `real`, a real path, one of the files? + fn has(&self, real: &Path) -> bool { + self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() + } + + /// The paths read through the files alone so far. + fn read_paths(&self) -> Vec { + self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() + } + + /// Notes that `path` was read through the files alone. + fn note_read(&self, path: &str) { + let path = crate::cmd::fileio::absolute_path(path); + let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !read.contains(&path) { + read.push(path); + } + } +} + impl ScriptGate { /// The real paths of the files at `paths` that are files now, each once, for /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, /// is left out. - pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + pub(crate) fn real_files(paths: impl IntoIterator) -> LinkedFiles { let mut real: Vec = paths .into_iter() .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) @@ -307,18 +340,20 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - real.into() + LinkedFiles { files: real.into(), read: Arc::default() } } /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. + /// run opened from such a file is read, never written. A document counts as one when a command + /// read its file through the linked files alone, whatever the path leads to or the script may + /// read now, and when its file is one of them now that nothing else lets the gate read. pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; - let linked = self.linked.clone(); + let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; + let (linked, read) = (self.linked.clone(), self.linked.read_paths()); let only_linked = |d: &String| { let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) }; self.documents.retain(|d| before.contains(d) || !only_linked(d)); self @@ -342,10 +377,17 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), + Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { + return true; + } + let linked = matches!(access, Access::Read) && self.linked.has(&real); + if linked { + self.linked.note_read(path); + } + linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -957,7 +999,7 @@ mod tests { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -986,7 +1028,7 @@ mod tests { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -1013,7 +1055,7 @@ mod tests { std::fs::write(&other, "").unwrap(); let later = base.join("outside/later.svg"); let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); - assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}"); let gate = ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; std::fs::write(&later, "").unwrap(); @@ -1053,6 +1095,73 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A document opened from a file a command read through the linked files alone stays + /// read-only after the script is allowed to read that file's folder, and after the file is + /// replaced by another one. + #[test] + fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { + let (base, _) = folders("linked-granted"); + let secret = s(base.join("outside/secret.svg")); + let linked = ScriptGate::real_files([secret.clone()]); + let gate = |read: &str, documents: Vec| ScriptGate { + read: ScriptScope::of_folder(&base.join(read)), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(granted.check(&secret, Access::Read).is_ok()); + assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); + std::fs::remove_file(&secret).unwrap(); + std::fs::write(&secret, "").unwrap(); + let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document opened from a file a command read through the linked files alone gives no + /// access to the file its path leads to after the path is pointed elsewhere by a link. + #[test] + fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + let (base, _) = folders("linked-redirected"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok(); + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via")); + for dir in [&first, &second] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("a.svg"), "").unwrap(); + } + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&first, &via) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); + let linked = ScriptGate::real_files([doc.clone()]); + let gate = |documents: Vec| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); + assert!(made(&second, &via)); + let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); + for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { + assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + } + let _ = std::fs::remove_dir_all(base); + } + /// A link to a linked file read through the gate counts only while it leads to that file. #[cfg(unix)] #[test] diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 34179a55b5..2c63c9cd66 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -73,9 +73,8 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -459,7 +458,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, the files of the /// open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. - pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 62dc11df23..9e3419d10d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -806,9 +806,9 @@ struct Host { /// The files of the documents open when the run began /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). opened_before: Vec, - /// The real paths of the files the documents open when the run began link to - /// ([`crate::file_access::ScriptGate::linked`]). - linked: std::cell::OnceCell>, + /// The files the documents open when the run began link to, and the paths the run's commands + /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell, } /// A document open when a run began, with its own file and the file it was read from. @@ -817,8 +817,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. - fn linked(&self) -> Arc<[std::path::PathBuf]> { + /// changes, and a document it opens, give it no file to read. Every command's gate shares the + /// record of the paths read through them. + fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); diff --git a/docs/mcp.md b/docs/mcp.md index 9a1f57c42f..6c0de9e418 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,9 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it. The files are taken as those links led at the run's + saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its + path leads to another file later, the document does not let the script read or write that file. The files are + taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points elsewhere, and a document it opens, does not let it read any file it could not read before. The automation read roots still apply. From 956a76baa65af79fc6212a7cb89023cc4a812a8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:36:06 -0800 Subject: [PATCH 033/145] Paths: tied start candidates at one point search the old path once When several refit points tie for nearest to a closed path's old start, the earliest-along-the-path tie rule now places each distinct point on the old path once, so many segments meeting at one point no longer search every old segment once each. The tie rule is unchanged. Also "the same way around" in the docs. --- crates/pathops/src/edit.rs | 42 ++++++++++++++++++++++++++++++++------ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index a26da95828..d95a6c9037 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -1,7 +1,7 @@ //! Object → Path commands: Simplify, Smooth, Remove redundant points, Add Anchor Points, Average, //! Join, Split Into Grid. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -128,6 +128,8 @@ const START_TIE: f64 = 1e-6; /// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place /// when there is none. fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + #[cfg(test)] + tests::count_places(); let mut best: Option<(f64, usize, f64)> = None; for j in 0..orig.anchors.len() { let hit = orig.segment(j).nearest(p, 1e-9); @@ -140,11 +142,14 @@ fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { /// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: /// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from -/// its first anchor, then the first given. +/// its first anchor, then the first given. Each distinct point is placed along `orig` once. fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { // (distance, place along `orig` once a tie needs it, point, value) type Best = (f64, Option<(usize, f64)>, Point, T); let mut best: Option> = None; + // Places along `orig` by the bits of the point, so many ties at one point search `orig` once. + let mut placed: HashMap<[u64; 2], (usize, f64)> = HashMap::new(); + let mut place = |p: Point| *placed.entry([p.x.to_bits(), p.y.to_bits()]).or_insert_with(|| place_along(orig, p)); for (d, p, x) in candidates { if !d.is_finite() { continue; @@ -152,10 +157,10 @@ fn earliest_nearest(candidates: impl IntoIterator, or match &mut best { None => best = Some((d, None, p, x)), Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); - let place = place_along(orig, p); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), p, x)); + let held = *bplace.get_or_insert_with(|| place(*bp)); + let at = place(p); + if at.0 < held.0 || (at.0 == held.0 && at.1 < held.1) { + best = Some((d, Some(at), p, x)); } } Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), @@ -1533,6 +1538,31 @@ mod tests { MOVES.set(MOVES.get() + n); } + std::thread_local! { + /// Calls of [`place_along`], each a search of every segment of the path before the refit. + static PLACES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_places() { + PLACES.set(PLACES.get() + 1); + } + + /// Candidates tied at one point are placed along the old path once, not once each, and the first + /// given still wins the tie. + #[test] + fn tied_candidates_at_one_point_are_placed_once() { + let orig = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0)), Anchor::corner(Point::new(100.0, 100.0))], + true, + ); + let candidates = (0..1000).map(|i| (0.0, Point::new(0.0, 0.0), i)); + PLACES.set(0); + let got = earliest_nearest(candidates, &orig); + let places = PLACES.get(); + assert_eq!(got, Some(0)); + assert_eq!(places, 1, "searches of the old path for 1000 candidates at one point"); + } + /// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle. fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath { let mut rnd = || { diff --git a/docs/mcp.md b/docs/mcp.md index 9ca5ab7c48..e3043ece27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7116,7 +7116,7 @@ than 65,536 samples at that tolerance stays as it is, and so does a segment afte limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at -the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: +the refit's anchor nearest that point. It runs the same way around as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3af61d620e..677cc05923 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,7 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. - Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way around. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From 263718ffd24f5dc41b5c60d6fda529fdfb41a5b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:58:10 -0800 Subject: [PATCH 034/145] Paths: a run across a closed path's start keeps the new start on that run When a direct-selected run holds a closed path's first anchor, Simplify and Smooth now look for the new start on that run alone, so an unselected segment that passes through the old start is not split. When the first anchor stays, the path already starts there and is left as it is. --- crates/pathops/src/edit.rs | 85 +++++++++++++++++++++++++++++++------- docs/mcp.md | 3 +- 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index d95a6c9037..dd5d84ebe7 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -2,6 +2,7 @@ //! Join, Split Into Grid. use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ops::Range; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -114,7 +115,10 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit /// starts where the subpath started ([`keep_start`]). fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { - refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) + refit_subpath(sp, opts).map(|fit| { + let n = fit.anchors.len(); + keep_start(fit, sp, 0..n).0 + }) } /// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] @@ -176,18 +180,21 @@ fn earliest_nearest(candidates: impl IntoIterator, or /// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - start_near(sp, start, orig, true).0 + let n = sp.anchors.len(); + start_near(sp, start, orig, true, 0..n).0 } -/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies -/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → -/// (the path, the segment split when one was, where the new start was before the anchors turned). -fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { +/// [`start_nearest`] on the segments `within` alone, splitting a segment only when `split` is set; +/// otherwise, when no anchor lies at the nearest point, the path starts at the anchor of those +/// segments nearest `start`, with the same tie rule. → (the path, the segment split when one was, +/// where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within: Range) -> (SubPath, Option, usize) { let n = sp.anchors.len(); if !sp.closed || n < 2 { return (sp, None, 0); } - let hits = (0..n).map(|i| { + let within = within.start.min(n)..within.end.min(n); + let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; @@ -212,7 +219,8 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + // The anchors of the segments `within`: each one's first, and the last one's end. + let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); (earliest_nearest(near, orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); @@ -221,13 +229,13 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su /// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at /// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has -/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An -/// open `orig` keeps `fit` as it is. -fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]), +/// looking only at the segments `within`. An open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath, within: Range) -> (SubPath, Option, usize) { match orig.anchors.first() { Some(a) if orig.closed => { let split = fit.anchors.len() + 1 < orig.anchors.len(); - start_near(fit, a.p, orig, split) + start_near(fit, a.p, orig, split, within) } _ => (fit, None, 0), } @@ -820,7 +828,8 @@ pub struct SimplifiedPart { /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more /// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath -/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]), on the run that held its +/// first anchor when that anchor goes. pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -859,6 +868,7 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP let mut anchors = vec![sp.anchors[start]]; let mut kept = vec![(start, 0)]; let mut runs = vec![]; + let mut start_run = None; let mut k = 0; while k < n { let j = (start + k) % n; @@ -891,7 +901,12 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } // The run's segments, from its first anchor on: a run back to the walk's start ends with // the closing segment, the last index. - runs.extend(first..first + if keep_original { run.len() } else { fitted.len() }); + let segs = first..first + if keep_original { run.len() } else { fitted.len() }; + if sp.closed && (k + 1..k + len).any(|i| (start + i) % m == 0) { + // The run that held the old first anchor. + start_run = Some(segs.clone()); + } + runs.extend(segs); let end_seg = fitted.last().filter(|_| !keep_original); if sp.closed && k + len == n { // The run ends where the walk started. @@ -908,8 +923,11 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. - let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + // A closed subpath starts where it did: the walk already starts at its first anchor when that + // stays, and otherwise the run that held it starts the path ([`keep_start`] on that run's + // segments alone, so no other segment changes), with the runs and anchors kept renumbered. + let Some(within) = start_run else { return (SubPath::new(anchors, sp.closed), runs, kept) }; + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp, within); let len = out.anchors.len(); if (cut, first) == (None, 0) || len == 0 { return (out, runs, kept); @@ -1547,6 +1565,41 @@ mod tests { PLACES.set(PLACES.get() + 1); } + /// A refitted run across the start of a closed path that crosses itself at its start keeps the + /// start on the run: the unselected segment through the old start is not split. + #[test] + fn a_run_across_the_start_keeps_the_start_on_the_run() { + let pts = [ + (0.0, 0.0), + (10.0, 0.3), + (20.0, -0.3), + (30.0, 0.3), + (40.0, 0.6), + (40.0, 50.0), + (0.0, 50.0), + (0.0, -50.0), + (-40.0, -50.0), + (-40.0, 0.6), + (-30.0, 0.3), + (-20.0, -0.3), + (-10.0, 0.3), + ]; + let sp = SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true); + let path = PathData::new(vec![sp]); + let picked: BTreeSet<(usize, usize)> = [9, 10, 11, 12, 0, 1, 2, 3].into_iter().map(|s| (0, s)).collect(); + let out = simplify_part(&path, &picked, &SimplifyOptions { tolerance: 1.0, ..SimplifyOptions::default() }); + let got = &out.path.subpaths[0]; + let n = got.anchors.len(); + assert!(n < pts.len(), "{n} anchors"); + let (top, bottom) = (Point::new(0.0, 50.0), Point::new(0.0, -50.0)); + assert!( + (0..n).any(|i| got.anchors[i].p == top && got.anchors[(i + 1) % n].p == bottom), + "the segment through the old start was split: {:?}", + got.anchors.iter().map(|a| a.p).collect::>() + ); + assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e3043ece27..8f907cea87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7125,7 +7125,8 @@ the refit's anchor nearest that point. It runs the same way around as before. Wi With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does, with the new start on +that run. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: From c8d02b0dbd7d8d7b287e72864290b2a45af2cc3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:58:33 -0800 Subject: [PATCH 035/145] Retype: a glyph in an even-odd compound matches with only some of its contours reversed An even-odd compound paints the same whichever way each contour runs, so an o's counter may run the same way as its outer contour. Such a part matched neither as it is nor with all its contours reversed, and stayed an outline at tolerance 0. A part of a split compound is now also read with each contour turned the way its depth gives (outer contours one way, their counters the other), both ways round. In a nonzero compound those contours paint the counter, and the painted-area check still keeps the part an outline. The containment test that splits a compound into glyphs moves into its own function, `containers`, which the new reading also calls. Docs: docs/mcp.md, docs/type-parity.md. --- crates/engine/src/cmd/retype.rs | 2 +- crates/engine/src/cmd/retype_tests.rs | 28 ++++ crates/text/src/retype.rs | 209 +++++++++++++++++++++----- docs/mcp.md | 5 +- docs/type-parity.md | 2 +- 5 files changed, 207 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b0d37a1d61..81972395e2 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, 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 )] diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 2727dd4432..7151ba0a23 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1385,6 +1385,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { assert_eq!(r["texts"], json!(["oo"]), "{r}"); } +#[test] +fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() { + // An even-odd compound paints the same whichever way its contours run, so an o's counter may + // run the same way as its outer contour: neither the part as it is nor all its contours turned + // is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the + // compound stays an outline. + for turned in [1usize, 2] { + let mut s = session(); + let c = one_compound(&mut s, "do"); + // One path per contour: the d's two, then the o's two. + let paths = children_of(&s, c); + assert_eq!(paths.len(), 4, "a d and an o are two contours each"); + let p = paths[paths.len() - turned]; + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths()); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + #[test] fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let mut s = session(); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 0a991c669f..aed9d29679 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -360,13 +360,25 @@ impl RetypeIndex { /// [`Self::all_matches`], and when the shape fits no glyph as it is, its contours read the /// other way round: for a part of a compound path, which Make Compound Path may have turned so - /// it cuts a hole in the paths behind it. + /// it cuts a hole in the paths behind it. When neither reading fits, the contours are read the + /// way their depth gives, outer contours one way and their counters the other, both ways round: + /// an even-odd compound paints the same whichever way each contour runs, so an o's counter may + /// run the same way as its outer contour. pub fn matches_either_way(&self, shape: &BezPath) -> Vec { let found = self.matches_read(shape, shape); if !found.is_empty() { return found; } - self.matches_read(shape, &shape.reverse_subpaths()) + let found = self.matches_read(shape, &shape.reverse_subpaths()); + if !found.is_empty() { + return found; + } + let Some(nested) = nested_reading(shape) else { return vec![] }; + let found = self.matches_read(shape, &nested); + if !found.is_empty() { + return found; + } + self.matches_read(shape, &nested.reverse_subpaths()) } /// [`Self::all_matches`] of `shape`, its contours read as in `reading` (the same outline). @@ -880,39 +892,7 @@ pub fn clusters(path: &BezPath) -> Vec { }, } } - let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); - // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in - // another only when every one of them does. - let probes: Vec> = subs - .iter() - .map(|s| { - let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); - let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); - anchors.into_iter().step_by(step).collect() - }) - .collect(); - // Each contour's container: the smallest contour around it. - let parent: Vec> = (0..subs.len()) - .map(|i| { - let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; - if pi.is_empty() { - return None; - } - (0..subs.len()) - .filter(|&j| j != i) - .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) - .filter(|(_, bj, sj)| { - bj.area() > bi.area() - && bj.x0 <= bi.x0 - && bj.y0 <= bi.y0 - && bj.x1 >= bi.x1 - && bj.y1 >= bi.y1 - && pi.iter().all(|p| sj.winding(*p) != 0) - }) - .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) - .map(|(j, _, _)| j) - }) - .collect(); + let parent = containers(&subs); let root = |mut i: usize| { // Containers are strictly larger, so the chain ends; the bound keeps it so. for _ in 0..subs.len() { @@ -935,6 +915,90 @@ pub fn clusters(path: &BezPath) -> Vec { groups.into_iter().map(|(_, p)| p).collect() } +/// Each contour's container among `subs` (one contour each): the smallest other contour that holds +/// it, `None` for an outer contour. +fn containers(subs: &[BezPath]) -> Vec> { + let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); + // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in + // another only when every one of them does. + let probes: Vec> = subs + .iter() + .map(|s| { + let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); + let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); + anchors.into_iter().step_by(step).collect() + }) + .collect(); + // Each contour's container: the smallest contour around it. + (0..subs.len()) + .map(|i| { + let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; + if pi.is_empty() { + return None; + } + (0..subs.len()) + .filter(|&j| j != i) + .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) + .filter(|(_, bj, sj)| { + bj.area() > bi.area() + && bj.x0 <= bi.x0 + && bj.y0 <= bi.y0 + && bj.x1 >= bi.x1 + && bj.y1 >= bi.y1 + && pi.iter().all(|p| sj.winding(*p) != 0) + }) + .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) + .map(|(j, _, _)| j) + }) + .collect() +} + +/// `path` with each contour turned to run the way its depth gives (an outer contour one way, its +/// counters the other, what lies in those the first way again), the outer contours keeping the way +/// the first of them runs. `None` when that turns no contour (the path read as it is), for a +/// contour that encloses no area, and for more than [`MAX_CONTOURS`] contours. +fn nested_reading(path: &BezPath) -> Option { + let mut subs: Vec = vec![]; + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + if subs.len() >= MAX_CONTOURS { + return None; + } + subs.push(BezPath::new()); + } + subs.last_mut()?.push(*el); + } + let parent = containers(&subs); + let depth = |mut i: usize| { + let mut d = 0usize; + // Containers are strictly larger, so the chain ends; the bound keeps it so. + for _ in 0..subs.len() { + match parent.get(i).copied().flatten() { + Some(p) => { + i = p; + d += 1; + } + None => break, + } + } + d + }; + let areas: Vec = subs.iter().map(Shape::area).collect(); + if areas.iter().any(|a| !a.is_normal()) { + return None; + } + let outer = (0..subs.len()).find(|&i| depth(i) == 0).and_then(|i| areas.get(i)).map(|a| a.signum())?; + let turned: Vec = areas.iter().enumerate().map(|(i, a)| a.signum() != if depth(i) % 2 == 0 { outer } else { -outer }).collect(); + if turned.iter().all(|t| !*t) { + return None; + } + let mut out = BezPath::new(); + for (s, t) in subs.iter().zip(&turned) { + out.extend(if *t { s.reverse_subpaths() } else { s.clone() }.iter()); + } + Some(out) +} + /// `a` wrapped into −π..π. fn wrapped(a: f64) -> f64 { (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI @@ -2271,6 +2335,81 @@ mod tests { assert!(clusters(&BezPath::new()).is_empty()); } + #[test] + fn the_nested_reading_turns_counters_against_their_outer_contour() { + let split = |p: &BezPath| -> Vec { + let mut out: Vec = vec![]; + for el in p.elements() { + if matches!(el, PathEl::MoveTo(_)) { + out.push(BezPath::new()); + } + out.last_mut().unwrap().push(*el); + } + out + }; + let join = |cs: &[BezPath]| { + let mut p = BezPath::new(); + for c in cs { + p.extend(c.iter()); + } + p + }; + let cs = split(&letter()); + let (outer, counter) = (cs[0].clone(), cs[1].clone()); + let (same, opposite) = if outer.area().signum() == counter.area().signum() { + (counter.clone(), counter.reverse_subpaths()) + } else { + (counter.reverse_subpaths(), counter.clone()) + }; + // A counter running the same way as its outer contour is turned; the outer one is kept. + let read = nested_reading(&join(&[outer.clone(), same.clone()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[0], outer); + assert_eq!(rs[1].area().signum(), opposite.area().signum()); + // So is the outer contour's way when it comes second. + let read = nested_reading(&join(&[opposite.clone(), outer.reverse_subpaths()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[1], outer.reverse_subpaths()); + assert_eq!(rs[0].area().signum(), outer.area().signum()); + // Already nested so: nothing to turn. + assert!(nested_reading(&join(&[outer.clone(), opposite])).is_none()); + // A contour enclosing no area gives none. + let mut flat = BezPath::new(); + flat.move_to((0.0, 0.0)); + flat.line_to((10.0, 0.0)); + flat.close_path(); + assert!(nested_reading(&join(&[outer, flat])).is_none()); + } + + #[test] + fn a_part_with_some_contours_turned_still_matches_exactly() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::named_copy(false, ("Turntest", "Regular", "Version 1.000", "Turntest-Regular")).unwrap()), 1); + let face = db.face("Turntest", "Regular").unwrap(); + let o = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut cs: Vec = vec![]; + for el in o.elements() { + if matches!(el, PathEl::MoveTo(_)) { + cs.push(BezPath::new()); + } + cs.last_mut().unwrap().push(*el); + } + assert_eq!(cs.len(), 2, "an o is two contours"); + let keys = std::iter::once(shape_key(&o).unwrap()).collect(); + let index = RetypeIndex::build(&db, vec![face], &keys); + assert!(!index.all_matches(&o).is_empty()); + for turned in 0..2 { + let mut shape = BezPath::new(); + for (i, c) in cs.iter().enumerate() { + shape.extend(if i == turned { c.reverse_subpaths() } else { c.clone() }.iter()); + } + assert!(index.all_matches(&shape).is_empty(), "contour {turned} turned is no glyph as it is"); + assert!(index.all_matches(&shape.reverse_subpaths()).is_empty(), "nor read the other way round"); + let found = index.matches_either_way(&shape); + assert!(found.iter().any(|m| m.ch == 'o'), "contour {turned} turned still matches the o"); + } + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..41b31464d7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11456,8 +11456,9 @@ at a leftover distance of 0.05. A compound path that holds several glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other -way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come -first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The +way round, as Make Compound Path leaves some of them, still matches exactly, and so does one where only some of its +contours run the other way round (in an even-odd compound, an o's counter and not its outer contour). Exact matches +of the whole shape come first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule diff --git a/docs/type-parity.md b/docs/type-parity.md index 868b944bcd..94993affe1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a 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 (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a 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 (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From 2d6b8680e6de3d718dadd704b09a7d34130a966d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:01:48 -0800 Subject: [PATCH 036/145] Dimension tool: whole-path dimensions keep clear of the path when turned A dimension of a whole path whose line lay across the path, made vertical or horizontal with dimension.update, now goes as far past the path as it lay from its first point. Before, its line landed on the path's edge. A line on the edge to within rounding still counts as outside the path. When the new place would be more than 1,000,000 pt from the first point, the update is an error unless it also gives offset, and the dimension is left as it was. A dimension whose measured node is missing or is not a path, as in a file that names a node it does not hold, is unlinked at the next edit. Tests: a dimension of a whole path saved in a native file and opened again still follows the path, and one that names a missing node is unlinked at the next edit; past a corner of the path the side the pointer is farther out on decides; after the first point Alt picks a point; a hovered segment's length stays by the pointer at a high zoom. The line in docs/target-app-parity.md now attributes only the Alt hover over a path to the linear dimensions help page. Docs: docs/dimensions.md and dimension.update's params text. --- crates/doc/src/dimension.rs | 62 ++++++++++++++++++--------- crates/engine/src/cmd/dimension.rs | 11 ++++- crates/engine/tests/it/dimensions.rs | 64 ++++++++++++++++++++++++++++ crates/tools/src/dimension.rs | 25 +++++++++++ docs/dimensions.md | 8 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 145 insertions(+), 27 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 0b50358622..3e08f96977 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -425,10 +425,11 @@ impl DimensionSource { }) } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. + /// A node without a path, or missing from both, counts as changed. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { - (Some(old), Some(new)) => !std::ptr::eq(old, new) && old.path_data() != new.path_data(), - (old, new) => old.is_some() != new.is_some(), + (Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()), + _ => true, }) } /// The map that took the measured art from `before` to `after`, when every path it measures @@ -861,28 +862,44 @@ impl Dimension { /// that side as the old line lay from its points. A dimension of a whole path /// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the /// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on - /// the side the middle of the old line is on. + /// the side the middle of the old line is on. A line that lay across the path goes as far past + /// the path as it lay from its first point. For such a dimension it is an error when the path + /// no longer exists, or when the line would lie more than 1,000,000 pt from its first point, + /// and the dimension is then left as it was. pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> { if self.mode != DimensionMode::Linear || self.orientation == orientation { self.orientation = orientation; return Ok(()); } - let (handle, mut gap) = (self.handle(), self.offset.abs()); - if let Some(DimensionSource::Extent { .. }) = &self.source { - // Measured from the whole path. - let (low, high) = self.span(Some(doc)); - let line = self.a.to_vec2().dot(self.normal()) + self.offset; - gap = if line >= high { line - high } else { (low - line).max(0.0) }; + let mut next = self.clone(); + let (handle, mut gap) = (next.handle(), next.offset.abs()); + if let Some(DimensionSource::Extent { .. }) = &next.source { + // Measured from the whole path, relative to the first point, which the line is + // `offset` from. A line on the path's edge, to within the rounding of the + // projections, is outside it. + let n = next.normal(); + let base = next.a.to_vec2().dot(n); + let (low, high) = next.span(Some(doc)); + let eps = 8.0 * f64::EPSILON * ((next.a.x * n.x).abs() + (next.a.y * n.y).abs() + low.abs() + high.abs()); + let (low, high, line) = (low - base, high - base, next.offset); + gap = if line >= high - eps { + (line - high).max(0.0) + } else if line <= low + eps { + (low - line).max(0.0) + } else { + gap + }; } - self.orientation = orientation; - if let Some(DimensionSource::Extent { node }) = &self.source { - (self.a, self.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + next.orientation = orientation; + if let Some(DimensionSource::Extent { node }) = &next.source { + (next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; } - let n = self.normal(); - let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = self.span(Some(doc)); - let h = across(handle); - let whole = matches!(self.source, Some(DimensionSource::Extent { .. })); + // Along the new normal, relative to the new first point, so that the result is the offset. + let n = next.normal(); + let base = next.a.to_vec2().dot(n); + let (low, high) = next.span(Some(doc)); + let (low, high, h) = (low - base, high - base, handle.to_vec2().dot(n) - base); + let whole = matches!(next.source, Some(DimensionSource::Extent { .. })); let at = if whole && h >= high { high + gap } else if whole && h <= low { @@ -894,11 +911,14 @@ impl Dimension { } else { low - gap }; - let offset = at - across(self.a); - if offset.is_finite() && offset.abs() <= 1e6 { - self.offset = offset; + if at.is_finite() && at.abs() <= 1e6 { + next.offset = at; + } else if whole { + // The old offset would put the line across the path. + return Err("Invalid dimension offset".into()); } - self.length = self.measured(); + next.length = next.measured(); + *self = next; Ok(()) } fn bisector(&self) -> Vec2 { diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 27e1d81ae8..610558be73 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Update Dimensions", [], None, - "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", + "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on; for an extent source, an error when that would put the line more than 1,000,000 pt from its first point and no offset is given), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", has_doc, update ), @@ -175,7 +175,14 @@ fn update(s: &mut Session, p: &Value) -> Result { dim.options = o.clone(); } if let Some(orientation) = orientation(p, dim.mode)? { - dim.set_orientation(orientation, doc).map_err(error)?; + // An offset given with the orientation replaces the one the orientation would + // give: the dimension takes the orientation, and `resolve` reads its points. + if let Err(e) = dim.set_orientation(orientation, doc) { + if p.get("offset").is_none() { + return Err(error(e)); + } + dim.orientation = orientation; + } } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 2cbd61de92..2c0738f737 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -596,6 +596,28 @@ fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() { assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}"); let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min); assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line"); + + // A line across the path, 30 pt below the top, made vertical: it goes 30 pt past the path's + // side rather than onto it. + let rect = run(&mut s, "shape.rectangle", json!({"x":600,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 570.0).abs() < 1e-6 || (line - 730.0).abs() < 1e-6, "line at x = {line}, path from 600 to 700"); + // When that would put the line farther from its first point than an offset may be, the + // change is refused rather than leaving the line across the path. + let far = run(&mut s, "path.create", json!({"d":"M0 0 L950000 -100 L950000 200000 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":far},"orientation":"horizontal","offset":100000}))["id"] + .as_u64() + .unwrap(); + assert!(s.execute("dimension.update", &json!({"ids":[id],"orientation":"vertical"})).is_err()); + assert_eq!(recipe(&s, id).orientation, vectorcraft_doc::dimension::Orientation::Horizontal); + // An offset given with the orientation places the line instead. + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical","offset":-30})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 950030.0).abs() < 1e-6, "line at x = {line}"); } /// The line of a linked horizontal dimension keeps its gap from the outermost point on its side @@ -1223,6 +1245,48 @@ fn free_points_survive_a_native_file() { assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); } +/// Saved and opened again, a dimension of a whole path still measures the path: turned, the path +/// is wider than before, and so is the dimension. +#[test] +fn a_dimension_of_a_whole_path_survives_a_native_file() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + let before = recipe(&s, id); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + assert_eq!(recipe(&reopened, id).source, before.source); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&reopened, id) - wide).abs() < 0.01, "{} against {wide}", text(&reopened, id)); + + // A file whose dimension names a node that is not there: the next edit unlinks it. + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + fn dangle(v: &mut Value) { + match v { + Value::Object(m) => { + if m.get("kind") == Some(&json!("extent")) { + m.insert("node".into(), json!(99999)); + } + m.values_mut().for_each(dangle); + } + Value::Array(a) => a.iter_mut().for_each(dangle), + _ => {} + } + } + dangle(&mut v); + let mut dangling = Session::new(); + dangling.add_document(vectorcraft_format::load(&serde_json::to_vec(&v).unwrap()).unwrap(), None); + assert!(recipe(&dangling, id).source.is_some()); + run(&mut dangling, "shape.rectangle", json!({"x":300,"y":300,"width":10,"height":10})); + assert!(recipe(&dangling, id).source.is_none(), "no longer linked"); +} + /// A linked dimension opened from a file with options it cannot be drawn with keeps its art, as a /// plain group, when the art it measures is deleted. #[test] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index f5a9ca880c..fe82d4df30 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -2365,6 +2365,11 @@ mod tests { let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); assert_eq!(above["source"], json!({"kind":"extent","node":id})); assert_eq!(above["orientation"], json!("horizontal")); + // Past a corner, the side the pointer is farther out on decides. + let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0))); + assert_eq!(corner["orientation"], json!("vertical")); + let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 230.0, 40.0))); + assert_eq!(corner["orientation"], json!("horizontal")); let beside = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 260.0, 150.0))); assert_eq!(beside["orientation"], json!("vertical")); t.pointer(&c, &PointerEvent::new(PointerKind::Down, 260.0, 150.0)); @@ -2383,6 +2388,26 @@ mod tests { t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)); t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); assert!(t.pending.is_none() && t.points.len() == 1, "a plain click picks a point"); + // After the first point, Alt does not make the path whole: the second click picks a point. + t.pointer(&c, &held(PointerKind::Move, 100.0, 150.0)); + assert!(matches!(t.hover, Some(Target::Segment(_))), "{:?}", t.hover); + t.pointer(&c, &held(PointerKind::Down, 100.0, 150.0)); + t.pointer(&c, &held(PointerKind::Up, 100.0, 150.0)); + let d = t.pending.as_ref().expect("the second click starts placing a dimension between the two points"); + assert!( + !matches!(d.source, Some(DimensionSource::Extent { .. })) + && d.a.distance(Point::new(150.0, 100.0)) < 1e-6 + && d.b.distance(Point::new(100.0, 150.0)) < 1e-6, + "{d:?}" + ); + + // A hovered segment's length also stays by the pointer at a high zoom. + let mut t = DimensionTool::default(); + t.pointer(&zoomed, &PointerEvent::new(PointerKind::Move, 150.0, 100.0)); + assert!(matches!(t.hover, Some(Target::Segment(_))), "{:?}", t.hover); + let o = t.overlays(&zoomed); + let near = |o: &Overlay| matches!(o, Overlay::Measure { p, .. } if p.distance(Point::new(150.0, 100.0)) < zoomed.tol(20.0)); + assert!(o.iter().any(near), "{o:?}"); } /// A point that Smart Guides leave where the pointer already is (the pointer right in line diff --git a/docs/dimensions.md b/docs/dimensions.md index ba1fd687df..f886371dbb 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -84,7 +84,7 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers placed. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) - describes plotting an object's overall horizontal and vertical dimensions by holding Alt + describes plotting an object's horizontal and vertical dimensions by holding Alt (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when they are off, with its width and height beside the pointer when Measurement Labels are on. @@ -177,8 +177,10 @@ another document. line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear - ones. A new orientation keeps the line on the side of the points it was on. An update that - changes nothing records no undo step. + ones. A new orientation keeps the line on the side of the points it was on. For a dimension of + a whole path, a new orientation that would put the line more than 1,000,000 pt from its first + point is an error unless the update also gives `offset`. An update that changes nothing records + no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and `tool.setOption {"tool":"dimension","values":{"mode":"linear","style":{"units":"mm","scale":"1:10"}}}` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e35dd9151..6b185f98d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -684,7 +684,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path (#5590):** With Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), and a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes; by VectorCraft's own rule the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height` and `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From d8db9eda83f7919b621fa70d08d3709b79571759 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:42:10 -0800 Subject: [PATCH 037/145] Symbols: Direct Selection picks a dynamic instance's part where its fill and stroke effects draw it A geometry effect on a dynamic symbol instance's fill or stroke moves or reshapes the art the canvas draws, and a click there already selects the instance. Direct Selection still picked a part of the art at its plain shape and outlined that shape, so a click on the drawn result picked nothing and a click where the part no longer paints picked it. symbol_part_at and symbol_part_outline_in_view now test and outline the instance's art with the effects of its active fill and stroke added, as the canvas adds them. Live objects in the art keep their place, so the child-index path still leads to the part. A nested instance is picked and outlined where its reshaped art is drawn, type with a fill or stroke of its own where its reshaped glyphs are drawn (Type Object Selection by Path Only still takes the type path), and an image's outline includes the shapes its own fills and strokes paint. A clipping path is still picked and outlined by its own geometry. Outline view and layers with Preview off keep the plain shapes; blends, envelopes and repeats in the art are picked without the instance's effects. --- crates/doc/src/hit.rs | 179 +++++++++++++++++++-- crates/effects/src/lib.rs | 6 +- crates/effects/src/reshape.rs | 28 +++- crates/engine/src/session/documents.rs | 3 + crates/engine/src/tests/dynamic_symbols.rs | 154 ++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 347 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..6286597882 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -115,6 +115,22 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } +/// Adds the geometry and raster effects of a symbol instance's active fill and stroke to the fills +/// and strokes that paint in the art it is given, the instance's art in the symbol's coordinates, +/// as the canvas adds them to the art it draws. Every object keeps its place in the art, so the +/// child indices of [`symbol_part_at`] still lead to it. Effects are evaluated above this crate, so +/// the engine registers one with [`set_instance_row_art`]. +pub type InstanceRowArt = fn(Option<&Document>, &Node, &mut Node); + +static INSTANCE_ROW_ART: OnceLock = OnceLock::new(); + +/// Register how a symbol instance's art takes the effects of the instance's fill and stroke, for +/// Direct Selection's parts (the first registration stays). +pub fn set_instance_row_art(f: InstanceRowArt) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_ROW_ART.set(f); +} + /// The shapes that [`ImagePaint`] gives for one object. type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; @@ -1575,12 +1591,45 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio /// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a /// stroke along its shape, a fill inside it except with Selection by Path Only. fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + painted_hit(&image_paint(Some(symbols.document()), n), p, opt) +} + +/// What a click at `p` hits among `painted`, the shapes [`image_paint`] gives, as [`hit_painted`] +/// tests them. +fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option { + painted.iter().rev().find_map(|(bp, rule, item)| match item { AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), }) } +/// Is `n` a symbol instance whose active fill or stroke has geometry effects that reshape the art +/// it draws ([`image_paint`])? Callers ask [`own_effects_art`] first, which takes an instance whose +/// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow) +/// is tested here. Never with `outline`, where the canvas draws no effects, nor while a +/// [`DrawnOff`] guard lives. +fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { + !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && !image_paint(Some(symbols.document()), n).is_empty() +} + +/// The art that symbol instance `n` draws with a visible effect of its own, the effects of its +/// fills and strokes and those of its symbol's art all applied, or that type `n` draws with the +/// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]). +/// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or +/// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect +/// changes what it draws. +fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option { + let has = match n.kind { + NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible), + NodeKind::Text(_) => has_own_effects(n), + _ => false, + }; + if outline || DRAWN_OFF.get() || !has { + return None; + } + DRAWN_ART.get()?(symbols, n) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -1690,6 +1739,17 @@ impl<'a> InstanceArt<'a> { Some(Self { art, map, xf: *xf, boxes }) } + /// [`Self::of`] with the effects of the instance's active fill and stroke added to the fills and + /// strokes in the art ([`set_instance_row_art`]), so that each object of it is tested and + /// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects. + fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option { + let mut art = Self::of(doc, inst)?; + if !outline && let Some(f) = INSTANCE_ROW_ART.get() { + f(Some(doc), inst, &mut art.art); + } + Some(art) + } + /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides @@ -1751,15 +1811,18 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not /// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a -/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or -/// no editable object of its art is under `p`. +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. Elsewhere each +/// object is tested where the geometry effects of the instance's active fill and stroke draw it +/// ([`InstanceArt::drawn`]), and not where its own shape no longer paints. Live objects in the art +/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a +/// symbol instance or no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { let _walk = ArtWalk::open(); - let art = InstanceArt::of(doc, inst)?; + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; - let outline = opt.outline || below_preview_off(doc, inst, opt.scope); - let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; + let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; find.find(&art.art, &mut path, None, outline).map(|_| path) } @@ -1772,14 +1835,35 @@ struct FindPart<'a> { /// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws /// them, and clipping paths are not picked by their outline. whole_instance: bool, + /// For [`symbol_part_at`] and [`drawn_instance_hit`]: the art carries the effects of the + /// instance's active fill and stroke ([`InstanceArt::drawn`]). + drawn: bool, } impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each - /// object it visits inside `n` from the [`ArtWalk`] limit. + /// object it visits inside `n` from the [`ArtWalk`] limit. In drawn art, a symbol instance with + /// geometry effects of its own, and type whose own effects or fill and stroke effects (its own, + /// or those the outer instance adds) reshape it, are hit only where the art they draw is + /// ([`own_effects_art`]), and an instance whose fill or stroke has geometry effects that reshape + /// its art (its own, or those the outer instance passes on) only where its art is drawn with + /// them ([`drawn_instance_hit`]); not anywhere in their bounds. With Type Object Selection by + /// Path Only ([`HitOptions::type_path_only`]), type is still picked by its type path. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { let placed = self.art.place(n, whole)?; let _charged = ArtWalk::charge(); + // Type Object Selection by Path Only picks type by its type path, whatever its effects draw. + let type_path = opt.type_path_only && matches!(placed.kind, NodeKind::Text(_)); + if self.drawn && !type_path { + if let Some(art) = own_effects_art(&placed, self.symbols, opt.outline) { + let _off = DrawnOff::set(); + let _art_only = ArtOnly::set(); + return hit_any(&art, self.p, opt, self.symbols); + } + if reshapes_instance_art(&placed, self.symbols, opt.outline) { + return drawn_instance_hit(&placed, self.p, opt, self.symbols); + } + } hit_any(&placed, self.p, opt, self.symbols) } @@ -1858,7 +1942,26 @@ fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) ARTS_WALKED.with(|c| c.set(c.get() + 1)); let opt = HitOptions { clip_outlines: false, ..opt }; let _art_only = ArtOnly::set(); - FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false) + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: false }.find(&art.art, &mut vec![], None, false) +} + +/// What a click at `p` hits of symbol instance `n`, an object of another instance's drawn art, +/// where the canvas draws `n`'s art with the geometry effects of `n`'s active fill and stroke +/// ([`InstanceArt::drawn`]): each object of that art where it is drawn, paths, images and type +/// alike, and not anywhere in `n`'s box. Locked and template objects of the art count, as in +/// [`instance_art_hit`]. `None` for an instance of a missing symbol, of a symbol that holds an +/// instance of itself or nests too deep ([`SymbolBoxes::art`]), of art past the 9-slice object +/// limit ([`InstanceArt::of`]), and once the click has visited as many objects of symbol art as +/// [`ArtWalk`] allows. +fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None }; + if symbols.art(symbol).is_none() || ArtWalk::used_up() { + return None; + } + let art = InstanceArt::drawn(symbols.document(), n, false)?; + let opt = HitOptions { clip_outlines: false, ..opt }; + let _art_only = ArtOnly::set(); + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false) } thread_local! { @@ -2008,15 +2111,18 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< /// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the /// outlines are cut to the bounds of the plain clipping paths, without their live effects, as /// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around -/// the object leave no region. +/// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's +/// active fill and stroke, as [`symbol_part_at`] does. pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { - let art = InstanceArt::of(doc, inst)?; - let part = crate::symbol_overrides::part(&art.art, path)?; let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; + let part = crate::symbol_overrides::part(&art.art, path)?; + let symbols = doc.kept_symbol_boxes(); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; let mut n = &art.art; + let mut mask = false; for &i in path { let children = n.children()?; whole = art.whole(n, whole); @@ -2028,9 +2134,12 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], op let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; limit = within; } + mask = i == 0 && n.clips(); n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, whole)?, limit, outline, &mut out); + // A clipping path is picked by its own geometry ([`FindPart::find`]), and outlined so. + let placed = art.place(part, whole)?; + plain(mask, || outline_within(&placed, &symbols, limit, outline, &mut out)); Some(out) } @@ -2052,9 +2161,37 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option, outline: bool, out: &mut BezPath) { +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. A path +/// or compound path whose geometry effects reshape it is outlined as the art they draw +/// ([`drawn_art`]), a symbol instance with geometry effects of its own and type whose effects +/// reshape it as the art they draw ([`own_effects_art`]), and a symbol instance whose fill or stroke effects reshape its art as that +/// art drawn with them ([`InstanceArt::drawn`]), as [`FindPart`] tests them, except with `outline` +/// and while a [`DrawnOff`] guard lives. +fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && let Some(art) = drawn_art(symbols, n, outline) + { + let _off = DrawnOff::set(); + art.iter().for_each(|a| outline_within(a, symbols, limit, outline, out)); + return; + } + if let Some(art) = own_effects_art(n, symbols, outline) { + let _off = DrawnOff::set(); + outline_within(&art, symbols, limit, outline, out); + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && reshapes_instance_art(n, symbols, outline) + { + if symbols.art(symbol).is_some() + && let Some(art) = InstanceArt::drawn(symbols.document(), n, false) + && let Some(placed) = art.place(&art.art, None) + { + outline_within(&placed, symbols, limit, outline, out); + } + return; + } if let Some(pd) = n.path_data() { match limit { Some(r) => push_cut(out, &pd.to_bezpath(), r), @@ -2066,16 +2203,26 @@ fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPat { out.extend(b.to_path(0.1)); } + // An image is also outlined where its own fills and strokes paint with their effects, as + // [`hit_leaf`] picks it there ([`image_paint`]). + if !outline && matches!(n.kind, NodeKind::Image(_)) { + for (bp, ..) in image_paint(Some(symbols.document()), n).iter() { + match limit { + Some(r) => push_cut(out, bp, r), + None => out.extend(bp.iter()), + } + } + } let Some(children) = n.children() else { return }; let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { let Some(inner) = limit_within(first, limit, outline) else { return }; - rest.iter().for_each(|c| outline_within(c, inner, outline, out)); + rest.iter().for_each(|c| outline_within(c, symbols, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, outline, out)); + children.iter().for_each(|c| outline_within(c, symbols, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..46fd9344e2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -89,9 +89,9 @@ pub use raster::{ without_geometry, }; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies, - has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, - instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, + SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, + has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, + has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index a57c2085f6..c7ab85e7a8 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -388,11 +388,23 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, true); +} + +/// [`add_instance_row_effects`] for Direct Selection's parts of a symbol instance's art: live +/// objects (blends, envelopes, repeats) are left as they are, without the effects, so that every +/// object keeps its place in the art and the child indices that pick a part still lead to it. +pub fn add_instance_row_effects_to_parts(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, false); +} + +/// [`add_instance_row_effects`], evaluating live objects in the art only with `live`. +fn add_instance_rows(doc: Option<&Document>, n: &Node, art: &mut Node, live: bool) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); if !fill.is_empty() || !stroke.is_empty() { - add_row_effects(doc, symbol, art, &fill, &stroke); + add_row_effects(doc, symbol, art, &fill, &stroke, live); } } @@ -413,8 +425,9 @@ fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) { +/// instance of the symbol named `outer`. Without `live`, live objects are left as they are +/// ([`add_instance_row_effects_to_parts`]). +fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect], live: bool) { match &n.kind { NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return, NodeKind::SymbolInstance { symbol, .. } => { @@ -425,7 +438,12 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef } return; } - _ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n), + _ if vectorcraft_doc::live::is_live(n) => { + if !live { + return; + } + *n = evaluated(doc, n); + } _ => {} } let takes = |i: &AppearanceItem| { @@ -445,7 +463,7 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef let clips = n.clips(); for (i, c) in n.children_mut().into_iter().flatten().enumerate() { if !(clips && i == 0) { - add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke); + add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke, live); } } } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..0272e8fb76 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,9 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Direct Selection picks and outlines the parts of a dynamic symbol's instance where the + // effects of the instance's fill and stroke draw them. + vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks and marquees find paths, compound paths, groups and layers where their geometry diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e136d9f45b..6f4973cd15 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -587,6 +587,160 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() { assert_eq!(pixel(&s, 80, 30), BLUE); } +/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect` +/// with `params`. +fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) { + s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap(); + let row = node(s, inst).appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap(); + s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap(); +} + +/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`. +fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option> { + let doc = &s.doc().unwrap().doc; + vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt) +} + +/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it. +fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect { + use vectorcraft_geom::kurbo::Shape; + let doc = &s.doc().unwrap().doc; + let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap(); + outline.bounding_box() +} + +/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art +/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer +/// paints, and outlines it there; Outline view still takes the plain shapes. +#[test] +fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The squares are drawn at x 110..150 and 160..200. + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn"); + assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn"); + assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}"); + direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default()); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.objects, [inst]); + assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it"); + + // A stroke effect: Offset Path moves the first square's stroke out to x = 0. + let mut s = session(); + let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0)); + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap(); + let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10})); + assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape"); + let b = part_outline_box(&s, inst, &[0]); + assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}"); + + // A symbol instance in the art takes the effect too: it is picked and outlined where its art is + // drawn, not in its box. The fill effect moves its square; its image has no fill and stays. + let mut s = session(); + let a = square(&mut s, 10.0); + place_image(&mut s); + let img = top(&s); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap()); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn"); + assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}"); + + // A nested instance with a geometry effect of its own is picked where both effects draw it. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}"); + + // Type with a fill of its own in the art is picked and outlined where the fill effect draws its + // glyphs, not in its own bounds. + let mut s = session(); + let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap()); + s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap(); + let plain = { + let doc = &s.doc().unwrap().doc; + doc.node(t).unwrap().geometric_bounds().unwrap() + }; + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The type's own color still paints the glyph in place; the new fill paints it 100 pt right. + let drawn = part_outline_box(&s, inst, &[0]); + assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}"); + let glyph = drawn.x1 - 100.0 - drawn.x0; + let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0); + assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph"); + assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph"); + let by_path = HitOptions { type_path_only: true, ..opt }; + assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline"); + + // A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the + // outer fill effect draws its art. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box"); + + // An image whose fill has Convert to Shape is picked and outlined where the instance's fill + // effect moves that shape. + let mut s = session(); + place_image(&mut s); + let img = top(&s); + let frame = node(&s, img).geometric_bounds().unwrap(); + s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap(); + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap(); + let b = square(&mut s, 200.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + let c = frame.center(); + assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn"); + let o = part_outline_box(&s, inst, &[0]); + assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}"); +} + +/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its +/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws. +#[test] +fn a_picked_clipping_path_is_outlined_by_its_own_geometry() { + let mut s = session(); + let content = square(&mut s, 20.0); + let clip = square(&mut s, 10.0); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap()); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}"); +} + #[test] fn a_drag_of_a_picked_object_moves_nothing_and_says_why() { let mut s = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..17eb1a0ee0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2102,6 +2102,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. + Direct Selection on a dynamic symbol's instance picks an object of the art where the geometry effects of the instance's fill and stroke draw it, not where the object's own shape no longer paints, and outlines it there. An instance nested in the art is picked and outlined where its reshaped art is drawn, and type with a fill or stroke of its own where its reshaped glyphs are drawn, not anywhere in their bounds; Type Object Selection by Path Only still picks type by its type path. An image is outlined where its own fills and strokes paint as well as by its frame. A clipping path is still picked and outlined by its own geometry. Outline view and layers with Preview off still take the plain shapes, and blends, envelopes and repeats in the art are picked without those effects. These are VectorCraft's own rules (engine `dynamic_symbols::direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it`, `a_picked_clipping_path_is_outlined_by_its_own_geometry`). Before, a part was picked and outlined at its plain shape only. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). From 29ddc57821b8d559b0de4f704e6e48b1df98980f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:45:27 -0800 Subject: [PATCH 038/145] Scripts: what a script's commands open or change gives later runs no file access The commands a script runs could read the files that the documents open at the run's start link to, and could read and write the files of every open document. Both lists were taken from the documents as they were, so a document a script opened, or a link or data set value a script added, widened what the next run could read, and a document opened from a linked file could be saved over that file in the next run. - DocState::by_script records what scripts' commands did to a document since the person last opened or saved it: opened it, or changed it or gave it another file, keeping the document, its file and the file it was read from as they were before. The script host notes it after every command, and a save the person makes from the document's current content clears it. Revert keeps it, and a recovery copy restores the document as one a script opened. - The gate's document files and the linked files are taken from each document as the person left it (DocState::as_person_left). A document a script opened gives neither, in that run or a later one. - This replaces the per-run record of paths read through the linked files and ScriptGate::keeping_linked_read_only. - docs/mcp.md and docs/target-app-parity.md describe the rule. --- crates/engine/src/cmd/fileio/save.rs | 6 +- crates/engine/src/cmd/links.rs | 3 +- crates/engine/src/cmd/recovery.rs | 9 ++ crates/engine/src/doc_state.rs | 44 ++++++++ crates/engine/src/file_access.rs | 135 +++++-------------------- crates/engine/src/script/files.rs | 9 +- crates/engine/src/script/mod.rs | 44 ++++---- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_run.rs | 110 ++++++++++++++++++++ docs/mcp.md | 15 +-- docs/target-app-parity.md | 2 +- 11 files changed, 238 insertions(+), 141 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..7585861e9b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1148,10 +1148,14 @@ impl SaveJob { /// Once written: Save and Save As (except to a template) make the file `st`'s own: path, /// title, format, options, and the snapshot as the saved state (edits made since the job was /// made keep the document modified; changes that are not edits to save don't, - /// [`DocState::same_content`]). + /// [`DocState::same_content`]). Saved outside a command a script runs, from the document's + /// content as it is now, the document is as the person left it ([`DocState::by_script`]). pub fn finish(self, st: &mut DocState) { let retargets = self.plan.retargets(); if let (true, Some(path)) = (retargets, self.plan.path) { + if !crate::file_access::in_script_command() && st.same_content(&self.source) { + st.by_script = None; + } st.path = Some(path); st.format = self.plan.format.id; st.save_options = self.plan.options; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9f1e7c3d79..3950d39f0b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -410,7 +410,8 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { /// finds each linked image's and placed document's file from `base` and from no document (as /// output reads them, [`full_linked_images`]), the plate files of their own of images placed from /// DCS files, and the image files its data sets name. The commands a script runs may read these -/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +/// for the documents open when the run began, as the person left them +/// ([`crate::file_access::ScriptGate::linked`]). pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..de64441623 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -874,6 +874,11 @@ struct Meta { /// images were kept apart: the document entry holds them). #[serde(skip_serializing_if = "BTreeMap::is_empty")] images: BTreeMap, + /// A command a script ran opened or changed the document since the person last saved it + /// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as + /// one a script opened. + #[serde(skip_serializing_if = "std::ops::Not::not")] + by_script: bool, } /// One of a copy's images: its entry in the copy's area. @@ -1195,6 +1200,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec, file: &str) -> R st.imported_from = meta.imported_from.clone(); st.import_losses = meta.import_losses.clone(); st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft"); + if meta.by_script { + st.by_script = Some(crate::doc_state::ByScript::Opened); + } if let Some(pdf) = meta.native_pdf_compatible { st.save_options.insert("pdfCompatible".into(), json!(pdf)); } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..d57173ae76 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -128,6 +128,11 @@ pub struct DocState { /// paths the document links to are looked at within them later too, when the Links panel /// asks about a link outside any caller's scope. pub opened_by: Option>, + /// What the commands scripts ran did to the document since the person last opened or saved it: + /// `None` when they did nothing. The commands a script runs read and write the document's file, + /// and read the files it links to, only as the person left them ([`DocState::as_person_left`]). + /// Not saved. + pub(crate) by_script: Option, /// The live-effect plug-in stages deferred while the document is drawn on screen, and the time /// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved. pub plugin_effects: vectorcraft_plugins::deferred::Deferrals, @@ -146,6 +151,17 @@ pub struct DocState { pub(crate) inline_resolved: Option, } +/// What the commands scripts ran did to an open document since the person last opened or saved it +/// ([`DocState::by_script`]). +#[derive(Clone, Debug)] +pub(crate) enum ByScript { + /// A command a script ran opened it (or made it). + Opened, + /// A command a script ran changed it or gave it another file: the document, its file and the + /// file it was read from as they were before the first such command. + Changed { doc: Arc, path: Option, links_from: Option }, +} + /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that /// was measured. #[derive(Clone, Debug, Default)] @@ -360,6 +376,7 @@ impl DocState { links_from: None, last_perspective: None, opened_by: file_access::current(), + by_script: None, empty_artboards: Default::default(), plugin_effects: Default::default(), art_to_fit: Default::default(), @@ -367,6 +384,33 @@ impl DocState { inline_resolved: None, } } + + /// The document, its file and the file it was read from as the person last left them, for the + /// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command + /// opened. + pub(crate) fn as_person_left(&self) -> Option<(&Arc, Option<&str>, Option<&str>)> { + match &self.by_script { + None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())), + Some(ByScript::Opened) => None, + Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())), + } + } + + /// Notes what a command a script ran did to the document, which was `was` (the document, its + /// file and the file it was read from) before the command ran, or not open when `was` is + /// `None`. The first change is kept until the person saves the document. + pub(crate) fn note_script_command(&mut self, was: Option<(&Arc, &Option, &Option)>) { + if self.by_script.is_some() { + return; + } + let Some((doc, path, links_from)) = was else { + self.by_script = Some(ByScript::Opened); + return; + }; + if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from { + self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() }); + } + } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, /// so a menu that asks on every frame measures it once, and a change of the selection or the view /// keeps the answer. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 890be26fb9..c20e37b58e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -28,7 +28,7 @@ //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the //! files of the open documents, and for reading, the files the documents open when the run began -//! link to. +//! link to, each as the person last left the document. use std::cell::RefCell; use std::ffi::OsString; @@ -277,33 +277,31 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. Reading, and only reading, the files the documents open when the -/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as -/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and +/// only reading, the files the documents link to as the person left them when the run began is +/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by +/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, - /// The paths of the open documents' files, as the documents hold them. + /// The paths of the open documents' files, as the documents held them when the person last + /// opened or saved them. A document a script's command opened has none here. pub(crate) documents: Vec, - /// The files the documents open when the run began link to: readable, not writable. + /// The files the documents link to as the person left them when the run began: readable, not + /// writable. pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } /// The files the commands a script runs may only read because the documents open when the run -/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. -/// Clones share the record of those paths. +/// began link to them as the person left them ([`ScriptGate::linked`]). #[derive(Clone, Debug, Default)] pub(crate) struct LinkedFiles { /// The real paths of the files, as they were when the run's first command was run, sorted. A /// path that leads to another file now is not one of them. files: Arc<[PathBuf]>, - /// The paths, absolute as a document holds its file, that a command read only because they led - /// to one of `files` when it read them. A document opened from one of them stays read-only for - /// the rest of the run, wherever the path leads later. - read: Arc>>, } impl LinkedFiles { @@ -311,20 +309,6 @@ impl LinkedFiles { fn has(&self, real: &Path) -> bool { self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() } - - /// The paths read through the files alone so far. - fn read_paths(&self) -> Vec { - self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() - } - - /// Notes that `path` was read through the files alone. - fn note_read(&self, path: &str) { - let path = crate::cmd::fileio::absolute_path(path); - let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !read.contains(&path) { - read.push(path); - } - } } impl ScriptGate { @@ -340,23 +324,7 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - LinkedFiles { files: real.into(), read: Arc::default() } - } - - /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless - /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. A document counts as one when a command - /// read its file through the linked files alone, whatever the path leads to or the script may - /// read now, and when its file is one of them now that nothing else lets the gate read. - pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; - let (linked, read) = (self.linked.clone(), self.linked.read_paths()); - let only_linked = |d: &String| { - let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) - }; - self.documents.retain(|d| before.contains(d) || !only_linked(d)); - self + LinkedFiles { files: real.into() } } /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every @@ -380,14 +348,7 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { - return true; - } - let linked = matches!(access, Access::Read) && self.linked.has(&real); - if linked { - self.linked.note_read(path); - } - linked + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -431,6 +392,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> { GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) } +/// Whether this thread runs a command a script runs ([`with_script_gate`]). +pub(crate) fn in_script_command() -> bool { + GATE.with(|g| g.borrow().is_some()) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -1072,59 +1038,10 @@ mod tests { let _ = std::fs::remove_dir_all(base); } - /// A document the run opened from a file only the linked files let it read is not written - /// through the document-file rule; one open when the run began, and one in the script's own - /// places, still is. + /// A path read through the linked files gives no access to the file it leads to after it is + /// pointed elsewhere by a link in one of its folders. #[test] - fn a_document_opened_from_a_linked_file_stays_read_only() { - let (base, _) = folders("linked-doc"); - let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); - let gate = ScriptGate { - read: ScriptScope::of_folder(&base.join("in")), - write: ScriptScope::of_folder(&base.join("in")), - documents: vec![secret.clone(), own.clone()], - linked: ScriptGate::real_files([secret.clone(), own.clone()]), - also: None, - }; - let opened = gate.clone().keeping_linked_read_only(&[]); - assert!(opened.check(&secret, Access::Read).is_ok()); - assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); - assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); - let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); - assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone stays - /// read-only after the script is allowed to read that file's folder, and after the file is - /// replaced by another one. - #[test] - fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { - let (base, _) = folders("linked-granted"); - let secret = s(base.join("outside/secret.svg")); - let linked = ScriptGate::real_files([secret.clone()]); - let gate = |read: &str, documents: Vec| ScriptGate { - read: ScriptScope::of_folder(&base.join(read)), - write: ScriptScope::default(), - documents, - linked: linked.clone(), - also: None, - }; - assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); - let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(granted.check(&secret, Access::Read).is_ok()); - assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); - std::fs::remove_file(&secret).unwrap(); - std::fs::write(&secret, "").unwrap(); - let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone gives no - /// access to the file its path leads to after the path is pointed elsewhere by a link. - #[test] - fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() { let (base, _) = folders("linked-redirected"); #[cfg(unix)] let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); @@ -1144,20 +1061,18 @@ mod tests { return; } let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); - let linked = ScriptGate::real_files([doc.clone()]); - let gate = |documents: Vec| ScriptGate { + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), - documents, - linked: linked.clone(), + documents: vec![], + linked: ScriptGate::real_files([doc.clone()]), also: None, }; - assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file"); std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); assert!(made(&second, &via)); - let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { - assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + assert!(gate.check(path, access).is_err(), "{path} {access:?}"); } let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2c63c9cd66..d0f54bfe32 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,8 +54,9 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that -//! the documents open when the run began link to, as those links were then. +//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read +//! the files that the documents open when the run began link to, as the person last left those +//! documents and as those links led then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -455,8 +456,8 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, the files of the - /// open documents, `documents`, and the files it may only read because the documents open when + /// The gate for a command the script runs: the places it reads and writes now, the files the + /// person gave the open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9e3419d10d..6d7181d283 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,15 +799,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, - /// The documents open when the run began, each with its own file and the file it was read from - /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// The documents open when the run began as the person last left them, each with its own file + /// and the file it was read from ([`crate::DocState::as_person_left`], + /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files /// they link to from them ([`Host::linked`]). run_docs: RefCell>, - /// The files of the documents open when the run began - /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). - opened_before: Vec, - /// The files the documents open when the run began link to, and the paths the run's commands - /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + /// The files the documents open when the run began link to as the person left them + /// ([`crate::file_access::ScriptGate::linked`]). linked: std::cell::OnceCell, } @@ -816,9 +814,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began - /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. Every command's gate shares the - /// record of the paths read through them. + /// link to them, found once, from those documents as the person left them: a link a script's + /// command added or changed, in this run or an earlier one, and a document it opened, give it + /// no file to read. fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { @@ -1269,12 +1267,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files; - // it also reads the files the documents open when the run began link to, and does not write a document - // the run opened from one of those. - let linked = host.linked(); - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); + // The command reads and writes only where the script's own files may, and the files the person gave + // the open documents; it also reads the files the documents open when the run began link to, as the + // person left them. A document a script's command opened gives it no file. + let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); + let gate = host.disk.borrow().gate(documents, host.linked()); + let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); + // What the command opened, changed or gave another file is not as the person left it. + for st in &mut s.docs { + let prior = was.iter().find(|(uid, _)| *uid == st.uid); + st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from))); + } + drop(was); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { @@ -2074,8 +2079,13 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), - opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + run_docs: RefCell::new( + self.docs + .iter() + .filter_map(DocState::as_person_left) + .map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string))) + .collect(), + ), linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..d5d71c9704 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -402,6 +402,8 @@ impl Session { st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; + // What scripts' commands did to the document stays until the person saves it. + st.by_script = old.by_script.clone(); st.save_options = old.save_options.clone(); // The remembered artboard pick follows the artboards it named when the file read back has // the artboards the document had at the save, in the same order and with the same ids (a diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d0a9723f3e..a57d3be23b 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -479,6 +479,116 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { let _ = std::fs::remove_dir_all(&dir); } +/// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate +/// refuses a file. +fn tried(id: &str, params: &str) -> String { + format!( + "try {{ vc.run('{id}', {params}); vc.log('ok'); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) +} + +/// A document a script opened from a file that only a link let it read is not written in that run +/// or a later one, and gives a later run no access to its file once no document the person left +/// links to it. +#[test] +fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { + use crate::tests_links::{RED, open, place, png, save, session, write}; + let art = fresh_folder("gate-linked-runs").join("art"); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &inner); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &inner); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + open(&mut s, &poster); + let bytes = std::fs::read(&inner).unwrap(); + let opened = run(&mut s, &[tried("document.open", &format!("{{path: {inner:?}}}")), tried("document.save", "{}")].concat()).unwrap(); + assert_eq!(opened["log"], json!(["ok", "denied"]), "{opened}"); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(inner.as_str())); + let mut log = vec![]; + let next = run(&mut s, &tried("document.save", "{}")).unwrap(); + log.push(next["log"][0].clone()); + // The person closes the document that links to it. + let at = s.documents().iter().position(|d| d.path.as_deref() == Some(poster.as_str())).unwrap(); + assert!(s.set_active(at)); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let later = run(&mut s, &tried("file.place", &format!("{{path: {inner:?}, at: [200, 150]}}"))).unwrap(); + log.push(later["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); + assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); + let _ = std::fs::remove_dir_all(art.parent().unwrap()); +} + +/// A data set value a script gives a document, and a document a script opens, let no later run +/// read the files they name; once the person saves the document, the files its data sets name are +/// read again. +#[test] +fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { + use crate::tests_links::{RED, place, png, session, write}; + let dir = fresh_folder("gate-linked-later"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, other, mine) = (p(art.join("secret.png")), p(inside.join("other.vectorcraft")), p(inside.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &secret); + s.execute("document.save", &json!({"path": other})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let read_secret = tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}")); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + let mut log = vec![]; + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + let own = s.active_index().unwrap(); + let r = run_allowed(&mut s, &inside, &tried("document.open", &format!("{{path: {other:?}}}"))).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "{r}"); + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "after a data set value, then after a document a script opened"); + assert!(s.set_active(own)); + s.execute("document.save", &json!({"path": mine})).unwrap(); + let saved = run(&mut s, &read_secret).unwrap(); + assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A save the person started before a script's command changed the document, and that finishes +/// after it, does not let a later run read the files that change names. +#[test] +fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::tests_links::{RED, png, session, write}; + let dir = fresh_folder("gate-linked-save"); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, mine) = (p(dir.join("secret.png")), p(dir.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + let uid = s.doc().unwrap().uid; + let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": mine})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + job.write(|_, _| Ok(())).unwrap(); + job.complete(&mut s, uid); + let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6c0de9e418..62978099cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3022,13 +3022,14 @@ VectorCraft writes files by these rules of its own: its `Folder.temp` and `Folder.userData` and to the open documents' own files. Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, - save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its - path leads to another file later, the document does not let the script read or write that file. The files are - taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points - elsewhere, and a document it opens, does not let it read any file it could not read before. The automation - read roots still apply. + save, print or package of them includes the linked art. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. + Both rules count each document as the person last opened or saved it. A document that a script's command opened, + in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. + A document opened from a linked file is therefore not saved over that file unless the script may write there. A + link or data set value that a script's command adds or changes, and a file that a script's command saves a document + to, give later runs no access either. The person's next save of the document ends this. The automation read roots + still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 37b87a97d9..4c24e057f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 8e6f06574f212f3315bf1fa7aef6149a3f61d6e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:49:58 -0800 Subject: [PATCH 039/145] Paths: a closed path starts at a kept anchor at its old start When the refit keeps an anchor at a closed path's old start, Simplify and Smooth now start the path at that anchor, even where a segment of the refit crosses the path at the same point. Before, a crossing segment that came first could be split there instead, adding an anchor and changing the segment the path starts along. --- crates/pathops/src/edit.rs | 57 +++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index dd5d84ebe7..c5a340365a 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -174,10 +174,11 @@ fn earliest_nearest(candidates: impl IntoIterator, or best.map(|(.., x)| x) } -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is -/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// The closed `sp` started at the point on it nearest `start`: at an anchor within [`START_SNAP`] of +/// `start` when it has one, even where a segment crosses the path there, otherwise at the anchor at +/// that point or at a new anchor split into the segment there, which leaves the outline as it is. Of +/// points equally near `start`, the one earliest along `orig` (the path before it was refitted) from +/// its first anchor is used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { let n = sp.anchors.len(); @@ -194,6 +195,14 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within return (sp, None, 0); } let within = within.start.min(n)..within.end.min(n); + // The anchors of the segments `within`: each one's first, and the last one's end. + let anchors = || (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); + // An anchor within [`START_SNAP`] of `start` starts the path, before any segment through there. + let snapped = if within.is_empty() { None } else { earliest_nearest(anchors().filter(|(d, ..)| *d <= START_SNAP), orig) }; + if let Some(first) = snapped { + sp.anchors.rotate_left(first); + return (sp, None, first); + } let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); @@ -219,9 +228,7 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - // The anchors of the segments `within`: each one's first, and the last one's end. - let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); - (earliest_nearest(near, orig).unwrap_or(0), None) + (earliest_nearest(anchors(), orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); (sp, cut, first) @@ -1600,6 +1607,42 @@ mod tests { assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); } + /// A closed polyline from its start at (0, 0) up to (0, 10) whose diagonal from (-20, -20) to + /// (20, 20) crosses it at that start, with two anchors on the diagonal that a refit drops. + fn crossing_at_start() -> SubPath { + let pts = [(0, 0), (0, 10), (40, 10), (40, -20), (-20, -20), (-10, -10), (10, 10), (20, 20), (20, 30), (-10, 30), (-10, 0)]; + SubPath::polyline(&pts.map(|(x, y)| Point::new(f64::from(x), f64::from(y))), true) + } + + /// A refitted run that keeps an anchor at the old start of a closed path starts the path at that + /// anchor, though a segment of the run that crosses the path there comes first in the run. + #[test] + fn a_run_that_keeps_the_start_anchor_starts_there() { + let path = PathData::new(vec![crossing_at_start()]); + let picked: BTreeSet<(usize, usize)> = [0, 4, 5, 6, 7, 8, 9, 10].into_iter().map(|s| (0, s)).collect(); + let opts = SimplifyOptions { tolerance: 0.01, corner_angle_deg: 1.0, straight_lines: true, ..SimplifyOptions::default() }; + let got = &simplify_part(&path, &picked, &opts).path.subpaths[0]; + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(ps.len(), 9, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + assert_eq!(ps.iter().filter(|&&p| p == Point::ZERO).count(), 1, "{ps:?}"); + } + + /// The whole closed path refitted keeps its start anchor first when a segment of the refit + /// crosses the path there. + #[test] + fn a_refit_that_keeps_the_start_anchor_starts_there() { + let sp = crossing_at_start(); + let mut fit = sp.clone(); + fit.anchors.retain(|a| ![Point::new(-10.0, -10.0), Point::new(10.0, 10.0)].contains(&a.p)); + fit.anchors.rotate_left(4); + let n = fit.anchors.len(); + let (got, cut, _) = keep_start(fit, &sp, 0..n); + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(cut, None, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test] From a45e2dc710c28b9e81e54fe0adc904e2c8824876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:57:54 -0800 Subject: [PATCH 040/145] Scripts: a linked file in the settings folder is not read through the linked list The read check for the files the documents link to now applies the script scope's fence of the folder that holds the settings, as the script's own reads do. A file in a place left open inside that folder is still read. --- crates/engine/src/file_access.rs | 35 ++++++++++++++++++++++++++++++-- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c20e37b58e..50b7f725fa 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -348,7 +348,8 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) + let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -663,7 +664,13 @@ impl ScriptScope { pub(crate) fn allows(&self, real: &Path) -> bool { (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) || self.roots.iter().any(|r| inside(real, r))) - && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) + && !self.keeps_out(real) + } + + /// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place + /// left open there? + fn keeps_out(&self, real: &Path) -> bool { + self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// The scope of a script run from a file in the folder whose real path, with its links already @@ -1038,6 +1045,30 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A linked file in a folder the script's scope keeps out, such as the settings folder, is not + /// read through the gate; one in a place left open there is. + #[test] + fn a_gate_reads_no_linked_file_in_a_folder_kept_out() { + let (base, _) = folders("linked-fenced"); + let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg")); + std::fs::create_dir_all(base.join("outside/open")).unwrap(); + std::fs::write(&kept, "").unwrap(); + std::fs::write(&open, "").unwrap(); + let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap(); + let mut read = ScriptScope::of_folder(&base.join("in")); + read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]); + let gate = ScriptGate { + read, + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]), + also: None, + }; + assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out"); + assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open"); + let _ = std::fs::remove_dir_all(base); + } + /// A path read through the linked files gives no access to the file it leads to after it is /// pointed elsewhere by a link in one of its folders. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 62978099cb..9967588b8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,8 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. + first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds + the settings is not read this way. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c24e057f2..8af5ee8f9e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From b06bccfaebab42ace4c09bd1f3a889df455c14fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:30:44 -0800 Subject: [PATCH 041/145] Symbols: picking and outlining a dynamic instance's part stays within one object limit Outlining a part of a dynamic symbol's instance expanded every nested instance whose fill or stroke effects reshape its art, at every level, with no limit, so art that nests many such instances a few levels deep took work that grew with each level. A part pick charged each object it tested but copied each nested instance's art before charging anything for it. The part outline now shares the object limit a click has, and each object it outlines takes one object of it. The art of a nested instance takes its size from the limit before it is copied, and the art an object's own effects draw takes its size once evaluated; nothing more is copied or evaluated once the limit is used up. The art of the instance itself is charged by its walk, as before. --- crates/doc/src/hit.rs | 73 ++++++++++++++++++++++++++----- crates/doc/src/hit/tests.rs | 85 +++++++++++++++++++++++++++++++++++-- 2 files changed, 145 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6286597882..6320be059d 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1609,7 +1609,17 @@ fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option /// is tested here. Never with `outline`, where the canvas draws no effects, nor while a /// [`DrawnOff`] guard lives. fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { - !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && !image_paint(Some(symbols.document()), n).is_empty() + !outline + && !DRAWN_OFF.get() + && matches!(n.kind, NodeKind::SymbolInstance { .. }) + && n.appearance.items.iter().any(|i| !i.effects().is_empty()) + && !image_paint(Some(symbols.document()), n).is_empty() +} + +/// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what +/// testing or outlining it takes from the [`ArtWalk`] limit. +fn walk_size(n: &Node) -> u64 { + u64::try_from(n.count_with_masks()).unwrap_or(u64::MAX) } /// The art that symbol instance `n` draws with a visible effect of its own, the effects of its @@ -1617,17 +1627,28 @@ fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool /// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]). /// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or /// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect -/// changes what it draws. +/// changes what it draws. Evaluating the art is work that walking it does not count, so the art +/// takes its objects from the [`ArtWalk`] limit of the click or outline under way, and the walk of +/// it takes them again. Once the limit is used up, the result is `Some` of an empty group, which +/// hits and outlines nothing, and no more art is evaluated. fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option { let has = match n.kind { NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible), NodeKind::Text(_) => has_own_effects(n), _ => false, }; - if outline || DRAWN_OFF.get() || !has { + if outline || DRAWN_OFF.get() || !has || DRAWN_ART.get().is_none() { return None; } - DRAWN_ART.get()?(symbols, n) + let nothing = || Some(Node::group(n.id, vec![])); + if ArtWalk::used_up() { + return nothing(); + } + let art = DRAWN_ART.get()?(symbols, n)?; + if !ArtWalk::take(walk_size(&art)) { + return nothing(); + } + Some(art) } /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path @@ -1744,12 +1765,36 @@ impl<'a> InstanceArt<'a> { /// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects. fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option { let mut art = Self::of(doc, inst)?; + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); if !outline && let Some(f) = INSTANCE_ROW_ART.get() { f(Some(doc), inst, &mut art.art); } Some(art) } + /// [`Self::drawn`] for symbol instance `inst` in the art of another instance, outside Outline. + /// Copying the art and adding the effects to it is work that walking it does not count, so the + /// art takes as many objects as placing it makes ([`Self::size`]) from the [`ArtWalk`] limit of + /// the click or outline under way before it is copied, as the marquee takes the art it places, + /// and the walk of it takes its objects again. `None` once fewer are left. + fn nested(doc: &'a Document, inst: &Node) -> Option { + if ArtWalk::used_up() { + return None; + } + let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; + let boxes = doc.symbol_boxes().quick(); + let source = boxes.symbol_art(symbol)?; + let size = match boxes.slice_map(symbol, *xf) { + Some(m) => m.most_placed_with(source, &boxes), + None => walk_size(source), + }; + if !ArtWalk::take(size) { + return None; + } + Self::drawn(doc, inst, false) + } + /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides @@ -1958,7 +2003,7 @@ fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes if symbols.art(symbol).is_none() || ArtWalk::used_up() { return None; } - let art = InstanceArt::drawn(symbols.document(), n, false)?; + let art = InstanceArt::nested(symbols.document(), n)?; let opt = HitOptions { clip_outlines: false, ..opt }; let _art_only = ArtOnly::set(); FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false) @@ -2112,8 +2157,11 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< /// outlines are cut to the bounds of the plain clipping paths, without their live effects, as /// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around /// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's -/// active fill and stroke, as [`symbol_part_at`] does. +/// active fill and stroke, as [`symbol_part_at`] does. Outlining visits at most as many objects of +/// symbol art as one click does ([`ArtWalk`]), the art of the instances nested in the part included, +/// and leaves out what is past that limit. pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { + let _walk = ArtWalk::open(); let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let art = InstanceArt::drawn(doc, inst, outline)?; let part = crate::symbol_overrides::part(&art.art, path)?; @@ -2164,11 +2212,16 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; + if !ArtWalk::take(1) { + return; + } if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && let Some(art) = drawn_art(symbols, n, outline) { @@ -2185,7 +2238,7 @@ fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: && reshapes_instance_art(n, symbols, outline) { if symbols.art(symbol).is_some() - && let Some(art) = InstanceArt::drawn(symbols.document(), n, false) + && let Some(art) = InstanceArt::nested(symbols.document(), n) && let Some(placed) = art.place(&art.art, None) { outline_within(&placed, symbols, limit, outline, out); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index ad037931a0..7c704511c3 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1324,11 +1324,11 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } -/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to -/// (320, 20); nothing for anything else. +/// For instances of the symbols whose names start with "Painted", a fill that paints the square +/// from (300, 0) to (320, 20); nothing for anything else. fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { match &n.kind { - NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + NodeKind::SymbolInstance { symbol, .. } if symbol.starts_with("Painted") => { let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] } @@ -3041,6 +3041,85 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); } +/// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect: +/// [`painted_far_away`] gives it shapes when the name starts with "Painted", so a part pick and a +/// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]). +fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc { + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + Arc::new(n) +} + +/// Five levels of symbols: "Painted 0" is a 1 pt square, and each level above holds 8 instances +/// of the level below whose fills have a geometry effect. Returns the id of an instance of +/// "Painted 4" on the layer. +fn painted_chain(d: &mut Document) -> NodeId { + let l = d.layers[0].id; + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted 0".into(), art: Arc::new(dot) }); + for level in 1..5 { + let members = (0..8).map(|_| painted_instance_of(d, &format!("Painted {}", level - 1))).collect(); + group_symbol(d, &format!("Painted {level}"), members); + } + let inst = instance_of(d, "Painted 4"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + id +} + +/// The outline of a part of a dynamic symbol's instance visits at most the art walk's limit of +/// objects, though the part is an instance whose art, drawn with its fill's effects, nests +/// instances 3 levels deep, 8 at each level. Within the limit every square is outlined. +#[test] +fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let n = d.node(id).unwrap(); + let squares = |o: &BezPath| o.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count(); + // Part [0] is an instance of "Painted 3": 8 × 8 × 8 squares. + assert_eq!(squares(&symbol_part_outline(&d, n, &[0]).unwrap()), 512, "within the limit"); + let (outline, _, arts) = with_art_limit(100, || symbol_part_outline(&d, n, &[0]).unwrap()); + assert!(squares(&outline) < 100, "{} squares outlined", squares(&outline)); + assert!(arts < 100, "{arts} instances' art walked"); +} + +/// A part pick in a dynamic symbol's instance visits at most the art walk's limit of objects of +/// nested instances whose art, drawn with their fills' effects, is walked: in a chain of nested +/// instances, and in instances whose clip groups the click misses, where only the clip group +/// itself is tested. A click on the clipped art of a nested instance is still found. +#[test] +fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let opt = HitOptions::default(); + let (hit, _, arts) = with_art_limit(100, || symbol_part_at(&d, d.node(id).unwrap(), Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 40, "chain: {arts} instances' art walked"); + // 30 instances of a clip group whose 10 pt clipping path holds 40 squares: 42 objects each. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut members = vec![Arc::new(mask)]; + members.extend((0..40).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())))); + let mut clip = Node::group(d.alloc_id(), members); + clip.set_clips(true); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted clip".into(), art: Arc::new(clip) }); + let members = (0..30).map(|_| painted_instance_of(&mut d, "Painted clip")).collect(); + group_symbol(&mut d, "Clips", members); + let inst = instance_of(&mut d, "Clips"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let n = d.node(id).unwrap(); + let (hit, _, arts) = with_art_limit(300, || symbol_part_at(&d, n, Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 8, "clip groups: {arts} instances' art walked"); + assert_eq!(with_art_limit(300, || symbol_part_at(&d, n, Point::new(2.0, 2.0), opt)).0, Some(vec![29]), "the clipped art"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. From f54afb117b27335113b0dcdb0985b901f014965c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:49:04 -0800 Subject: [PATCH 042/145] Smooth: a drag that would not make a path smoother leaves it as it was path.smoothRegion kept every changed result. A drag along the top of a clean ellipse split it from 4 to 5 anchors without smoothing it, took away its Live Shape and added an undo step, and a third drag left it with 7 anchors and about 20% more turning. Each subpath's result is now measured against the subpath at one spacing: how much it turns along its length, with each turn at an anchor counted twice, and how much it bends. The result is kept only when it turns no more than a thousandth more and has fewer anchors, turns less or bends less. Otherwise the subpath stays as it was; a path with no kept subpath keeps its Live Shape, is left out of ids and the counts, and a call that keeps nothing adds no undo step. The measure and the thresholds are VectorCraft's own. Three tests that dragged over a convex curve with nothing to smooth now drag over a sharp peak or crest, so they still test the reach search and a closed path of two anchors. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/smooth.rs | 114 +++++++++++++++++++++++- crates/engine/src/tests/draw2.rs | 90 ++++++++++++++++--- docs/mcp.md | 8 ++ docs/target-app-parity.md | 1 + 5 files changed, 203 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..d56c4be6b4 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}", has_selection, smooth_region ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..cca6cbbb2c 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -730,6 +730,89 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool out } +/// Most pieces [`roughness`] cuts one curved segment into. +const ROUGHNESS_SEGMENT_PIECES: usize = 1024; + +/// Most pieces [`roughness`] cuts the curved segments of one subpath into, shared equally by them. +const ROUGHNESS_PIECES: usize = 1 << 18; + +/// How rough the subpath `sp` is, measured along the lines between points on each curved segment +/// no more than `step` apart along its control polygon (at least 4 and at most +/// [`ROUGHNESS_SEGMENT_PIECES`] pieces a segment, fewer on a subpath of very many segments): how +/// much it turns along its length in radians, from the direction each segment leaves its first anchor +/// along to the one it arrives at its last anchor along, with each turn at an anchor counted twice; +/// and how much it bends, the sum of each turn between two pieces squared over their mean length. +/// `None` when a point or a turn is not a number. +fn roughness(sp: &SubPath, step: f64) -> Option<(f64, f64)> { + let segments = sp.segment_count(); + let most = (ROUGHNESS_PIECES / segments.max(1)).clamp(4, ROUGHNESS_SEGMENT_PIECES); + // The directions along the path, each with whether it leaves an anchor, and the pieces' vectors. + let (mut dirs, mut pieces): (Vec<(kurbo::Vec2, bool)>, Vec) = (vec![], vec![]); + for i in 0..segments { + let c = sp.segment(i); + if sp.segment_is_line(i) { + dirs.push((c.p3 - c.p0, true)); + pieces.push(c.p3 - c.p0); + continue; + } + let leave = [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let arrive = [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let len = polygon_len(c); + let k = if step > 0.0 && step.is_finite() && len.is_finite() { (len / step).ceil().clamp(4.0, most as f64) as usize } else { most }; + dirs.push((leave, true)); + let mut at = c.p0; + for j in 1..=k { + let q = if j == k { c.p3 } else { c.eval(j as f64 / k as f64) }; + dirs.push((q - at, false)); + pieces.push(q - at); + at = q; + } + dirs.push((arrive, false)); + } + // A direction of no length is left out; the turn at an anchor is then taken at the next one. + let mut kept: Vec<(kurbo::Vec2, bool)> = Vec::with_capacity(dirs.len()); + let mut at_anchor = false; + for (d, anchor) in dirs { + at_anchor |= anchor; + if d.hypot() > 1e-12 { + kept.push((d, at_anchor)); + at_anchor = false; + } + } + pieces.retain(|d| d.hypot() > 1e-12); + let turn = |u: kurbo::Vec2, v: kurbo::Vec2| u.cross(v).atan2(u.dot(v)).abs(); + let pairs = |n: usize| if sp.closed { n } else { n.saturating_sub(1) }; + let mut turning = 0.0; + for j in 0..pairs(kept.len()) { + let (u, (v, anchor)) = (kept[j].0, kept[(j + 1) % kept.len()]); + turning += if anchor { 2.0 } else { 1.0 } * turn(u, v); + } + let mut bending = 0.0; + for j in 0..pairs(pieces.len()) { + let (u, v) = (pieces[j], pieces[(j + 1) % pieces.len()]); + bending += turn(u, v).powi(2) / (0.5 * (u.hypot() + v.hypot())); + } + (turning.is_finite() && bending.is_finite()).then_some((turning, bending)) +} + +/// Whether the Smooth tool keeps `new`, the subpath `old` smoothed with the reach `radius` +/// (VectorCraft's own rule). Both are measured with [`roughness`] at one spacing, an eighth of the +/// reach or 1/512 of the diagonal of `old`'s control points, whichever is smaller. `new` must turn +/// no more than a thousandth more than `old` (counting a turn of less than 1 radian as 1), and it +/// must have fewer anchors, turn less, or bend more than a ten-thousandth less. A result that would +/// leave the path rougher, or that adds anchors or changes the path without smoothing it, is not +/// kept. +fn smoother(old: &SubPath, new: &SubPath, radius: f64) -> bool { + let size = old.anchors.iter().fold(None, |r: Option, a| { + let b = Rect::from_points(a.p, a.h_in).union_pt(a.h_out); + Some(r.map_or(b, |r| r.union(b))) + }); + let step = (radius / 8.0).min(size.map_or(0.0, |r| r.width().hypot(r.height()) / 512.0)); + let (Some((t0, b0)), Some((t1, b1))) = (roughness(old, step), roughness(new, step)) else { return false }; + let scale = t0.max(1.0); + t1 <= t0 + 1e-3 * scale && (new.anchors.len() < old.anchors.len() || t0 - t1 >= 1e-6 * scale || b0 - b1 > 1e-4 * b0) +} + pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.smoothRegion"; let pts = points_param(p, "points", C)?; @@ -759,7 +842,10 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { _ => sp.clone(), }) .collect(); - if changed { + // A subpath whose result would not be smoother stays as it was. + let subs: Vec = + subs.into_iter().zip(&pd.subpaths).map(|(n, sp)| if n == *sp || smoother(sp, &n, radius) { n } else { sp.clone() }).collect(); + if changed && subs != pd.subpaths { let np = PathData::new(subs); before += pd.anchor_count(); after += np.anchor_count(); @@ -1246,4 +1332,30 @@ mod tests { assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); } + + /// `sp` scaled by `k` about the origin. + fn scaled(sp: &SubPath, k: f64) -> SubPath { + let at = |p: Point| Point::new(p.x * k, p.y * k); + SubPath::new(sp.anchors.iter().map(|a| Anchor { p: at(a.p), h_in: at(a.h_in), h_out: at(a.h_out), ..*a }).collect::>(), sp.closed) + } + + /// The Smooth tool keeps a result that turns less, and not one that turns more with as many + /// anchors, one that adds an anchor and keeps the outline, or one that is the path itself, at + /// any size. + #[test] + fn the_smooth_tool_keeps_only_a_smoother_result() { + let round = ring(); + let mut bumped = ring(); + bumped.anchors[1].translate(kurbo::Vec2::new(0.0, -25.0)); + let split = start_nearest(ring(), round.segment(0).eval(0.3), &round); + assert_eq!(split.anchors.len(), 5, "{split:?}"); + for k in [1e-3, 1.0, 1e3] { + let (round, bumped, split) = (scaled(&round, k), scaled(&bumped, k), scaled(&split, k)); + let reach = 12.0 * k; + assert!(smoother(&bumped, &round, reach), "at {k}x a bump smoothed away is kept"); + assert!(!smoother(&round, &bumped, reach), "at {k}x a bump added is not kept"); + assert!(!smoother(&round, &split, reach), "at {k}x an anchor added on the outline is not kept"); + assert!(!smoother(&round, &round.clone(), reach), "at {k}x the same path is not kept"); + } + } } diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..3e2a319c01 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2306,13 +2306,13 @@ fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() { assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path"); } -/// A click on a curve 100,000 pt long, between the places a fixed number of samples along it would -/// look at, still finds the curve under it. +/// A click on a curve 100,000 pt long, at the sharp crest in its middle and between the places a +/// fixed number of samples along it would look at, still finds the curve under it. #[test] fn a_smooth_drag_finds_a_very_long_curve_under_it() { use kurbo::ParamCurve; let mut s = session(); - let anchors = [json!({"x": 0.0, "y": 0.0, "out": [30000.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, -9000.0]})]; + let anchors = [json!({"x": 0.0, "y": 0.0, "out": [99800.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [200.0, -9000.0]})]; let id = smooth_test_path(&mut s, &anchors, false); let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0); assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0])); @@ -2329,9 +2329,9 @@ fn a_smooth_click_that_only_just_reaches_a_segment_smooths_it() { assert_ne!(path(&s, id), before); } -/// A drag that runs along a very long curve first and then crosses a second curve away from its -/// middle, with both of its anchors out of reach, smooths the second curve too: each curve in reach -/// gets the same share of the search, so the long one does not use it all. +/// A drag that runs along a very long curve first and then crosses a second curve at the peak in +/// its middle, with both of its anchors out of reach, smooths the second curve too: each curve in +/// reach gets the same share of the search, so the long one does not use it all. #[test] fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { let mut s = session(); @@ -2342,7 +2342,7 @@ fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { ); let next = smooth_test_path( &mut s, - &[json!({"x": 100100.0, "y": -100.0, "out": [100130.0, 200.0]}), json!({"x": 100100.0, "y": 900.0, "in": [100130.0, 600.0]})], + &[json!({"x": 100050.0, "y": 75.0, "out": [100150.0, -25.0]}), json!({"x": 100250.0, "y": 75.0, "in": [100150.0, -25.0]})], false, ); s.execute("select.set", &json!({"ids": [long.0, next.0]})).unwrap(); @@ -2372,14 +2372,14 @@ fn smoothing_smooths_an_open_two_anchor_path() { assert_eq!((a[0].p, a[a.len() - 1].p), (Point::new(100.0, 200.0), Point::new(200.0, 200.0)), "the ends stay"); } -/// A closed path of two anchors is smoothed along the middle of one side and stays closed. +/// A closed path of two anchors is smoothed at the peak in the middle of one side and stays closed. #[test] fn smoothing_smooths_a_closed_two_anchor_path() { use kurbo::ParamCurve; let mut s = session(); let anchors = [ - json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [100.0, 200.0]}), - json!({"x": 300.0, "y": 300.0, "in": [300.0, 160.0], "out": [300.0, 440.0]}), + json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [200.0, 150.0]}), + json!({"x": 300.0, "y": 300.0, "in": [200.0, 150.0], "out": [300.0, 440.0]}), ]; let id = smooth_test_path(&mut s, &anchors, true); let before = path(&s, id); @@ -2405,6 +2405,76 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() { assert_eq!(path(&s, line), before); } +/// Whether `id` is still a Live Shape. +fn smooth_test_live(s: &Session, id: NodeId) -> bool { + matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { live: Some(_), .. }) +} + +/// Smooth drags over a clean ellipse, again and again and at any Fidelity, change nothing: the +/// ellipse has nothing to smooth, so no pass adds anchors to it, leaves it rougher, adds an undo step +/// or takes its Live Shape away. Each returns no ids and counts of 0, as a drag that reaches no path +/// does. +#[test] +fn smooth_drags_over_a_clean_ellipse_change_nothing() { + for fidelity in [0.05, 0.5, 2.5, 10.0] { + let mut s = session(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = path(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 240.0).iter().map(|p| json!([p.x, p.y])).collect(); + for pass in 1..=4 { + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap(); + assert_eq!(r, json!({"ids": [], "before": 0, "after": 0}), "Fidelity {fidelity}, pass {pass}"); + assert_eq!(path(&s, id), before, "Fidelity {fidelity}, pass {pass}: {} anchors", path(&s, id).anchor_count()); + assert!(smooth_test_live(&s, id), "Fidelity {fidelity}, pass {pass}: still a Live Shape"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "Fidelity {fidelity}, pass {pass}: no undo step"); + } + } +} + +/// A Smooth drag over a clean ellipse and a jagged line selected together smooths the line only: the +/// result names the line and counts its anchors alone, the ellipse stays as it was and a Live Shape, +/// and one undo brings the line back. +#[test] +fn a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line() { + let mut s = session(); + let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=50).map(|i| json!({"x": 320.0 + 5.0 * f64::from(i), "y": 100.0 + smooth_noise(&mut seed)})).collect(); + let line = smooth_test_path(&mut s, &anchors, false); + s.execute("select.set", &json!({"ids": [ellipse.0, line.0]})).unwrap(); + let (oval, jagged) = (path(&s, ellipse), path(&s, line)); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 580.0).iter().map(|p| json!([p.x, p.y])).collect(); + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap(); + let smoothed = path(&s, line); + assert!(smoothed.anchor_count() < jagged.anchor_count(), "the line is smoothed: {} anchors", smoothed.anchor_count()); + assert_eq!(r, json!({"ids": [line.0], "before": jagged.anchor_count(), "after": smoothed.anchor_count()})); + assert_eq!(path(&s, ellipse), oval); + assert!(smooth_test_live(&s, ellipse), "the ellipse is still a Live Shape"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, line), path(&s, ellipse)), (jagged, oval)); +} + +/// A Smooth drag at the lowest Fidelity still smooths a jagged line: it turns less and has fewer +/// anchors after each of three drags. +#[test] +fn a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line() { + let mut s = session(); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let pts: Vec<_> = smooth_drag_along(200.0, 90.0, 410.0).iter().map(|p| json!([p.x, p.y])).collect(); + let mut before = path(&s, id); + for pass in 1..=3 { + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.05})).unwrap(); + let after = path(&s, id); + assert!(after.anchor_count() < before.anchor_count(), "pass {pass}: {} -> {} anchors", before.anchor_count(), after.anchor_count()); + assert!(total_turning(&after) < total_turning(&before), "pass {pass}: turning {} -> {}", total_turning(&before), total_turning(&after)); + before = after; + } +} + /// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open /// path's first and last anchors. fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..27b2b0d236 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7171,6 +7171,14 @@ own, and the corner keeps its place and the directions the path arrives and leav `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. +`path.smoothRegion` keeps a subpath's result only when it is smoother. Measured along lines between points no more +than an eighth of `radius` apart (or 1/512 of the subpath's size when that is smaller), the result must turn no more +than a thousandth more than the subpath did, with each turn at an anchor counted twice, and it must have fewer +anchors, turn less, or bend more than a ten-thousandth less (the sum of each turn squared over the length it is taken +over). Any other result is dropped and the subpath stays as it was. A path none of whose subpaths is kept stays a Live +Shape if it was one, is left out of `ids` and is not counted in `before` or `after`. The measure and both thresholds +are VectorCraft's own. + In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..e5658b152a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1547,6 +1547,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `brush.freehand` refuses a `brush` that names no brush in the document, or is not a string, and a `style` other than "pencil" or "brush", with an error and no change or undo step, instead of drawing the plain path; the Paintbrush skips a chosen brush that has since been deleted (engine tests `brush_freehand_refuses_a_brush_or_style_it_cannot_use` and `paintbrush_tool_skips_a_deleted_brush`). A `brush.freehand` stroke and its brush are one undo step, so one Undo removes both. A `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled "pencil" path while the stroke is None) is refused with "cannot apply brush ``: path has no stroke", and a key the command does not take with "unknown parameter", with no change or undo step; the no-stroke refusal is VectorCraft's own rule (engine tests `brush_freehand_direct_call_has_one_undo_step`, `brush_freehand_refuses_a_brush_on_a_path_without_a_stroke` and `brush_freehand_refuses_unknown_keys`). Each drag of the Smooth tool smooths the stretch of a selected path in its reach along its length before refitting it within Fidelity, so a wobble wider than Fidelity is smoothed out and another drag over the same place smooths it further, as [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) describes (`path.smoothRegion`). The smoothing spread (a third of the reach) and the rule that each refit stays within twice the distance the smoothing moved the path, so repeated drags do not drift from it, are VectorCraft's own. A drag over the whole of a closed path smooths it across its first anchor too, so a bump there is smoothed like any other and no corner is left; Object › Path › Smooth smooths a closed path across its first anchor the same way. + A Smooth drag changes a path only when the result is smoother, which [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=79) gives as the aim of the tool's Fidelity: the result turns no more than a thousandth more along its length than the path did, with each turn at an anchor counted twice, and it has fewer anchors, turns less or bends less. Otherwise the path stays as it was and keeps its Live Shape, and the drag adds no undo step, so drags over a clean ellipse no longer add anchors to it or leave it rougher. A drag that only splits a convex curve into more anchors without smoothing it now leaves the path as it was. The measure and its thresholds are VectorCraft's own (engine tests `smooth_drags_over_a_clean_ellipse_change_nothing`, `a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line`, `a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line` and `cmd::draw2::smooth::tests::the_smooth_tool_keeps_only_a_smoother_result`). When a Smooth tool drag reaches the first anchor of a closed path, the smoothed path starts at its point nearest where that anchor was: at an anchor there, or at a new anchor split into the curve without changing its outline. Dashes and type on the path start from that point. A drag that does not reach the first anchor leaves it first. This is VectorCraft's own rule (engine tests `smoothing_over_a_closed_paths_first_anchor_keeps_its_start` and `smoothing_a_whole_closed_path_with_a_spike_keeps_its_start`). The Smooth tool shows the Not Allowed cursor while no path is selected that it can act on (an editable path, not a guide, with three or more anchors on one of its subpaths or two anchors joined by a curve), and the release of a drag then sends no command and changes nothing; [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) has the path selected first. A selected path anywhere on the canvas gives the Smooth cursor wherever the pointer is. The Pencil with Alt key toggles to Smooth Tool on and the Blob Brush show Not Allowed the same way when Alt gives them the Smooth tool; the Paintbrush keeps its closing cursor, since its release with Alt closes the stroke. Use Precise Cursors leaves Not Allowed as it is. This cursor rule is VectorCraft's own (tools `smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `borrowed_smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `smoothing_release_sends_nothing_without_a_selected_path_to_smooth`; engine `use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer`). When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). From 53098c9f9fc520c5891ee6e6b9dd8ce180a449d9 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 19:56:32 +0800 Subject: [PATCH 043/145] Align craft-libs pins for EPS RunLength decoding --- Cargo.lock | 93 ++++++++++++++++----------------- Cargo.toml | 68 ++++++++++++------------ apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- 4 files changed, 80 insertions(+), 85 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8995c19ea..9facb25052 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9b28b56bc7207ef7ce806f37df72cb94c0ad5c37#9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "md-5", "rayon", @@ -1030,12 +1030,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "rayon", ] @@ -1043,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,17 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" - -[[package]] -name = "craft-eps" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1084,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "gif", ] @@ -1097,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", ] @@ -1105,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1128,7 +1123,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1155,7 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "thiserror 2.0.21", ] @@ -1163,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1174,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "egui", "serde", @@ -1184,7 +1179,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1196,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "encoding_rs", "image", @@ -1207,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "chrono", "craft-codepage", @@ -1217,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1228,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1237,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-winprint-gdi", "log", @@ -1251,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1262,9 +1257,9 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)", + "craft-eps", "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", @@ -1276,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "encoding_rs", "flate2", @@ -1287,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fax", "hayro-ccitt", @@ -1298,7 +1293,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1319,7 +1314,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "serde", "thiserror 2.0.21", @@ -1328,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1349,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "chrono", "dunce", @@ -1376,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", "serde", @@ -1387,7 +1382,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "js-sys", "serde_json", @@ -1398,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "egui", "objc2 0.6.5", @@ -1417,7 +1412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2524,7 +2519,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli", "hayro-postscript", @@ -2533,7 +2528,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2551,7 +2546,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2569,12 +2564,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", "hayro-ccitt", @@ -3374,7 +3369,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3483,7 +3478,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6876,7 +6871,7 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-eps", "craft-image-codecs", "craft-pdf", "craft-ps", diff --git a/Cargo.toml b/Cargo.toml index 9c933c3549..182dfa732d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,43 +11,43 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -190,13 +190,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..4b4641d11f 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 07695b034c..8342873fe7 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } From 2fcee167569dbbef78cee791ab510a11e7e97cb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:08:23 -0800 Subject: [PATCH 044/145] Scripts: a recovery copy keeps a script's change through a crash A recovery copy's details now say that a script's command changed the document before the new document entry is written, and a restore writes a copy's details before its document entry in the new area. A crash between the two writes no longer restores a script-changed document without that record, so a later run cannot read the files its links name. The docs say that a linked file in one of the script's own places inside the settings folder is still read. --- crates/engine/src/cmd/recovery.rs | 13 ++++++--- crates/engine/src/tests/recovery.rs | 42 +++++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index de64441623..fe6deb0b4b 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1038,10 +1038,13 @@ impl RecoveryJob { let meta_name = format!("{}{META_EXT}", self.file); // The details name the images, so a crash between writing the document and its details // would pair the new document with the old copy's images: when the new document has - // images the old details don't name, they name both until the new document is in. - let old = read_meta(store, &self.file).images; - if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { + // images the old details don't name, they name both until the new document is in. Likewise + // when a script's command changed the document since the old details: they say so first. + let old_meta = read_meta(store, &self.file); + let old = old_meta.images; + if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { let mut both = meta.clone(); + both.by_script |= old_meta.by_script; for (k, r) in old { both.images.entry(k).or_insert(r); } @@ -1503,8 +1506,10 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R for (blob, data) in &blobs { store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?; } - store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; + // The details go first: a crash in between leaves no copy without them (a copy is its + // document entry), and the copy in the old area stays whole. store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?; + store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; } // The copy's images in its old area go with the area, once no copy is left there. store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index eed8801efc..613a453d47 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1714,3 +1714,45 @@ fn a_crash_between_a_copys_document_and_its_details_keeps_every_image() { assert_eq!(images_of(&s), images, "first copy: {first}"); } } + +/// A crash between writing a copy's document and its details, after a script's command changed +/// the document since the last copy, restores the document as one a script opened. +#[test] +fn a_crash_between_a_copys_document_and_its_details_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + s.execute("file.recovery.save", &json!({})).unwrap(); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert!(s.doc().unwrap().by_script.is_some(), "the script's command changed the document"); + let doc = vectorcraft_doc::Document::clone(&s.doc().unwrap().doc); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + assert!(s.execute("file.recovery.save", &json!({})).is_err(), "the details weren't written"); + drop(s); + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + let count = |d: &vectorcraft_doc::Document| d.layers.iter().map(|l| l.count()).sum::(); + assert_eq!(count(&s.doc().unwrap().doc), count(&doc), "the new document is in"); + assert!(s.doc().unwrap().by_script.is_some(), "restored as a document a script opened"); +} + +/// A crash while a restore moves a copy into the app's own area leaves no copy that a later +/// restore opens without its details: a script's change is kept. +#[test] +fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + let _ = s.execute("file.recovery.restore", &json!({})); + drop(s); + let mut s = relaunch(&store); + assert!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()) >= 1); + for st in s.documents().iter().filter(|st| st.recovered) { + assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9967588b8f..fede932de6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3024,7 +3024,7 @@ VectorCraft writes files by these rules of its own: (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds - the settings is not read this way. + the settings is not read this way unless it lies in one of the script's own places inside that folder. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8af5ee8f9e..b00ba51236 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 05d5befece364ebcc9bf19df82fdf59f745db832 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:09:01 -0800 Subject: [PATCH 045/145] Symbols: Direct Selection follows a nested instance of a clip group moved by the instance's fill effects A symbol instance nested in a dynamic symbol's art was picked and outlined where its art is drawn only when the shapes its fill and stroke paint were non-empty. Those shapes leave out clip groups and type, so a nested instance whose art is a clip group was picked at its plain place although the canvas draws its members moved by the outer instance's fill or stroke effects. The test is now whether the nested instance's active fill or stroke has a visible geometry effect, which the engine registers with set_instance_reshapes. Picks and outlines no longer evaluate those shapes for each nested instance they visit. --- crates/doc/src/hit.rs | 29 ++++++++++++++++------ crates/doc/src/hit/tests.rs | 10 +++++++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/dynamic_symbols.rs | 26 +++++++++++++++++++ 4 files changed, 58 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6320be059d..6507112c24 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -131,6 +131,20 @@ pub fn set_instance_row_art(f: InstanceRowArt) { let _ = INSTANCE_ROW_ART.set(f); } +/// Does a symbol instance's active fill or stroke carry a visible geometry effect, which the art it +/// places takes on each of its fills and strokes ([`set_instance_row_art`])? Effects are classified +/// above this crate, so the engine registers one with [`set_instance_reshapes`]. +pub type InstanceReshapes = fn(&Node) -> bool; + +static INSTANCE_RESHAPES: OnceLock = OnceLock::new(); + +/// Register how Direct Selection tells whether a symbol instance's fill or stroke effects reshape +/// its art (the first registration stays). +pub fn set_instance_reshapes(f: InstanceReshapes) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_RESHAPES.set(f); +} + /// The shapes that [`ImagePaint`] gives for one object. type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; @@ -1603,17 +1617,18 @@ fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option }) } -/// Is `n` a symbol instance whose active fill or stroke has geometry effects that reshape the art -/// it draws ([`image_paint`])? Callers ask [`own_effects_art`] first, which takes an instance whose +/// Is `n` a symbol instance whose active fill or stroke has a visible geometry effect, which +/// reshapes the art it draws ([`set_instance_reshapes`])? This holds whatever that art is, clip +/// groups and type included. Callers ask [`own_effects_art`] first, which takes an instance whose /// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow) /// is tested here. Never with `outline`, where the canvas draws no effects, nor while a -/// [`DrawnOff`] guard lives. -fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { +/// [`DrawnOff`] guard lives, nor while nothing is registered. +fn reshapes_instance_art(n: &Node, outline: bool) -> bool { !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.appearance.items.iter().any(|i| !i.effects().is_empty()) - && !image_paint(Some(symbols.document()), n).is_empty() + && INSTANCE_RESHAPES.get().is_some_and(|f| f(n)) } /// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what @@ -1905,7 +1920,7 @@ impl FindPart<'_> { let _art_only = ArtOnly::set(); return hit_any(&art, self.p, opt, self.symbols); } - if reshapes_instance_art(&placed, self.symbols, opt.outline) { + if reshapes_instance_art(&placed, opt.outline) { return drawn_instance_hit(&placed, self.p, opt, self.symbols); } } @@ -2235,7 +2250,7 @@ fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: return; } if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && reshapes_instance_art(n, symbols, outline) + && reshapes_instance_art(n, outline) { if symbols.art(symbol).is_some() && let Some(art) = InstanceArt::nested(symbols.document(), n) diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 7c704511c3..ea38de43b8 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -3041,8 +3041,14 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); } +/// Whether a symbol instance's fill or stroke effects reshape its art, for these tests: when +/// [`painted_far_away`] gives it shapes. +fn reshapes_when_painted(n: &Node) -> bool { + !painted_far_away(None, n).is_empty() +} + /// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect: -/// [`painted_far_away`] gives it shapes when the name starts with "Painted", so a part pick and a +/// [`reshapes_when_painted`] holds for it when the name starts with "Painted", so a part pick and a /// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]). fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc { let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); @@ -3075,6 +3081,7 @@ fn painted_chain(d: &mut Document) -> NodeId { #[test] fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); let mut d = Document::new(600.0, 400.0); let id = painted_chain(&mut d); let n = d.node(id).unwrap(); @@ -3093,6 +3100,7 @@ fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { #[test] fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() { set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); let mut d = Document::new(600.0, 400.0); let id = painted_chain(&mut d); let opt = HitOptions::default(); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 0272e8fb76..1685adc40f 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -27,6 +27,7 @@ impl Session { // Direct Selection picks and outlines the parts of a dynamic symbol's instance where the // effects of the instance's fill and stroke draw them. vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts); + vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks and marquees find paths, compound paths, groups and layers where their geometry diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index 6f4973cd15..fc1305a0a7 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -741,6 +741,32 @@ fn a_picked_clipping_path_is_outlined_by_its_own_geometry() { assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}"); } +/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's +/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it +/// where its member is drawn, not where the member's own shape is, and outlines it there. +#[test] +fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let content = square(&mut s, 10.0); + let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap()); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap()); + let b = square(&mut s, 160.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The member is drawn at x 110..150, inside the clipping path. + assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved"); + assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place"); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place"); + let o = part_outline_box(&s, inst, &[0]); + assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}"); +} + #[test] fn a_drag_of_a_picked_object_moves_nothing_and_says_why() { let mut s = session(); From 8b6204ee62f47bd1c798766d63ff6ceb6e7c3721 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 20:15:12 +0800 Subject: [PATCH 046/145] Keep the PDF dependency check aligned with the shared pin --- xtask/src/pdf_deps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 29a599c400..ca613bfa13 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; +const REV: &str = "b674d91fbe1d8b4a98654de201a21aeda33910e6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 4077615205826c7a2dbe53bf39bfc1ce63123171 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 20:17:44 +0800 Subject: [PATCH 047/145] Credit Terra854 in VectorCraft About --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 420177ffb6..f3930b2a8a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -225,3 +225,6 @@ sync_github_name = true real_name = "Hassan Nawaz Khan" display_name = "Hassan Nawaz Khan" sync_github_name = false + +[people.Terra854] +display_name = "Terra854" From d54cbce77875bcc4ccfeccf3941f771514b3e744 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:52:00 -0800 Subject: [PATCH 048/145] Symbols: a part's outline leaves out hidden art of instances nested in it The outline of a dynamic instance's part walked the art of an instance nested in the part, drawn with that instance's fill and stroke effects, and outlined its hidden objects as well. It now skips a hidden object and what it holds, as the part pick does. --- crates/doc/src/hit.rs | 4 ++-- crates/doc/src/hit/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6507112c24..93a13296de 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2231,10 +2231,10 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option