From 426ea942687c8005305ffaf2fd3defc7c1e97bdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:32:07 -0800 Subject: [PATCH 001/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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/126] 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 011b6fb0e7e7e6bbe08f80ef4a2397109dd54993 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:56:06 -0800 Subject: [PATCH 015/126] 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 b919dbd66f7a70dd0b56c5dca81d37d83ea32963 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:41:45 -0800 Subject: [PATCH 016/126] 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 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 NgrdLn{x8z|zX1V{_bdPa delta 29513 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 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 5a2eae86a7fb9bae02a417dfb81bc4215bef5199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:43:00 -0800 Subject: [PATCH 017/126] 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 018/126] 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 9758ece7efae40e3b7cd20e537b3abb8f4962afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:07:34 -0800 Subject: [PATCH 019/126] 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 4367a9ce68b9b1cba848dd06c1a573369096ac8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:22:58 -0800 Subject: [PATCH 020/126] 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 bab25d02487c087f44d143d0000ea33fb0de2660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:32:08 -0800 Subject: [PATCH 021/126] 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 2d6b8680e6de3d718dadd704b09a7d34130a966d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:01:48 -0800 Subject: [PATCH 022/126] 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 29ddc57821b8d559b0de4f704e6e48b1df98980f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:45:27 -0800 Subject: [PATCH 023/126] 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 a45e2dc710c28b9e81e54fe0adc904e2c8824876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:57:54 -0800 Subject: [PATCH 024/126] 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 f54afb117b27335113b0dcdb0985b901f014965c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:49:04 -0800 Subject: [PATCH 025/126] 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 026/126] 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 027/126] 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 8b6204ee62f47bd1c798766d63ff6ceb6e7c3721 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 20:15:12 +0800 Subject: [PATCH 028/126] 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 029/126] 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 162a3c10651c6b6ea7cbe79810fada2224ce9602 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:00:00 -0800 Subject: [PATCH 030/126] Scripts: a recovery copy with unreadable details restores as a script's document A recovery copy whose details entry is missing or can't be parsed now restores as a document a script opened, and the details written for the moved copy say so, so a later restore does the same. A valid details entry without the script's mark still restores as the person left it. The script docs now say that a link does not let a command write the file it names: a linked file is written only where the script's write places or an open document's own file allow it. --- crates/engine/src/cmd/recovery.rs | 14 ++++++++++++-- crates/engine/src/tests/recovery.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index fe6deb0b4b..b81e0b3885 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1465,8 +1465,18 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) -> /// (for Save As) and format. The copy moves into this session's area (another crash keeps it). fn restore_one(s: &mut Session, store: &Arc, file: &str) -> Result { let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; - let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default(); - let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default(); + // A details entry that is missing or can't be parsed does not say whether a script's command + // changed the document: the copy restores as one a script opened, and the details written for + // it say so. + let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::(&b).ok().map(|m| (m, b))); + let (meta, meta_bytes) = match read { + Some(both) => both, + None => { + let meta = Meta { by_script: true, ..Meta::default() }; + let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?; + (meta, bytes) + } + }; let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?; // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 613a453d47..08a691f222 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1756,3 +1756,28 @@ fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); } } + +/// A copy whose details entry is missing or can't be parsed restores as a document a script +/// opened, and so does the copy that restore writes, after a later crash; a valid details entry +/// without the script's mark restores as the person left it. +#[test] +fn a_copy_without_readable_details_restores_as_a_scripts_document() { + let cases: [Option<&[u8]>; 3] = [Some(b"{ not json"), None, Some(b"{}")]; + for details in cases { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let entry = format!("{}.json", r["saved"][0]["file"].as_str().unwrap()); + drop(s); + match details { + Some(bytes) => store.write(&entry, bytes).unwrap(), + None => store.remove(&entry).unwrap(), + } + let by_script = details != Some(b"{}".as_slice()); + for round in 1..=2 { + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1, "{details:?}, restore {round}"); + assert_eq!(s.doc().unwrap().by_script.is_some(), by_script, "{details:?}, restore {round}"); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index fede932de6..1bd3166ee0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,9 +3020,10 @@ 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. The files are taken as those links led at the run's + Such a command also reads 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 link does not let the command write the file it names: it writes a linked file + only when the rule above lets it write there. 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 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, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b00ba51236..ce4d074eef 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 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: 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 as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); 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 80b089590b90c8df7fe4799bbaf7c8d20a339eec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:37:52 -0800 Subject: [PATCH 031/126] Smooth: the long-curve click test puts the crest between the places a fixed search would look at The click sat 0.15 pt from two of 1,024 evenly spaced places along the curve, so a fixed search found it too. The crest is now a cusp halfway between two of 65 evenly spaced places and more than the 12 pt reach from each, and the test checks that distance before the drag. --- crates/engine/src/tests/draw2.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 3e2a319c01..289a11f9cc 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2306,15 +2306,25 @@ 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, 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. +/// A click on the sharp crest of a curve 100,000 pt wide finds the curve under it, although the crest +/// lies halfway between two of 65 evenly spaced places along the curve and more than the click's 12 pt +/// reach from each of them, so a search that looked only at those places would miss 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": [99800.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [200.0, -9000.0]})]; + // The crest is a cusp at t0: the control points are chosen so that the curve's velocity is 0 there. + let (t0, wide): (f64, f64) = (32.5 / 64.0, 1.0e5); + let (d0, d2) = ((wide, -wide), (wide, wide)); + let d1 = ((1.0 - t0).powi(2) * d0.0 + t0 * t0 * d2.0, (1.0 - t0).powi(2) * d0.1 + t0 * t0 * d2.1); + let d1 = (-d1.0 / (2.0 * t0 * (1.0 - t0)), -d1.1 / (2.0 * t0 * (1.0 - t0))); + let (p1, p2) = (d0, (d0.0 + d1.0, d0.1 + d1.1)); + let anchors = [json!({"x": 0.0, "y": 0.0, "out": [p1.0, p1.1]}), json!({"x": p2.0 + d2.0, "y": p2.1 + d2.1, "in": [p2.0, p2.1]})]; 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); + let curve = path(&s, id).subpaths[0].segment(0); + let at = curve.eval(t0); + let nearest_place = (0..=64).map(|k| curve.eval(f64::from(k) / 64.0).distance(at)).fold(f64::INFINITY, f64::min); + assert!(nearest_place > 12.0, "the nearest of 65 places is {nearest_place} pt from the click"); assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0])); } From 217c80a5f1536ad75d279039537bb05e7f7f8cdb Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:17:26 +0800 Subject: [PATCH 032/126] deps: align the shared EPS prefix decoders --- Cargo.lock | 84 ++++++++++++++++----------------- Cargo.toml | 68 +++++++++++++------------- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 79 insertions(+), 79 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9facb25052..248a5e5880 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=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" 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=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" 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=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" 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=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "rayon", ] @@ -1043,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,12 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1079,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "gif", ] @@ -1092,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", ] @@ -1100,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1123,7 +1123,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-dds", "craft-jpeg", @@ -1150,7 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "thiserror 2.0.21", ] @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1169,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "egui", "serde", @@ -1179,7 +1179,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1191,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "encoding_rs", "image", @@ -1202,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "chrono", "craft-codepage", @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1223,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1232,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-winprint-gdi", "log", @@ -1246,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1257,7 +1257,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-eps", "flate2", @@ -1271,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "encoding_rs", "flate2", @@ -1282,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fax", "hayro-ccitt", @@ -1293,7 +1293,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1314,7 +1314,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1323,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1344,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "chrono", "dunce", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", "serde", @@ -1382,7 +1382,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "js-sys", "serde_json", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "egui", "objc2 0.6.5", @@ -1412,7 +1412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2519,7 +2519,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli", "hayro-postscript", @@ -2528,7 +2528,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2546,7 +2546,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2564,12 +2564,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", "hayro-ccitt", @@ -3369,7 +3369,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3478,7 +3478,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 182dfa732d..a5cbf0de78 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 = "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" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # WMF, EMF and EMF+ reader (craft-libs#778). -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"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", 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 = "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" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } 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 4b4641d11f..0d399f2fc3 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", 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 8342873fe7..6d606fbbe6 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index ca613bfa13..c6ad85638f 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 = "b674d91fbe1d8b4a98654de201a21aeda33910e6"; +const REV: &str = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From d2fdc9728a674754caab11ca664f6103344da859 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:13:22 -0800 Subject: [PATCH 033/126] Pen: Quick Pen marks an arc's center with a cross while the arc is drawn Wherever the Quick Pen tool shows an arc's protractor (while the arc is dragged, or as the piece the next click adds), it also draws a small cross at the arc's center, as the circle and three-point arc tools draw theirs. The cross is VectorCraft's own behavior. Adds a test for the cross while hovering and dragging. --- crates/engine/src/tests/quickpen.rs | 27 +++++++++++++++++++++++++++ crates/tools/src/quickpen.rs | 18 ++++++++++++------ docs/mcp.md | 3 ++- docs/target-app-parity.md | 1 + 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index c6174aa19f..3612dfe2b9 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -677,6 +677,33 @@ fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { } } +/// The two arms of a cross centered on `c` among the overlays. +fn crosses_at(o: &[Overlay], c: Point) -> usize { + o.iter().filter(|o| matches!(o, Overlay::Line { a, b, .. } if a.midpoint(*b).distance(c) < 1e-9)).count() +} + +/// While a half circle from (200, 100) to (300, 100) is dragged, or is the piece the next click +/// adds, the tool shows a cross at its center, (250, 100); while a line is dragged, it shows none. +#[test] +fn an_arc_shows_a_cross_at_its_center() { + let mut s = session(); + quick_pen(&mut s); + let center = pt(250.0, 100.0); + for (action, arms) in [("line", 0), ("sharpArc", 2)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "hovering, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "dragging, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 100.0), view()).unwrap(); + } +} + /// With Measurement Labels on, hovering after the path's last point shows the distance label /// beside the pointer; with them off, no label shows. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index d542af832c..6b6a56b408 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -15,12 +15,13 @@ //! //! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a //! protractor around the arc's center: a tick across its circle every 15° from where the arc -//! starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its -//! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides -//! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies -//! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither -//! the grid nor pixels snap drawn points. A sharp-corner arc sweeps its arc size, so its end is not -//! snapped to a tick. Shift does not constrain Quick Pen points, so it does not change the snapping. +//! starts, a longer one every 90°, and one where it ends, with a small cross at the center. The +//! piece the next click adds shows its protractor only while the Pen tool's rubber band preference +//! shows that piece. With Smart Guides on, the end of a continuous arc goes onto the nearest tick +//! of that protractor when the tick lies within the snapping tolerance of the pointer, no other +//! Smart Guide snaps the point, and neither the grid nor pixels snap drawn points. A sharp-corner +//! arc sweeps its arc size, so its end is not snapped to a tick. Shift does not constrain Quick Pen +//! points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -49,6 +50,8 @@ pub const MAX_TURN: f64 = 359.0; pub const TICK_STEP: f64 = 15.0; /// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. const TICK_PX: f64 = 4.0; +/// Half the length (screen points) of each arm of the cross at an arc's center. +const CROSS_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight @@ -824,6 +827,9 @@ impl Tool for QuickPenTool { }; if let Some(arc) = arc { o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); + let (c, arm) = (arc.center, cx.tol(CROSS_PX)); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: FEEDBACK, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } if self.press.is_none() && let Some(h) = end.or(self.hover) diff --git a/docs/mcp.md b/docs/mcp.md index 65383caa1b..c5659c8b5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7335,7 +7335,8 @@ that piece. With Smart Guides on, the end of a continuous arc snaps onto the nea circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The -protractor, its 15° step and the tick snapping are VectorCraft's own behavior. +protractor, its 15° step and the tick snapping are VectorCraft's own behavior. A small cross marks the arc's center +wherever the protractor shows; the cross is VectorCraft's own behavior too. Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 581f72bb0f..fb125077f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,6 +643,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From 20425b6914113ec7d59bdfd0562ee8b480a3f036 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:09:35 -0800 Subject: [PATCH 034/126] Pen: Quick Pen snaps no first continuous arc to a tick and hides a stale hover A continuous arc that starts a path has no direction to follow and sweeps the arc size, as a sharp-corner arc does. Moving its end onto a protractor tick put the end on a circle the drawn arc does not follow, so `tick_end` now gives no tick for it. The hover keeps the snap settings it was made with (`SnapSettings` in guides/snap.rs: the window, zoom, snapping options, tolerances, Alignment Guides and construction angles). After one of them changes under a still pointer, the hover's rubber band, protractor, distance label and Smart Guides are hidden until the pointer moves, also through a press, so the preview shows no point that a click would not place. A press also drops the hover, so after a click puts an arc's end on a tick no preview runs from that end back to the pointer. While the pointer hovers, the tool asks the canvas to hover it again when the view, the document or the selection changes (`wants_rehover`). --- crates/engine/src/tests/quickpen.rs | 89 +++++++++++++++++++++++++++++ crates/tools/src/guides.rs | 2 +- crates/tools/src/guides/snap.rs | 22 +++++++ crates/tools/src/quickpen.rs | 56 +++++++++++++----- crates/tools/src/quickpen/tests.rs | 15 +++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 7 files changed, 177 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 3612dfe2b9..fe4a9ae553 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,23 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from +/// the placed end back to where the pointer was; the next move shows the preview again. +#[test] +fn a_click_on_a_tick_leaves_no_preview_back_to_the_pointer() { + let at = arc_end_61(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + press_in(&mut s, &[(at.x, at.y)], v); + assert!(drawn_end(&s).distance(tick_60()) < 1e-6); + let label = |s: &mut Session| s.overlays(v).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(!label(&mut s), "no distance label back to the pointer"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 300.0), v).unwrap(); + assert!(label(&mut s)); +} + /// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt /// switches the action, the same hover puts it beside the pointer. #[test] @@ -640,6 +657,78 @@ fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { } } +/// A hover made with Smart Guides off shows nothing once they are turned on under the still +/// pointer, so it shows no tick that a click would not use (another path's anchor under the +/// pointer takes the click). The next move shows the hover again, its label beside the anchor; +/// once Smart Guides are turned off again, its guides are hidden with it, also after a click. +#[test] +fn a_hover_shows_nothing_after_smart_guides_change() { + let at = arc_end_61(); + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": at.x, "y1": at.y, "x2": 600, "y2": at.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, off); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), off).unwrap(); + let label = |s: &mut Session, v: ViewInfo| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + assert!(label(&mut s, off).is_some()); + assert_eq!(label(&mut s, on), None, "the hover from before the change shows nothing"); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); + let off_anchor = label(&mut s, on).unwrap() - at; + assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on)); + assert!(only_points(&mut s, off), "only the path's points show"); + // A click before the pointer moves does not bring the stale hover back. + press_in(&mut s, &[(400.0, 300.0)], off); + assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); +} + +/// While the pointer hovers, the tool asks the canvas to hover it again when the view, the document +/// or the selection changes under a still pointer, so the snapped point follows the art; a press +/// stops it until the next move. +#[test] +fn a_hover_is_hovered_again_when_the_art_changes() { + let mut s = session(); + continuous_arc_after_a_line(&mut s, view()); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + assert!(s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); +} + +/// A hover on the path's last point, which another path's anchor shares, shows that anchor's Smart +/// Guide; after Smart Guides are turned off, a click there adds nothing and the guide stays hidden +/// while the button is held and after it is let go. +#[test] +fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": 200, "y1": 100, "x2": 200, "y2": 400})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, on); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + assert!(only_points(&mut s, off)); + let steps = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), off).unwrap(); + assert!(only_points(&mut s, off), "the guide stays hidden while the button is held"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 100.0), off).unwrap(); + assert_eq!(undo_steps(&s), steps, "the click adds nothing"); + assert!(only_points(&mut s, off), "the guide stays hidden"); +} + /// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. #[test] fn an_arc_drag_shows_the_protractor() { diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index e9f7bf7318..ccbf258512 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -25,10 +25,10 @@ mod snap; mod targets; pub(crate) use bitangent::TangentLine; -pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, }; +pub(crate) use snap::{SnapSettings, hold_on_path}; use targets::Kind; pub use targets::Targets; #[cfg(test)] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 948f5668b9..0a48b35001 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -376,6 +376,28 @@ impl SnapKey { } } +/// Every setting that can move a snapped drawn point besides the document: the window and the +/// zoom, the options and tolerances [`SnapKey`] holds except the guides' color and labels, and +/// the construction guides' angles a [`Leave::segment`] follows. A tool that keeps a hover's +/// snapped point compares two of these to see whether a click would still snap the same way. +#[derive(PartialEq)] +pub(crate) struct SnapSettings { + screen: Option, + zoom: f64, + view: [bool; 7], + snap_to_glyph: Option, + alignment_lines: bool, + tolerances: [f64; 2], + angles: &'static [f64], +} + +impl SnapSettings { + pub(crate) fn of(cx: &ToolContext) -> Self { + let SnapKey { screen, view, snap_to_glyph, style, tolerances, .. } = SnapKey::of(cx, &[]); + Self { screen, zoom: cx.zoom, view, snap_to_glyph, alignment_lines: style.lines, tolerances, angles: cx.construction_angles } + } +} + /// The part of the document the window shows (none headless: all of it). pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6b6a56b408..f4bf64a648 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -20,8 +20,11 @@ //! shows that piece. With Smart Guides on, the end of a continuous arc goes onto the nearest tick //! of that protractor when the tick lies within the snapping tolerance of the pointer, no other //! Smart Guide snaps the point, and neither the grid nor pixels snap drawn points. A sharp-corner -//! arc sweeps its arc size, so its end is not snapped to a tick. Shift does not constrain Quick Pen -//! points, so it does not change the snapping. +//! arc, and a continuous arc that has no direction to follow, sweep the arc size, so their ends are +//! not snapped to a tick. After a snap setting changes under a still pointer, the hover's preview, +//! protractor, distance label and Smart Guides are hidden until the pointer moves; when the view, +//! the document or the selection changes, the canvas hovers the still pointer again. Shift does +//! not constrain Quick Pen points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -31,7 +34,7 @@ use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; -use crate::guides::{DrawSnap, Leave}; +use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -237,12 +240,14 @@ pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option { /// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the /// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for -/// other pieces, an arc without a circle, a sweep that rounds to nothing or to a whole circle, and -/// a tick past the document's coordinate limit. +/// other pieces, a continuous arc with no direction to follow (it sweeps the arc size, as a +/// sharp-corner arc does), an arc without a circle, a sweep that rounds to nothing or to a whole +/// circle, and a tick past the document's coordinate limit. pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option { if piece.stroke != Stroke::ContinuousArc { return None; } + arrival(sp)?; let arc = arc_circle(sp, piece)?; let step = TICK_STEP.to_radians(); let s = (arc.sweep / step).round() * step; @@ -374,10 +379,11 @@ pub struct QuickPenTool { press: Option, hover: Option, snap: DrawSnap, - /// The pointer while it hovers, and whether it lies on a Smart Guide target ([`Self::landed`]); - /// `hover` is where Smart Guides put it. The protractor's tick is applied when the point is - /// used ([`Self::hover_end`]), for the action chosen then. A press clears it. - pointer: Option<(Point, bool)>, + /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and + /// the snap settings then; `hover` is where Smart Guides put it. The protractor's tick is + /// applied when the point is used ([`Self::hover_end`]), for the action chosen then. A press + /// clears it. + pointer: Option<(Point, bool, SnapSettings)>, } impl Default for QuickPenTool { @@ -508,12 +514,22 @@ impl QuickPenTool { /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the - /// pointer moves after a press. + /// pointer moves after a press, and while the hover is stale ([`Self::hover_stale`]). fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option { - let ((p, landed), q) = (self.pointer?, self.hover?); + let (&(p, landed, _), q) = (self.pointer.as_ref()?, self.hover?); + if self.hover_stale(cx) { + return None; + } Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) } + /// Whether the snap settings changed since the pointer last moved: the hover's snapped point + /// and its tick may then not be where a click puts the point, so the hover shows nothing until + /// the pointer moves again. + fn hover_stale(&self, cx: &ToolContext) -> bool { + self.pointer.as_ref().is_some_and(|(_, _, at)| *at != SnapSettings::of(cx)) + } + /// During a press that adds a piece: the points before that piece, as the press found them /// (the last two, see [`tail`]). fn before_piece(&self) -> Option { @@ -636,13 +652,20 @@ impl Tool for QuickPenTool { let (on, from) = self.leave(cx).unzip(); let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); self.hover = Some(q); - self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()))); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()), SnapSettings::of(cx))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + // The hover shows again when the pointer moves after the press: the point the press + // places can lie on a tick away from it. A stale hover's guides stay hidden, also + // when the press snaps nothing. + if self.hover_stale(cx) { + self.snap.clear(); + } + self.hover = None; self.pointer = None; self.press_down(cx, p) } @@ -812,8 +835,14 @@ impl Tool for QuickPenTool { self.pointer = None; } + /// A hover's snapped point and its tick depend on the art and the view under a still pointer. + fn wants_rehover(&self) -> bool { + self.pointer.is_some() + } + fn overlays(&self, cx: &ToolContext) -> Vec { - let mut o = self.snap.guides().to_vec(); + // A stale hover's Smart Guides go with its preview. + let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; let Some((id, sp)) = self.active(cx) else { return o }; let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; // The arc being drawn: the piece a press drags, or the piece the next click adds while the @@ -832,6 +861,7 @@ impl Tool for QuickPenTool { o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } if self.press.is_none() + && !self.hover_stale(cx) && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 5fb23565c5..1319948423 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -259,6 +259,21 @@ fn a_tick_past_the_coordinate_limit_is_not_used() { assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); } +/// A continuous arc that starts a path has no direction to follow and sweeps the arc size, so its +/// end has no tick to go to: with a 100° arc size, a tick at 105° would move the end off the arc +/// the click draws. +#[test] +fn a_continuous_arc_without_a_direction_has_no_tick() { + let sp = start(pt(0.0, 0.0)); + let pc = Piece { turn: 100.0, ..piece(100.0, 10.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 100.0).abs() < 1e-9, "{arc:?}"); + assert!(tick_end(&sp, &pc).is_none()); + // After a line, the same end has a tick. + let sp = build(&start(pt(-100.0, 0.0)), &[piece(0.0, 0.0, Stroke::Line)], false); + assert!(tick_end(&sp, &pc).is_some()); +} + /// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first /// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c5659c8b5c..a01a4440e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7333,8 +7333,12 @@ center: a tick across the arc's circle every 15° from where the arc starts, a l arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the -point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end -does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still +pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer +moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it +does not change the tick snapping. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. A small cross marks the arc's center wherever the protractor shows; the cross is VectorCraft's own behavior too. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fb125077f7..06234e9f34 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From a5433617279e68e8fbc6a840d540fd22672dd2b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:41:30 -0800 Subject: [PATCH 035/126] Pen: Alt tapped during a Quick Pen press moves the end on or off the tick at once A press keeps the pointer and the snapped point for the end of the piece it adds. When Alt changes the action during the press, the end goes through the protractor's tick again for the new action, so a continuous arc that snapped to a tick and becomes a sharp-corner arc ends at the pointer, and a piece that becomes a continuous arc goes onto the tick, without waiting for the next drag. This also covers a press that has not dragged. --- crates/engine/src/tests/quickpen.rs | 28 +++++++++++++++++ crates/tools/src/quickpen.rs | 47 ++++++++++++++++++++--------- docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 4 files changed, 64 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index fe4a9ae553..375f648ac8 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,34 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// Alt tapped during a press moves the end of the piece for the new action at once, with no +/// further drag: a continuous arc's end on the 60° tick goes to the pointer once the piece is a +/// sharp-corner arc, after a drag and after a press that has not dragged, and a line's end at the +/// pointer goes onto the tick once the piece is a continuous arc. +#[test] +fn an_alt_tap_during_a_press_moves_the_end_for_the_new_action() { + let at = arc_end_61(); + let v = ViewInfo::default(); + // (drag first, Alt taps before the press, the end before Alt, the end after it) + for (drag, taps, before, after) in [(true, 0, tick_60(), at), (false, 0, tick_60(), at), (true, 2, at, tick_60())] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + let first = if drag { (280.0, 140.0) } else { (at.x, at.y) }; + s.pointer(&PointerEvent::new(PointerKind::Down, first.0, first.1), v).unwrap(); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x, at.y), v).unwrap(); + } + assert!(drawn_end(&s).distance(before) < 1e-6, "{drag} {taps}: {:?}", drawn_end(&s)); + s.tool_key(ToolKey::AltTap, Mods::default(), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} after Alt: {:?}", drawn_end(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} placed: {:?}", drawn_end(&s)); + } +} + /// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from /// the placed end back to where the pointer was; the next move shows the preview again. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index f4bf64a648..2e5eb61491 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -364,12 +364,14 @@ impl Drawing { } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo -/// step (a piece it adds). +/// step (a piece it adds). `end` is the pointer for the end of the piece it adds and where the +/// snap put that end, before the protractor's tick. #[derive(Clone, Copy, Debug, PartialEq)] struct Press { at: Point, dragged: bool, begun: bool, + end: Option<(Point, Point)>, } pub struct QuickPenTool { @@ -478,12 +480,12 @@ impl QuickPenTool { let before = self.before_piece(); let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); - let q = match (&before, self.drawing.as_ref().and_then(|dr| dr.pieces.last())) { - (Some(sp), Some(piece)) => { - let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - self.on_tick(cx, sp, *piece, p, q, landed) - } - _ => q, + if let Some(pr) = self.press.as_mut() { + pr.end = Some((p, q)); + } + let q = match self.drawing.as_ref().and_then(|dr| dr.pieces.last()) { + Some(piece) => self.press_end(cx, piece, p, q), + None => q, }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { @@ -493,6 +495,15 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// Where `piece`, which a press draws, ends with the pointer at `p` that the snap put at `q`: + /// on the protractor's tick when [`Self::on_tick`] puts it there for the piece's action. + fn press_end(&self, cx: &ToolContext, piece: &Piece, p: Point, q: Point) -> Point { + let Some(sp) = self.before_piece() else { return q }; + let from = sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()); + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, &sp, *piece, p, q, landed) + } + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the @@ -582,15 +593,15 @@ impl QuickPenTool { return vec![]; } let from = self.leave(cx).map(|l| l.1); - let q = self.snap.press(cx, p, &[id], from.as_ref()); - let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - let q = self.on_tick(cx, sp, self.piece_to(q), p, q, landed); + let snapped = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, snapped, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(snapped), p, snapped, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); dr.before_press = shared_node(cx.doc, id).cloned(); } - self.press = Some(Press { at: p, dragged: false, begun: true }); + self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) @@ -800,11 +811,17 @@ impl Tool for QuickPenTool { } ToolKey::AltTap => { self.action = self.action.next(); - // A drag under way draws its piece with the new action. + // A drag under way draws its piece with the new action. Its end goes through the + // protractor's tick again for that action: a continuous arc's end on a tick goes + // back to where the snap put the pointer for another action, and the other way. if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { - let (action, turn) = (self.action, self.turn); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - (last.stroke, last.turn, last.flip) = (action, turn, false); + let (action, turn, end) = (self.action, self.turn, self.press.and_then(|pr| pr.end)); + let piece = self.drawing.as_ref().and_then(|dr| dr.pieces.last()).map(|&pc| { + let pc = Piece { stroke: action, turn, flip: false, ..pc }; + end.map_or(pc, |(p, q)| Piece { to: self.press_end(cx, &pc, p, q), ..pc }) + }); + if let (Some(piece), Some(last)) = (piece, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *last = piece; } return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } diff --git a/docs/mcp.md b/docs/mcp.md index a01a4440e4..a529564ad9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7334,7 +7334,9 @@ arc ends. The piece the next click adds shows its protractor only while Enable R that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that -starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. Alt tapped +during a press moves the piece's end for the new action at once: off the tick when a continuous arc becomes a +sharp-corner arc, and onto it when the piece becomes a continuous arc. After a snap setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 06234e9f34..03f9478ece 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From 4a6924669e6cef186cee3bd1e21aef26fcf74a25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:25:03 -0800 Subject: [PATCH 036/126] 3D: meshes carry UVs, smooth bevel normals and a part index Every mesh the 3D effects build now carries texture coordinates for each corner and a part for each triangle (front, back, side, front bevel, back bevel, end cap, cut side). Corners shared by two bands of one bevel take the mean of the bands' normals unless the bevel turns there by 60 degrees or more or a band lies flat toward the front or back, and Inflate's puffed front and back keep the surface's own normals. The vector facets do not change. - Caps, Rotate's plane and Inflate's front and back map the art's bounds; walls and bevels run u along each contour and v from the front cap's edge to the back cap's; Revolve's side runs u around the sweep and v along the profile. - OBJ, glTF and USD write every corner's texture coordinates, not only those of faces with mapped graphics. - Mesh::join checks its index offsets, and joining or exporting a mesh whose lists do not match or that holds a value that is not a number is an error. Docs: docs/three-d.md (3D meshes), docs/mcp.md, docs/effects-parity.md, docs/target-app-parity.md. --- crates/effects/src/lib.rs | 2 +- crates/effects/src/revolve.rs | 11 +- crates/effects/src/solids.rs | 13 +- crates/engine/src/cmd/fileio/mesh3d.rs | 32 +- crates/engine/src/cmd/fileio/mesh3d/tests.rs | 62 ++- crates/engine/src/tests/assets_3d.rs | 14 +- crates/three-d/src/lib.rs | 54 ++- crates/three-d/src/mesh.rs | 121 +++++- crates/three-d/src/mesh/tests.rs | 24 +- crates/three-d/src/mesh/tests_attributes.rs | 432 +++++++++++++++++++ crates/three-d/src/shadow.rs | 6 +- crates/three-d/src/solid.rs | 2 +- crates/three-d/src/solid/build.rs | 289 +++++++++++-- crates/three-d/src/solid/inflate.rs | 55 ++- crates/three-d/src/solid/tests.rs | 2 +- crates/three-d/src/tests/cut_sides.rs | 4 +- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/effects-parity.md | 2 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + docs/three-d.md | 31 ++ 45 files changed, 1081 insertions(+), 109 deletions(-) create mode 100644 crates/three-d/src/mesh/tests_attributes.rs diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..91715c500d 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -117,7 +117,7 @@ pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; pub use vectorcraft_three_d::PlanarFace; -pub use vectorcraft_three_d::{BevelProfile, Mesh}; +pub use vectorcraft_three_d::{BevelProfile, Mesh, MeshPart}; pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a6f0d6b2ae..dfaf8c35e6 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -893,8 +893,11 @@ fn surface_meshes( } let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?; let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]); - for (t, points) in mesh.triangles.iter().zip(&on) { - let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied()); + for ((t, points), part) in mesh.triangles.iter().zip(&on).zip(&mesh.parts) { + let corner = |i: u32| { + let i = i as usize; + Some((*mesh.positions.get(i)?, *mesh.normals.get(i)?, *mesh.uvs.get(i)?)) + }; let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; let into = match points { Some(points) => { @@ -904,11 +907,13 @@ fn surface_meshes( None => &mut rest, }; let base = into.positions.len() as u32; - for (p, n) in corners { + for (p, n, uv) in corners { into.positions.push(p); into.normals.push(n); + into.uvs.push(uv); } into.triangles.push([base, base + 1, base + 2]); + into.parts.push(*part); } let mut out = vec![]; if !rest.is_empty() { diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5d1493fcd7..ea5d72f7ef 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2893,10 +2893,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity }; let Some(on_mesh) = on_mesh else { continue }; let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]); - for t in &rest.triangles { - let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied()); + for (t, part) in rest.triangles.iter().zip(&rest.parts) { + let corner = |i: u32| { + let i = i as usize; + Some((*rest.positions.get(i)?, *rest.normals.get(i)?, *rest.uvs.get(i)?)) + }; let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; - let points: Option> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect(); + let points: Option> = corners.iter().map(|(m, n, _)| on_mesh.art_point(*m, *n)).collect(); let into = match points { Some(points) => { art.extend(points); @@ -2905,11 +2908,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity None => &mut left, }; let base = into.positions.len() as u32; - for (m, n) in corners { + for (m, n, uv) in corners { into.positions.push(m); into.normals.push(n); + into.uvs.push(uv); } into.triangles.push([base, base + 1, base + 2]); + into.parts.push(*part); } rest = left; if !taken.is_empty() { diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 2e781772ea..205a3cec35 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -7,7 +7,9 @@ //! about the point the object turns about: in points in OBJ and USD (whose layer says how many //! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear, //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since -//! an open solid or a turned plane is seen from both sides. +//! an open solid or a turned plane is seen from both sides. Every corner carries its normal and +//! texture coordinates (`vt`, `TEXCOORD_0`, `primvars:st`); a mesh whose lists do not match, or +//! that holds a value that is not a number, is refused before anything is written. //! //! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its //! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through @@ -140,6 +142,7 @@ pub(crate) fn image_maps(textures: &[Option]) -> Vec { /// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after /// its texture). `textures` holds the picture of each part that has one, in the order of `parts`. pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option]) -> Result)>, String> { + check_parts(parts)?; let (images, image) = images(parts.len(), textures); let maps: Vec = images.iter().map(|(_, map)| map.is_some()).collect(); let names = mesh_file_names(stem, format, &maps)?; @@ -180,6 +183,21 @@ impl Scene<'_> { let t = self.textures.get(k)?.as_ref()?; Some((t.uv.as_slice(), (*self.image.get(k)?)?)) } + + /// Part `k`'s texture coordinates, one for each corner, 0 to 1 across from the left and down + /// from the top: its picture's when it has one, else its mesh's own. + fn coords(&self, k: usize) -> Option<&[[f64; 2]]> { + let count = self.parts.get(k)?.mesh.positions.len(); + let own = self.parts.get(k).map(|p| p.mesh.uvs.as_slice()); + self.texture(k).map(|(uv, _)| uv).into_iter().chain(own).find(|uv| uv.len() == count && count > 0) + } +} + +/// An error when a part's mesh cannot be written as it is: its lists do not match, or a +/// position, normal or texture coordinate is not a number +/// ([`vectorcraft_render::effects::Mesh::check`]). +fn check_parts(parts: &[SolidMesh]) -> Result<(), String> { + parts.iter().try_for_each(|p| p.mesh.check()) } /// A material: a color, with a picture that replaces its red, green and blue. @@ -230,7 +248,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { } // OBJ's texture coordinates run up from the picture's bottom. for k in 0..parts.len() { - for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() { + for uv in scene.coords(k).unwrap_or_default() { let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1])); } } @@ -243,9 +261,9 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { for (k, p) in parts.iter().enumerate() { let _ = writeln!(o, "g Solid_{}", k + 1); let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); - let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some(); + let coords = scene.coords(k).is_some(); for t in &p.mesh.triangles { - if textured { + if coords { let [a, b, c] = t.map(|i| i as usize); let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base); let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c)); @@ -255,7 +273,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { } } base += p.mesh.positions.len(); - uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len()); + uv_base += scene.coords(k).map_or(0, <[_]>::len); } let mut m = String::new(); for (k, mat) in materials.iter().enumerate() { @@ -313,7 +331,7 @@ fn gltf(stem: &str, scene: &Scene) -> String { "material": material.get(k).copied().unwrap_or(0), }); // glTF's texture coordinates run down from the picture's top, as the picture's own do. - if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) { + if let Some(uv) = scene.coords(k) { let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); let coords = view(&mut buffer, bytes, 34962); primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len()); @@ -415,7 +433,7 @@ fn usda(stem: &str, scene: &Scene) -> String { ); let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); // USD's texture coordinates run up from the picture's bottom. - if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) { + if let Some(uv) = scene.coords(k) { let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect()); let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )"); } diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 876140fce7..f87625d9fe 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -1,12 +1,18 @@ use serde_json::Value; -use vectorcraft_render::effects::{Mesh, SolidMesh}; +use vectorcraft_render::effects::{Mesh, MeshPart, SolidMesh}; use super::*; /// A 10 × 10 square facing the viewer: two triangles, each with corners of its own. fn square(color: [f32; 4]) -> SolidMesh { let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; - let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; + let mesh = Mesh { + positions: vec![a, b, c, a, c, d], + normals: vec![[0.0, 0.0, 1.0]; 6], + uvs: vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]], + triangles: vec![[0, 1, 2], [3, 4, 5]], + parts: vec![MeshPart::Front; 2], + }; SolidMesh::plain(mesh, color) } @@ -31,8 +37,9 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() { assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18); assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18); + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).count(), 18); // The third solid's last triangle uses corners 13 to 18; red solids share Material_1. - assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18")); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16/16/16 17/17/17 18/18/18")); assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]); let mtl = text(&files, "Box.mtl"); assert_eq!(mtl.matches("newmtl").count(), 2); @@ -64,8 +71,12 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() { assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); assert!(g["materials"][0].get("alphaMode").is_none()); assert_eq!(g["materials"][0]["doubleSided"], true); - // Without graphics there are no textures. - assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none()); + // Without graphics there are no textures, but every corner has its mesh's texture coordinates. + assert!(g.get("images").is_none() && g.get("textures").is_none()); + for p in prims { + let uv = &g["accessors"][p["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; + assert_eq!((uv["type"].as_str(), uv["count"].as_u64()), (Some("VEC2"), Some(6))); + } } #[test] @@ -82,7 +93,28 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() { // sRGB 0.5 is about 0.214 linear. assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); assert_eq!(u.matches('{').count(), u.matches('}').count()); - assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture")); + // Each mesh carries its own texture coordinates, up from the bottom, with no picture to show. + assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}"); + assert!(!u.contains("UsdUVTexture")); +} + +#[test] +fn a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused() { + let good = square(RED); + let mut nan = square(RED); + nan.mesh.uvs[2] = [f64::NAN, 0.0]; + let mut infinite = square(RED); + infinite.mesh.normals[0] = [f64::INFINITY, 0.0, 0.0]; + let mut short = square(RED); + short.mesh.uvs.pop(); + let mut unnamed = square(RED); + unnamed.mesh.parts.pop(); + for bad in [nan, infinite, short, unnamed] { + for format in FORMATS_3D { + assert!(plain_files("Box", format, &[good.clone(), bad.clone()]).is_err(), "{format} {bad:?}"); + } + } + assert!(plain_files("Box", "obj", &[good]).is_ok()); } #[test] @@ -141,7 +173,10 @@ fn prim_names_are_usd_identifiers() { fn textured(png: &[u8]) -> (Vec, Vec>) { let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv }; - (vec![square(RED), square(BLUE)], vec![None, Some(texture)]) + // The picture's coordinates replace the mesh's own. + let mut blue = square(BLUE); + blue.mesh.uvs = vec![[0.25, 0.25]; 6]; + (vec![square(RED), blue], vec![None, Some(texture)]) } #[test] @@ -154,16 +189,18 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]); assert_eq!(files[2].1, png); let obj = text(&files, "My_Box.obj"); - assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]); - assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12")); - assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates"); + // The plain part's own coordinates come first, then the textured part's picture's. + let square_vt = ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]; + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), [square_vt, square_vt].concat()); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/10/10 11/11/11 12/12/12")); + assert!(obj.contains("f 1/1/1 2/2/2 3/3/3"), "the plain part keeps its mesh's texture coordinates"); let mtl = text(&files, "My_Box.mtl"); assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}"); assert_eq!(mtl.matches("map_Kd").count(), 1); // glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI. let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); let prims = g["meshes"][0]["primitives"].as_array().unwrap(); - assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none()); + assert!(prims[0]["attributes"].get("TEXCOORD_0").is_some(), "the plain part keeps its mesh's texture coordinates"); let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126))); let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize]; @@ -182,8 +219,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { let files = mesh_files("Box", "usda", &parts, &pictures).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.usda", "Box-texture-1.png"]); let u = text(&files, "Box.usda"); - assert_eq!(u.matches("primvars:st").count(), 1); - assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}"); + assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}"); assert!(u.contains("color3f inputs:diffuseColor.connect = "), "{u}"); assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\"")); assert!(u.contains("float2 inputs:st.connect = ")); diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 1a647fb798..05141e2cb9 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -301,8 +301,9 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); // The USDA's front cap shows the front picture through st, up from the picture's bottom. let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("UsdUVTexture").count(), 2); assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 3, "every mesh carries texture coordinates"); // glTF holds both pictures, and a cap's coordinates stay inside its picture. let (mut s, _) = mapped("gltf"); let out = files(&run(&mut s, "assets.export3D", json!({}))); @@ -354,7 +355,7 @@ fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { let middle = (150.0 * scale) as u32; assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (1, 1), "the side is the only face"); // Moved 50 pt around the axis, the graphic moves as far across the picture. let (mut s, _) = revolved("usda", json!({}), 50.0); let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); @@ -381,7 +382,8 @@ fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (2, 1), "the cut sides and the side"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 2, "the plain cut sides keep their own texture coordinates"); let d = &s.doc().unwrap().doc; let id = d.asset(asset).unwrap().nodes[0].0; // Without its graphics the surface is one plain mesh, as before. @@ -476,7 +478,11 @@ fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = String::from_utf8(out[0].1.clone()).unwrap(); - assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + assert!(!out[1].1.windows(6).any(|w| w == b"map_Kd") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + // The plain mesh still carries a texture coordinate, 0 to 1, for every corner. + let count = |p: &str| obj.lines().filter(|l| l.starts_with(p)).count(); + assert!(count("vt ") > 0 && count("vt ") == count("v ")); + assert!(obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ')).all(|v| (0.0..=1.0).contains(&v.parse::().unwrap()))); } #[test] diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 56a49aadf7..891ff4fcbc 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -23,7 +23,9 @@ mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; -pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface}; +pub use mesh::{ + Mesh, MeshPart, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface, +}; mod shadow; pub use shadow::{ MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, @@ -1071,9 +1073,21 @@ fn keep_profile( turn: f64, caps: &[usize], surface: Option>, - mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>) -> Result<(), String>, + mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>, MeshPart, solid::Attrs) -> Result<(), String>, ) -> Result<(), String> { let (o, steps) = (at.o, at.steps); + // For the mesh's texture, the side runs around the sweep (0 to 1 from its start) and along the + // profile (0 to 1 from its first point); each end cap spans its disk. + let mut profile = Vec::with_capacity(s.points.len()); + let mut length = 0.0; + for (k, p) in s.points.iter().enumerate() { + if let Some(q) = k.checked_sub(1).and_then(|k| s.points.get(k)) { + length += q.distance(*p); + } + profile.push(length); + } + let along = |k: usize| if length > 1e-12 { (profile.get(k).copied().unwrap_or(0.0) / length).clamp(0.0, 1.0) } else { 0.5 }; + let around = |j: usize| j as f64 / steps.max(1) as f64; for (i, (pair, hole)) in s.points.windows(2).zip(&s.holes).enumerate() { let [a, b] = pair else { continue }; let turn = if *hole { -turn } else { turn }; @@ -1088,7 +1102,9 @@ fn keep_profile( let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); // The corners on the side surface, as the drawn faces place them. let uv = surface.map(|(along, angle)| surface_corners(*a, *b, at.axis, along.get(i).copied().unwrap_or_default(), angle(j))); - keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv)?; + let (u0, u1, w0, w1) = (around(j), around(j + 1), along(i), along(i + 1)); + let texture = solid::Attrs::Corners(vec![vec![([u0, w0], None), ([u0, w1], None), ([u1, w1], None), ([u1, w0], None)]]); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv, MeshPart::Side, texture)?; } } for &index in caps { @@ -1099,7 +1115,14 @@ fn keep_profile( } else { cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); } - keep(cap, o.rotate(V3(0.0, outward, 0.0)), None)?; + let r = (end.x - at.axis).abs(); + let plane = solid::PlaneUv { + origin: o.rotate(V3(0.0, end.y - at.center_y, 0.0)), + x: o.rotate(V3(1.0, 0.0, 0.0)), + y: o.rotate(V3(0.0, 0.0, 1.0)), + area: Rect::new(-r, -r, r, r), + }; + keep(cap, o.rotate(V3(0.0, outward, 0.0)), None, MeshPart::Cap, solid::Attrs::Planar(plane))?; } Ok(()) } @@ -1324,8 +1347,8 @@ impl CutRegions { let (draw, mesh, lost) = kept; let result = match mesh.as_deref_mut() { Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| { - keep_cuts(at, &loops, |contours, normal| { - m.push((contours, normal)); + keep_cuts(at, &loops, |contours, normal, attrs| { + m.push(solid::Face3 { contours, normal, part: MeshPart::Cut, attrs }); if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }) }), @@ -1343,14 +1366,19 @@ impl CutRegions { /// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions /// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh -/// leaves the holes open. `keep` keeps one face with its outward normal. -fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { +/// leaves the holes open. `keep` keeps one face with its outward normal and where its corners lie +/// on its texture: each corner's profile point in the bounds of the loops. +fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3, solid::Attrs) -> Result<(), String>) -> Result<(), String> { if loops.is_empty() { return Ok(()); } + let area = solid::rings_bounds(loops.iter().map(Vec::as_slice)); for (step, normal) in cut_sides(at) { let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); - keep(contours, at.o.rotate(normal))?; + // A profile point goes to view space by one affine map at each step. + let origin = at.vertex(Point::ZERO, step); + let (x, y) = (at.vertex(Point::new(1.0, 0.0), step).sub(origin), at.vertex(Point::new(0.0, 1.0), step).sub(origin)); + keep(contours, at.o.rotate(normal), solid::Attrs::Planar(solid::PlaneUv { origin, x, y, area }))?; } Ok(()) } @@ -1399,8 +1427,8 @@ fn revolve_sweep( } let face_limit = revolve_face_limit(o); // A face kept for a mesh: its normal follows from its corners. - let keep = |mesh: &mut Vec, face: Vec, normal: V3| { - mesh.push((vec![face], normal)); + let keep = |mesh: &mut Vec, face: Vec, normal: V3, part: MeshPart, attrs: solid::Attrs| { + mesh.push(solid::Face3 { contours: vec![face], normal, part, attrs }); if mesh.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }; if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { @@ -1584,8 +1612,8 @@ fn revolve_sweep( let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); let along = (surface.is_some() && surface_contour == Some(contour)).then(|| along_profile(&kept.points, axis, sp.closed)); let layout = along.as_deref().map(|along| (along, &surface_angle as &dyn Fn(usize) -> [f64; 2])); - let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv| { - keep(m, face, normal)?; + let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv, part, attrs| { + keep(m, face, normal, part, attrs)?; if let (Some(uv), Some(s)) = (uv, surface.as_deref_mut()) { s.push((m.len() - 1, uv)); } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index a5cf621d9c..53e1cb5786 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -4,28 +4,71 @@ //! //! Coordinates are points with y up and z toward the viewer, about the point the solid turns about //! (the centre of the art's bounds; for Revolve, the axis at the profile's middle). Each face keeps -//! its own corners and normal, so the mesh is shaded flat. Planar faces with holes (caps and the -//! turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then the -//! outline is cut by ear clipping. +//! its own corners. A corner takes its face's normal, with two exceptions. On a bevel, the corners +//! two bands of one bevel share take the mean of the bands' normals, unless the bevel turns there +//! by 60° or more or one of the bands lies flat toward the front or back. On Inflate's puffed +//! front and back, each corner takes the surface's own normal. Planar faces with holes (caps and +//! the turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then +//! the outline is cut by ear clipping. +//! +//! Every corner has texture coordinates from 0 to 1 each way, u to the right and v down, and every +//! triangle names the part of the solid it belongs to ([`MeshPart`]): +//! +//! - Caps, Rotate's plane and Inflate's front and back take each corner's point in the art, before +//! any twist or taper, within the art's bounds. The back is not mirrored. +//! - Extrude & Bevel's bevels and walls, and Inflate's walls, take u along each contour of the +//! outline from its first point (its distance over the contour's length, so its first point is +//! at both 0 and 1) and v across the side from the front cap's edge to the back cap's. +//! - Revolve's side takes u around the sweep from its start and v along each contour of the +//! profile from its first point. Its end caps span the disk they close, and its cut sides take +//! each corner's profile point within the bounds of the profile. +//! +//! An axis with no extent (a contour of no length, art of no width) takes 0.5. + +use std::collections::HashMap; use vectorcraft_geom::{FillRule, PathData, Point, Rect}; -use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; +use crate::solid::{Attrs, Face3, Keep, extrude_faces, inflate_faces, plane_faces}; use crate::{Extrude, Facet, Inflate, Revolve, V3, View}; /// Most steps the triangulation of one solid may take: a face's ears and bridges each test the /// face's other corners. const MAX_WORK: usize = 400_000_000; +/// The part of a solid a triangle of its mesh belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MeshPart { + /// Extrude & Bevel's front cap, Rotate's plane, and Inflate's front. + Front, + /// Extrude & Bevel's back cap, and Inflate's back, puffed or flat. + Back, + /// The walls of Extrude & Bevel and Inflate, and the side Revolve sweeps. + Side, + /// Extrude & Bevel's bevel between the front cap and the walls. + FrontBevel, + /// Extrude & Bevel's bevel between the walls and the back cap, with the bevel on both sides. + BackBevel, + /// A disk or sector closing an end of Revolve's profile. + Cap, + /// A flat side closing a Revolve sweep of less than 360°. + Cut, +} + /// A triangle mesh. #[derive(Clone, Debug, Default, PartialEq)] pub struct Mesh { /// Corner positions in points: x right, y up, z toward the viewer. pub positions: Vec<[f64; 3]>, - /// One unit normal for each position: the normal of the face the corner belongs to. + /// One unit normal for each position: the normal of the face the corner belongs to, or a + /// smoothed one (see the module's description). pub normals: Vec<[f64; 3]>, + /// Texture coordinates for each position, each from 0 to 1: u to the right, v down. + pub uvs: Vec<[f64; 2]>, /// Corner indices, counterclockwise seen from the side the normals point to. pub triangles: Vec<[u32; 3]>, + /// The part of the solid each triangle belongs to. + pub parts: Vec, } impl Mesh { @@ -33,6 +76,24 @@ impl Mesh { self.triangles.is_empty() } + /// Whether the lists match and hold numbers: a normal and texture coordinates for each + /// position, a part for each triangle, every corner index naming a position, and every + /// position, normal and texture coordinate finite. + pub fn is_consistent(&self) -> bool { + let n = self.positions.len(); + let finite = self.positions.iter().chain(&self.normals).flatten().chain(self.uvs.iter().flatten()).all(|v| v.is_finite()); + self.normals.len() == n + && self.uvs.len() == n + && self.parts.len() == self.triangles.len() + && self.triangles.iter().flatten().all(|&i| usize::try_from(i).is_ok_and(|i| i < n)) + && finite + } + + /// An error when the mesh cannot be written as it is ([`Mesh::is_consistent`]). + pub fn check(&self) -> Result<(), String> { + if self.is_consistent() { Ok(()) } else { Err("The 3D object's mesh is incomplete or holds a value that is not a number".into()) } + } + /// The smallest and largest coordinate on each axis; `None` for an empty mesh. pub fn bounds(&self) -> Option<([f64; 3], [f64; 3])> { let first = *self.positions.first()?; @@ -41,16 +102,22 @@ impl Mesh { })) } - /// The meshes of `parts` as one, in order. - pub fn join(parts: impl IntoIterator) -> Mesh { + /// The meshes of `parts` as one, in order. An error when a mesh cannot be written as it is + /// ([`Mesh::check`]) or the corners would pass what a `u32` index can name. + pub fn join(parts: impl IntoIterator) -> Result { let mut out = Mesh::default(); for m in parts { - let base = out.positions.len() as u32; + m.check()?; + let base = u32::try_from(out.positions.len()).map_err(|_| too_complex())?; + // Every index of `m` is below its count of positions, so the shifted indices fit too. + base.checked_add(u32::try_from(m.positions.len()).map_err(|_| too_complex())?).ok_or_else(too_complex)?; out.positions.extend(m.positions); out.normals.extend(m.normals); + out.uvs.extend(m.uvs); out.triangles.extend(m.triangles.into_iter().map(|t| t.map(|i| i + base))); + out.parts.extend(m.parts); } - out + Ok(out) } } @@ -154,6 +221,11 @@ pub(crate) fn newell(contours: &[Vec]) -> V3 { n } +/// The exact position of `v`, as a key ([`Face3::corner`] matches corners exactly). +fn key(v: V3) -> [u64; 3] { + [v.0.to_bits(), v.1.to_bits(), v.2.to_bits()] +} + /// From the effects' view space (y down) to the mesh's (y up). fn up(v: V3) -> [f64; 3] { [v.0, -v.1, v.2] @@ -176,7 +248,8 @@ fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result) -> Result vec![[v0, v1, v2], [v0, v2, v3]], None => triangulate(contours, geometric, &mut work)?, }; + // A face with many listed corners looks each one up by its position. + let listed = match &face.attrs { + Attrs::Corners(list) if list.iter().map(Vec::len).sum::() > 16 => { + let mut map = HashMap::new(); + for (c, l) in contours.iter().zip(list) { + for (v, data) in c.iter().zip(l) { + map.entry(key(*v)).or_insert(*data); + } + } + Some(map) + } + _ => None, + }; for [a, b, c] in triangles { let (pa, pb, pc) = (up(a), up(b), up(c)); let cross = V3(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).cross(V3(pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])); @@ -212,9 +298,20 @@ fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result map.get(&key(v)).copied().unwrap_or(([0.5, 0.5], None)), + None => face.corner(v), + }; + // A corner's own normal, when it has a usable one, else the face's. + let own = own.map(V3::unit).filter(|m| m.dot(*m) > 0.5 && [m.0, m.1, m.2].iter().all(|x| x.is_finite())); + out.normals.push(own.map_or([nx, ny, nz], up)); + out.uvs.push(uv); + } out.triangles.push([base, base + 1, base + 2]); + out.parts.push(face.part); if track { on.push(point(a).zip(point(b)).zip(point(c)).map(|((a, b), c)| [a, b, c])); } @@ -497,3 +594,5 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_attributes; diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 907c9f91b2..63a0a21dc2 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -543,10 +543,32 @@ fn join_numbers_each_parts_corners_after_the_last() { square(&mut b, 0.0, 0.0, 10.0, false); let (p, r) = shape(&b); let one = plane_mesh(&p, FillRule::NonZero, r, front()).unwrap(); - let both = Mesh::join([one.clone(), one.clone()]); + let both = Mesh::join([one.clone(), one.clone()]).unwrap(); assert_eq!(both.triangles.len(), 2 * one.triangles.len()); assert!(both.triangles.iter().all(|t| t.iter().all(|i| (*i as usize) < both.positions.len()))); assert_eq!(both.triangles[one.triangles.len()][0], one.triangles[0][0] + one.positions.len() as u32); + assert!(both.is_consistent()); + assert_eq!(both.uvs.len(), 2 * one.uvs.len()); + assert_eq!(both.parts.len(), 2 * one.parts.len()); +} + +#[test] +fn join_refuses_a_mesh_whose_lists_do_not_match() { + let mut b = BezPath::new(); + square(&mut b, 0.0, 0.0, 10.0, false); + let (p, r) = shape(&b); + let one = plane_mesh(&p, FillRule::NonZero, r, front()).unwrap(); + for broken in [ + Mesh { uvs: vec![], ..one.clone() }, + Mesh { parts: vec![], ..one.clone() }, + Mesh { normals: vec![], ..one.clone() }, + Mesh { uvs: vec![[f64::NAN, 0.0]; one.uvs.len()], ..one.clone() }, + Mesh { positions: vec![[f64::INFINITY, 0.0, 0.0]; one.positions.len()], ..one.clone() }, + Mesh { triangles: vec![[0, 1, u32::MAX]], parts: vec![MeshPart::Front], ..one.clone() }, + ] { + assert!(!broken.is_consistent()); + assert!(Mesh::join([one.clone(), broken]).is_err()); + } } /// A mesh's positions and normals as bits, and its triangles. diff --git a/crates/three-d/src/mesh/tests_attributes.rs b/crates/three-d/src/mesh/tests_attributes.rs new file mode 100644 index 0000000000..bbd766a9b9 --- /dev/null +++ b/crates/three-d/src/mesh/tests_attributes.rs @@ -0,0 +1,432 @@ +use std::collections::HashMap; + +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::*; +use crate::{Bevel, BevelProfile, BevelShape, Edge}; + +fn rectangle(x: f64, y: f64, w: f64, h: f64) -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + w, y)); + b.line_to((x + w, y + h)); + b.line_to((x, y + h)); + b.close_path(); + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// A rectangle with a square hole: the hole's wall is a contour of its own. +fn holed() -> (PathData, Rect) { + let mut b = BezPath::new(); + for (x, y, s, clockwise) in [(0.0, 0.0, 100.0, false), (40.0, 40.0, 20.0, true)] { + b.move_to((x, y)); + let corners = if clockwise { [(x, y + s), (x + s, y + s), (x + s, y)] } else { [(x + s, y), (x + s, y + s), (x, y + s)] }; + for c in corners { + b.line_to(c); + } + b.close_path(); + } + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// A vertical line from y 0 to 100, 20 pt from the left edge of its bounds' axis. +fn line_profile() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((20.0, 0.0)); + b.line_to((20.0, 100.0)); + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +fn front() -> View { + View { rotation_x: 0.0, rotation_y: 0.0, rotation_z: 0.0, perspective: 0.0, ..View::default() } +} + +fn turned() -> View { + View { rotation_x: -25.0, rotation_y: 35.0, rotation_z: 10.0, perspective: 0.0, ..View::default() } +} + +fn bevel(shape: BevelShape) -> Bevel { + Bevel { shape, width: 6.0, height: 6.0, ..Bevel::default() } +} + +fn beveled(b: Bevel) -> Extrude { + Extrude { bevel: Some(b), ..Extrude::default() } +} + +fn custom() -> BevelShape { + BevelShape::Custom(BevelProfile::new(&[(0.0, 0.0), (0.5, 0.2), (0.8, 0.5), (1.0, 1.0)]).unwrap()) +} + +fn length(v: [f64; 3]) -> f64 { + v.iter().map(|x| x * x).sum::().sqrt() +} + +fn geometric(m: &Mesh, t: [u32; 3]) -> [f64; 3] { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]); + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let l = length(n); + n.map(|x| x / l) +} + +/// Every list of `m` matches, every texture coordinate is a number from 0 to 1, and every normal +/// is a unit vector. +fn check(m: &Mesh, what: &str) { + assert!(m.is_consistent(), "{what}"); + assert!(m.uvs.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{what}"); + assert!(m.normals.iter().all(|n| (length(*n) - 1.0).abs() < 1e-9), "{what}"); + assert!(m.positions.iter().flatten().all(|v| v.is_finite()), "{what}"); +} + +fn parts(m: &Mesh) -> Vec { + let mut out: Vec = vec![]; + for p in &m.parts { + if !out.contains(p) { + out.push(*p); + } + } + out +} + +/// The meshes of every effect and many options. +fn meshes() -> Vec<(String, Mesh)> { + let (square, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let (hole, hr) = holed(); + let mut out = vec![]; + let shapes = [BevelShape::Classic, BevelShape::Rounded, BevelShape::Cove, BevelShape::Step, BevelShape::Ogee, custom()]; + for view in [front(), turned(), View { perspective: 60.0, ..turned() }] { + for shape in shapes { + for b in [ + bevel(shape), + Bevel { inside: true, ..bevel(shape) }, + Bevel { both_sides: true, ..bevel(shape) }, + Bevel { repeat: 3, space: 0.2, ..bevel(shape) }, + ] { + let o = Extrude { bevel: Some(b), ..Extrude::default() }; + out.push((format!("{shape:?} {b:?} {view:?}"), extrude_mesh(&square, FillRule::NonZero, r, o, view).unwrap())); + } + } + for o in [ + Extrude::default(), + Extrude { twist: 90.0, taper: 0.5, bevel: Some(bevel(BevelShape::Rounded)), ..Extrude::default() }, + Extrude { depth: 0.0, ..Extrude::default() }, + Extrude { cap: false, ..Extrude::default() }, + ] { + out.push((format!("{o:?} {view:?}"), extrude_mesh(&hole, FillRule::NonZero, hr, o, view).unwrap())); + } + out.push((format!("plane {view:?}"), plane_mesh(&hole, FillRule::NonZero, hr, view).unwrap())); + let deep = Inflate { depth: 10.0, ..Inflate::default() }; + for o in [Inflate::default(), Inflate { both_sides: true, twist: 30.0, ..deep }, Inflate { cap: false, ..deep }] { + for (k, m) in inflate_meshes(&[(&hole, FillRule::NonZero)], hr, o, view).enumerate() { + out.push((format!("inflate {k} {o:?} {view:?}"), m.unwrap())); + } + } + } + let (line, lr) = line_profile(); + for angle in [360.0, 90.0] { + let o = Revolve { angle, offset: 10.0, edge: Edge::Left, rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + out.push((format!("revolve line {angle}"), revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap())); + out.push((format!("revolve holed {angle}"), revolve_mesh(&hole, FillRule::NonZero, hr, o).unwrap())); + } + out +} + +#[test] +fn every_corner_has_texture_coordinates_and_every_triangle_a_part() { + for (what, m) in meshes() { + assert!(!m.is_empty(), "{what}"); + check(&m, &what); + assert_eq!(m.uvs.len(), m.positions.len(), "{what}"); + assert_eq!(m.parts.len(), m.triangles.len(), "{what}"); + } +} + +#[test] +fn each_triangle_names_the_part_of_the_solid_it_comes_from() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let both = Extrude { bevel: Some(Bevel { both_sides: true, ..bevel(BevelShape::Rounded) }), ..Extrude::default() }; + let m = extrude_mesh(&p, FillRule::NonZero, r, both, front()).unwrap(); + let mut found = parts(&m); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Front, MeshPart::Back, MeshPart::Side, MeshPart::FrontBevel, MeshPart::BackBevel]); + // Straight on, the front cap faces the viewer and the back cap away; the walls face sideways. + for (t, part) in m.triangles.iter().zip(&m.parts) { + let n = geometric(&m, *t); + match part { + MeshPart::Front => assert!(n[2] > 1.0 - 1e-9), + MeshPart::Back => assert!(n[2] < -1.0 + 1e-9), + MeshPart::Side => assert!(n[2].abs() < 1e-9), + MeshPart::FrontBevel => assert!(n[2] > 0.0), + MeshPart::BackBevel => assert!(n[2] < 0.0), + other => panic!("{other:?}"), + } + } + assert!(plane_mesh(&p, FillRule::NonZero, r, turned()).unwrap().parts.iter().all(|p| *p == MeshPart::Front)); + let flat = extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: 0.0, ..Extrude::default() }, front()).unwrap(); + assert!(flat.parts.iter().all(|p| *p == MeshPart::Front)); + let deep = Inflate { depth: 10.0, ..Inflate::default() }; + let puffed = inflate_meshes(&[(&p, FillRule::NonZero)], r, deep, front()).next().unwrap().unwrap(); + let mut found = parts(&puffed); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Front, MeshPart::Back, MeshPart::Side]); + let (line, lr) = line_profile(); + let o = Revolve { angle: 90.0, offset: 10.0, ..Revolve::default() }; + let mut found = parts(&revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap()); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Side, MeshPart::Cap, MeshPart::Cut]); +} + +#[test] +fn caps_take_their_art_points_and_the_side_runs_around_the_outline_and_front_to_back() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let m = extrude_mesh(&p, FillRule::NonZero, r, Extrude::default(), front()).unwrap(); + let depth = Extrude::default().depth; + let (mut seams, mut ends) = (HashMap::<[u64; 3], Vec>::new(), [false; 2]); + for (t, part) in m.triangles.iter().zip(&m.parts) { + for &i in t { + let (q, uv) = (m.positions[i as usize], m.uvs[i as usize]); + match part { + // The art at (x, y) lies at (x - 50, 30 - y) in the mesh: the back is not mirrored. + MeshPart::Front | MeshPart::Back => { + assert!((uv[0] - (q[0] + 50.0) / 100.0).abs() < 1e-9 && (uv[1] - (30.0 - q[1]) / 60.0).abs() < 1e-9, "{q:?} {uv:?}"); + } + MeshPart::Side => { + seams.entry(q.map(f64::to_bits)).or_default().push(uv[0]); + // v runs from the front cap's edge to the back cap's. + let v = if q[2] > 0.0 { 0.0 } else { 1.0 }; + assert!((q[2].abs() - depth / 2.0).abs() < 1e-9 && (uv[1] - v).abs() < 1e-9, "{q:?} {uv:?}"); + ends[usize::from(q[2] < 0.0)] = true; + } + other => panic!("{other:?}"), + } + } + } + assert_eq!(ends, [true, true]); + // The outline's first point carries both ends of the side's u: the seam's corners are kept apart. + assert!(seams.values().any(|u| u.contains(&0.0) && u.contains(&1.0))); + // Along the 320 pt outline each corner of the rectangle lies 100, 160 and 260 pt from the first. + let mut along: Vec = seams.values().flatten().copied().collect(); + along.sort_by(f64::total_cmp); + along.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + assert_eq!(along.len(), 5, "{along:?}"); + for (u, expected) in along.iter().zip([0.0, 100.0, 160.0, 260.0, 320.0]) { + assert!((u - expected / 320.0).abs() < 1e-9, "{along:?}"); + } +} + +#[test] +fn revolves_side_runs_around_the_sweep_and_along_the_profile() { + let (line, lr) = line_profile(); + let o = Revolve { offset: 10.0, segments: 16, ..Revolve::default() }; + let m = revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap(); + let mut around = HashMap::<[i64; 3], Vec>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + for &i in t { + let (q, uv) = (m.positions[i as usize], m.uvs[i as usize]); + if *part == MeshPart::Side { + // The sweep's end lands on its start within rounding. + around.entry(q.map(|v| (v * 1e6).round() as i64)).or_default().push(uv[0]); + // The profile runs from y 0 (the mesh's top, at 50) to y 100 (at -50). + assert!((uv[1] - (50.0 - q[1]) / 100.0).abs() < 1e-9, "{q:?} {uv:?}"); + } else { + assert_eq!(*part, MeshPart::Cap); + } + } + } + assert!(around.values().any(|u| u.contains(&0.0) && u.contains(&1.0)), "the sweep's seam is kept apart"); +} + +/// The corners of the bottom edge's front bevel of `m` (an extruded rectangle seen straight on), +/// by position, with their normals. +fn bottom_bevel(m: &Mesh) -> HashMap<[u64; 3], Vec<[f64; 3]>> { + let mut out = HashMap::<[u64; 3], Vec<[f64; 3]>>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + let n = geometric(m, *t); + if *part != MeshPart::FrontBevel || n[0].abs() > 1e-9 || n[1] >= 0.0 { + continue; + } + for &i in t { + out.entry(m.positions[i as usize].map(f64::to_bits)).or_default().push(m.normals[i as usize]); + } + } + out +} + +/// The angle between `a` and `b` in degrees, from their cross and dot products, so that two equal +/// vectors give 0 exactly. +fn angle(a: [f64; 3], b: [f64; 3]) -> f64 { + let cross = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + length(cross).atan2(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]).to_degrees() +} + +#[test] +fn a_rounded_or_custom_bevels_normals_turn_smoothly_across_its_bands() { + let (p, r) = rectangle(0.0, 0.0, 200.0, 100.0); + for shape in [BevelShape::Rounded, custom(), BevelShape::Ogee] { + let o = Extrude { bevel: Some(bevel(shape)), ..Extrude::default() }; + let m = extrude_mesh(&p, FillRule::NonZero, r, o, front()).unwrap(); + let corners = bottom_bevel(&m); + let mut normals: Vec<[f64; 3]> = vec![]; + for (at, list) in &corners { + // Every band that meets at a corner gives it the same normal. + assert!(list.iter().all(|n| angle(*n, list[0]) < 1e-9), "{shape:?} {at:?} {list:?}"); + assert!(list.iter().all(|n| (length(*n) - 1.0).abs() < 1e-12)); + if !normals.iter().any(|n| angle(*n, list[0]) < 1e-9) { + normals.push(list[0]); + } + } + // The normals turn from the front toward the bottom in steps smaller than the profile's. + normals.sort_by(|a, b| b[2].total_cmp(&a[2])); + assert!(normals.len() >= 3, "{shape:?} {normals:?}"); + assert!(normals.windows(2).all(|w| angle(w[0], w[1]) < 45.0), "{shape:?} {normals:?}"); + // The vector facets keep their flat shading. + let facets = crate::extrude(&p, FillRule::NonZero, r, o, front()).unwrap(); + let built = crate::extrude_meshed(&p, FillRule::NonZero, r, o, front()).unwrap(); + assert_eq!(facets, built.facets); + } +} + +#[test] +fn a_steps_sharp_turns_and_a_classic_bevel_stay_hard_edges() { + let (p, r) = rectangle(0.0, 0.0, 200.0, 100.0); + let step = extrude_mesh(&p, FillRule::NonZero, r, Extrude { bevel: Some(bevel(BevelShape::Step)), ..Extrude::default() }, front()).unwrap(); + for (t, part) in step.triangles.iter().zip(&step.parts) { + if *part == MeshPart::FrontBevel { + let n = geometric(&step, *t); + for &i in t { + assert!(angle(step.normals[i as usize], n) < 1e-6, "a Step's flat bands keep their own normals"); + } + } + } + let classic = extrude_mesh(&p, FillRule::NonZero, r, Extrude { bevel: Some(bevel(BevelShape::Classic)), ..Extrude::default() }, front()).unwrap(); + for t in &classic.triangles { + let n = geometric(&classic, *t); + for &i in t { + assert!(angle(classic.normals[i as usize], n) < 1e-6); + } + } +} + +#[test] +fn inflates_puffed_front_takes_the_surfaces_own_normals() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let m = inflate_meshes(&[(&p, FillRule::NonZero)], r, Inflate::default(), front()).next().unwrap().unwrap(); + check(&m, "inflate"); + // Each point of the front has one normal, whichever pieces meet there. + let mut at = HashMap::<[u64; 3], Vec<[f64; 3]>>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + if *part == MeshPart::Front { + for &i in t { + at.entry(m.positions[i as usize].map(f64::to_bits)).or_default().push(m.normals[i as usize]); + } + } + } + assert!(at.values().filter(|list| list.len() > 1).count() > 10); + for list in at.values() { + assert!(list.iter().all(|n| angle(*n, list[0]) < 1e-9), "{list:?}"); + } +} + +/// Whether `p` lies inside the polygon `ring` (even-odd), or within `d` of one of its edges. +fn inside_or_near(rings: &[Vec], p: Point, d: f64) -> bool { + let mut odd = false; + for ring in rings { + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l2 = dx * dx + dy * dy; + let t = if l2 < 1e-18 { 0.0 } else { (((p.x - a.x) * dx + (p.y - a.y) * dy) / l2).clamp(0.0, 1.0) }; + if p.distance(Point::new(a.x + dx * t, a.y + dy * t)) <= d { + return true; + } + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + odd = !odd; + } + } + } + odd +} + +/// Every corner of `m` seen from `origin` without perspective lies within `d` of some polygon of +/// `drawn`, and every corner of `drawn` within `d` of some triangle of `m`: the mesh's outline +/// and the vector facets' differ by no more than `d`. +fn outlines_match(m: &Mesh, drawn: &[Vec>], origin: Point, d: f64, what: &str) { + let page = |q: [f64; 3]| Point::new(origin.x + q[0], origin.y - q[1]); + let triangles: Vec> = m.triangles.iter().map(|t| t.iter().map(|&i| page(m.positions[i as usize])).collect()).collect(); + for q in &m.positions { + let p = page(*q); + assert!(drawn.iter().any(|f| inside_or_near(f, p, d)), "{what}: mesh corner {p:?}"); + } + for p in drawn.iter().flatten().flatten() { + assert!(triangles.iter().any(|t| inside_or_near(std::slice::from_ref(t), *p, d)), "{what}: facet corner {p:?}"); + } +} + +/// The largest distance between the outline of a mesh and that of the vector facets of the same +/// solid, in points. +const OUTLINE_TOLERANCE: f64 = 0.05; + +#[test] +fn the_meshs_outline_stays_within_a_twentieth_of_a_point_of_the_vector_facets() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let (hole, hr) = holed(); + for shape in [BevelShape::Classic, BevelShape::Rounded, BevelShape::Step, custom()] { + for o in [ + Extrude { bevel: Some(bevel(shape)), ..Extrude::default() }, + Extrude { bevel: Some(Bevel { inside: true, both_sides: true, ..bevel(shape) }), ..Extrude::default() }, + ] { + for (path, bounds) in [(&p, r), (&hole, hr)] { + let m = extrude_mesh(path, FillRule::NonZero, bounds, o, turned()).unwrap(); + let facets = crate::extrude(path, FillRule::NonZero, bounds, o, turned()).unwrap(); + let drawn: Vec>> = facets.into_iter().map(|f| f.contours).collect(); + outlines_match(&m, &drawn, bounds.center(), OUTLINE_TOLERANCE, &format!("{shape:?} {o:?}")); + } + } + } + let (line, lr) = line_profile(); + for angle in [360.0, 120.0] { + let o = Revolve { angle, offset: 10.0, rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + let m = revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap(); + let drawn: Vec>> = crate::revolve(&line, lr, o).unwrap().into_iter().map(|f| vec![f.points]).collect(); + let origin = crate::revolve_projection(lr, o.sanitized()).origin; + outlines_match(&m, &drawn, origin, OUTLINE_TOLERANCE, &format!("revolve {angle}")); + } +} + +#[test] +fn hostile_input_gives_an_error_or_a_consistent_mesh() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + // A closed outline with no area. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((50.0, 0.0)); + b.line_to((100.0, 0.0)); + b.close_path(); + let flat = PathData::from_bezpath(&b); + let fr = Rect::new(0.0, 0.0, 100.0, 0.0); + for m in [ + extrude_mesh(&flat, FillRule::NonZero, fr, Extrude::default(), turned()), + extrude_mesh(&flat, FillRule::NonZero, fr, Extrude { bevel: Some(bevel(BevelShape::Rounded)), ..Extrude::default() }, turned()), + plane_mesh(&flat, FillRule::NonZero, fr, turned()), + extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: 0.0, ..Extrude::default() }, turned()), + extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: f64::NAN, twist: f64::NAN, ..Extrude::default() }, turned()), + extrude_mesh(&p, FillRule::NonZero, r, beveled(Bevel { width: f64::NAN, height: f64::INFINITY, ..bevel(custom()) }), turned()), + extrude_mesh(&p, FillRule::NonZero, r, beveled(Bevel { repeat: usize::MAX, ..bevel(BevelShape::Rounded) }), turned()), + revolve_mesh(&p, FillRule::NonZero, r, Revolve { segments: usize::MAX, ..Revolve::default() }), + revolve_mesh(&flat, FillRule::NonZero, fr, Revolve::default()), + ] + .into_iter() + .flatten() + { + check(&m, "hostile"); + } + let nan = Rect::new(f64::NAN, 0.0, 100.0, 60.0); + assert!(extrude_mesh(&p, FillRule::NonZero, nan, Extrude::default(), turned()).is_err()); + assert!(plane_mesh(&p, FillRule::NonZero, nan, turned()).is_err()); + assert!(revolve_mesh(&p, FillRule::NonZero, nan, Revolve::default()).is_err()); +} diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 38d2be50c7..8a89f5e3cc 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -261,7 +261,7 @@ impl ShadowCaster { let p = self.projection?; let light = p.light()?; let s = shadow.sanitized(); - let corners = || self.within(faces).flat_map(|(contours, _)| contours.iter().flatten()); + let corners = || self.within(faces).flat_map(|face| face.contours.iter().flatten()); let first = *corners().next()?; let (lo, hi) = corners() .fold((first, first), |(lo, hi), v| (V3(lo.0.min(v.0), lo.1.min(v.1), lo.2.min(v.2)), V3(hi.0.max(v.0), hi.1.max(v.1), hi.2.max(v.2)))); @@ -299,8 +299,8 @@ impl ShadowCaster { }; let to_page = |q: Point| p.project(add(foot, add(scale(u, q.x), scale(w, q.y)))); let mut bp = BezPath::new(); - for (contours, _) in self.within(faces) { - let flat: Vec> = contours.iter().map(|c| c.iter().map(|v| cast(*v)).collect()).collect(); + for face in self.within(faces) { + let flat: Vec> = face.contours.iter().map(|c| c.iter().map(|v| cast(*v)).collect()).collect(); let turn: f64 = flat.iter().map(|c| signed_area(c)).sum(); // A face edge-on to the light casts nothing. if flat_area(turn, flat.iter().flatten()) { diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 71f039724f..ca3a272dd0 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -25,9 +25,9 @@ mod side; pub(crate) use build::EXTRUDED; #[cfg(test)] pub(crate) use build::PLANES; +pub(crate) use build::{Attrs, Face3, Keep, PlaneUv, extrude_faces, plane_faces, rings_bounds}; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; -pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, extrude_side_size, extrude_surfaces, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; pub(crate) use inflate::inflate_faces; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d883ad14b8..69c0d114a4 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -10,6 +10,7 @@ use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, MapCell, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, SolidSurface, SurfaceKind, V3, View, eye_distance, perspective_scale, }; +use crate::mesh::MeshPart; use crate::shadow::Projection; /// Turns 3D points into document points and shades faces for one view. @@ -61,9 +62,109 @@ impl Camera { } } -/// A face of a solid before projection: its contours in view space (holes running the other way) -/// and its outward normal. -pub(crate) type Face3 = (Vec>, V3); +/// A face of a solid before projection: its contours in view space (holes running the other way), +/// its outward normal, the part of the solid it belongs to, and where its corners lie on the +/// part's texture ([`Attrs`]). +#[derive(Clone, Debug)] +pub(crate) struct Face3 { + pub(crate) contours: Vec>, + pub(crate) normal: V3, + pub(crate) part: MeshPart, + pub(crate) attrs: Attrs, +} + +impl Face3 { + /// The texture coordinates of corner `v` of the face, and its own normal when it has one (a + /// corner of a smoothed bevel or of a puffed surface). A point that is no corner of the face + /// lies at the middle of the texture. + pub(crate) fn corner(&self, v: V3) -> ([f64; 2], Option) { + match &self.attrs { + Attrs::Planar(plane) => (plane.at(v), None), + Attrs::Corners(list) => self + .contours + .iter() + .zip(list) + .flat_map(|(c, l)| c.iter().zip(l)) + .find(|(c, _)| **c == v) + .map_or(([0.5, 0.5], None), |(_, (uv, n))| (*uv, *n)), + } + } +} + +/// Where the corners of a face lie on its part's texture, from 0 to 1 each way (u to the right, v +/// down), and the normals of the corners that have their own. +#[derive(Clone, Debug)] +pub(crate) enum Attrs { + /// Each corner's place on a plane ([`PlaneUv`]); every corner takes the face's normal. + Planar(PlaneUv), + /// For each corner of each contour, in order, its texture coordinates and its own normal + /// (`None` takes the face's). + Corners(Vec)>>), +} + +/// A plane's texture coordinates: a point `p` on it lies at `origin + x·s + y·t`, and `(s, t)` +/// within `area` goes to 0..1 each way. `x` and `y` are square to each other. An axis on which +/// `area` has no extent gives 0.5. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PlaneUv { + pub(crate) origin: V3, + pub(crate) x: V3, + pub(crate) y: V3, + pub(crate) area: Rect, +} + +impl PlaneUv { + pub(crate) fn at(&self, p: V3) -> [f64; 2] { + let d = p.sub(self.origin); + let along = |axis: V3| d.dot(axis) / axis.dot(axis); + [share(along(self.x), self.area.x0, self.area.x1), share(along(self.y), self.area.y0, self.area.y1)] + } +} + +/// Where `v` lies from `lo` (0) to `hi` (1), within 0..1: 0.5 when the two are equal or `v` is not +/// finite. +pub(crate) fn share(v: f64, lo: f64, hi: f64) -> f64 { + let w = hi - lo; + if w > 1e-12 && v.is_finite() { ((v - lo) / w).clamp(0.0, 1.0) } else { 0.5 } +} + +/// The bounds of the points of `rings`, or an empty rectangle at the origin when they have none. +pub(crate) fn rings_bounds<'a>(rings: impl IntoIterator) -> Rect { + let mut points = rings.into_iter().flatten(); + let Some(first) = points.next() else { return Rect::ZERO }; + points.fold(Rect::from_points(*first, *first), |b, p| b.union_pt(*p)) +} + +/// The texture coordinate along each point of `ring` and back to its first point: the distance +/// along the ring from its first point over the ring's length, so the first point takes 0 and the +/// last entry (the first point again) 1. A ring of no length takes 0.5 throughout. +pub(crate) fn along_ring(ring: &[Point]) -> Vec { + let n = ring.len(); + let mut at = Vec::with_capacity(n + 1); + let mut sum = 0.0; + for i in 0..=n { + at.push(sum); + if let (Some(a), Some(b)) = (ring.get(i % n.max(1)), ring.get((i + 1) % n.max(1))) { + sum += a.distance(*b); + } + } + let total = at.last().copied().unwrap_or(0.0); + at.iter().map(|d| if total > 1e-12 { (d / total).clamp(0.0, 1.0) } else { 0.5 }).collect() +} + +/// The texture coordinates and corner normals of the faces of one band ([`Builder::curved_band`]): +/// the coordinate along the ring at each of its points and back at its first ([`along_ring`]), the +/// coordinate across the band at its two rings, and, for each edge of the rings, the normal of its +/// corners on each ring when they are smoothed (`None` takes the face's). +pub(super) struct BandMesh<'a> { + pub(super) part: MeshPart, + pub(super) u: &'a [f64], + pub(super) v: [f64; 2], + pub(super) normals: Option>, +} + +/// The smoothed normals of the corners of each edge on a band's two rings ([`BandMesh`]). +pub(super) type RowNormals<'a> = (&'a [Option], &'a [Option]); /// What a solid's builder makes: its facets, its faces before projection when a mesh is asked for /// (an error when they pass [`MAX_SOLID_FACES`] while the facets are built too), and the @@ -145,8 +246,22 @@ impl<'a> Builder<'a> { } } + /// Whether the builder keeps faces for a mesh. + pub(super) fn keeps_mesh(&self) -> bool { + self.mesh.is_some() + } + /// Add a face of view-space contours with outward normal `n` (view space), drawn in `order`. - pub(super) fn face(&mut self, contours: Vec>, n: V3, order: Order) -> Result<(), String> { + /// For a mesh it belongs to `part`, and `attrs` gives where its corners lie on the part's + /// texture, from its contours. + pub(super) fn face( + &mut self, + contours: Vec>, + n: V3, + order: Order, + part: MeshPart, + attrs: impl FnOnce(&[Vec]) -> Attrs, + ) -> Result<(), String> { let count: usize = contours.iter().map(Vec::len).sum(); if count < 3 { return Ok(()); @@ -155,7 +270,8 @@ impl<'a> Builder<'a> { self.facet(&contours, count, n, order)?; } let Some(mesh) = &mut self.mesh else { return Ok(()) }; - mesh.push((contours, n.unit())); + let attrs = attrs(&contours); + mesh.push(Face3 { contours, normal: n.unit(), part, attrs }); if mesh.len() > MAX_SOLID_FACES { if !self.draw { return Err(TOO_COMPLEX_SURFACE.into()); @@ -245,15 +361,23 @@ impl<'a> Builder<'a> { } /// A planar surface triangle with shared, smooth outward normals. Culling and sorting - /// still use its geometry, rather than the normals used only for lighting. - pub(super) fn smooth_triangle(&mut self, vertices: [V3; 3], normals: [V3; 3], back: bool) -> Result<(), String> { + /// still use its geometry, rather than the normals used only for lighting. For a mesh it + /// belongs to `part`, with its corners at `uv` on the part's texture and their normals. + pub(super) fn smooth_triangle( + &mut self, + vertices: [V3; 3], + normals: [V3; 3], + back: bool, + part: MeshPart, + uv: [[f64; 2]; 3], + ) -> Result<(), String> { let contours = vec![vertices.to_vec()]; let n = newell(&contours); let n = if back { V3(-n.0, -n.1, -n.2) } else { n }; let centre = vertices.iter().fold(V3::default(), |s, v| V3(s.0 + v.0 / 3.0, s.1 + v.1 / 3.0, s.2 + v.2 / 3.0)); let flip = !self.closed && self.camera.facing(centre, n.unit()) <= 0.0; let before = self.facets.len(); - self.face(contours, n, Order::Depth)?; + self.face(contours, n, Order::Depth, part, |_| Attrs::Corners(vec![uv.iter().zip(normals).map(|(uv, n)| (*uv, Some(n))).collect()]))?; if self.facets.len() == before || !self.camera.view.shade { return Ok(()); } @@ -270,15 +394,17 @@ impl<'a> Builder<'a> { /// The band between two partner rings (same length), as one quad per edge, or for a twisted /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the - /// direction (before rotation) the band faces away from the solid, for orienting normals. - pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None, None) + /// direction (before rotation) the band faces away from the solid, for orienting normals. For a + /// mesh the quads take their part, texture coordinates and corner normals from `mesh`. + pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3, mesh: &BandMesh) -> Result<(), String> { + self.curved_band(a, b, cuts, outward, None, None, mesh) } /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. /// With `side`, each quad carries where its corners lie on the side unrolled flat /// ([`Facet::surface`]). + #[allow(clippy::too_many_arguments)] pub(super) fn curved_band( &mut self, a: &[V3], @@ -287,6 +413,7 @@ impl<'a> Builder<'a> { outward: impl Fn(usize) -> V3, mut curves: Option, side: Option, + mesh: &BandMesh, ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. @@ -316,7 +443,17 @@ impl<'a> Builder<'a> { normal = V3(-normal.0, -normal.1, -normal.2); } let before = self.facets.len(); - self.face(vec![quad], normal, order)?; + let attrs = |_: &[Vec]| { + let (u0, u1) = (mesh.u.get(i).copied().unwrap_or(0.5), mesh.u.get(i + 1).copied().unwrap_or(0.5)); + let (ua, ub) = (u0 + (u1 - u0) * s0, u0 + (u1 - u0) * s1); + let [va, vb] = mesh.v; + // A cut edge's pieces keep their own normals. + let normals = mesh.normals.filter(|_| pieces == 1); + let na = normals.and_then(|(na, _)| na.get(i).copied().flatten()); + let nb = normals.and_then(|(_, nb)| nb.get(i).copied().flatten()); + Attrs::Corners(vec![vec![([ua, va], na), ([ub, va], na), ([ub, vb], nb), ([ua, vb], nb)]]) + }; + self.face(vec![quad], normal, order, mesh.part, attrs)?; if self.facets.len() > before && let Some(f) = self.facets.last_mut() { @@ -648,6 +785,92 @@ fn steps(o: &Extrude) -> Vec { out } +/// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when +/// it reaches a back bevel step, and 0 for a wall. +fn band_face(s0: &Step, s1: &Step) -> f64 { + if s1.face < 0.0 { + -1.0 + } else if s0.face > 0.0 && s1.face > 0.0 { + 1.0 + } else { + 0.0 + } +} + +/// The part of the mesh a band bordering `face` ([`band_face`]) belongs to. +fn band_part(face: f64) -> MeshPart { + if face > 0.0 { + MeshPart::FrontBevel + } else if face < 0.0 { + MeshPart::BackBevel + } else { + MeshPart::Side + } +} + +/// The texture coordinate across the side at each step, front to back: the distance from the +/// front cap's edge through the bevels and walls (inset and depth together) over the whole +/// distance to the back cap's edge. With no distance every step takes 0.5. +fn step_coordinates(steps: &[Step], depth: f64) -> Vec { + let mut at = Vec::with_capacity(steps.len()); + let mut sum = 0.0; + for (k, s) in steps.iter().enumerate() { + if let Some(p) = k.checked_sub(1).and_then(|k| steps.get(k)) { + sum += (s.inset - p.inset).hypot((s.t - p.t) * depth); + } + at.push(sum); + } + at.iter().map(|d| if sum > 1e-12 { (d / sum).clamp(0.0, 1.0) } else { 0.5 }).collect() +} + +/// The largest angle, in degrees, between two neighboring bands of one bevel whose shared corners +/// are smoothed for a mesh. A sharper turn (a Step profile's) stays a hard edge. +pub(crate) const BEVEL_CREASE: f64 = 60.0; + +/// For a mesh, the normal of each corner of each edge of `ring` at each step (one list per step, +/// one entry per edge) where the bands on either side are smoothed: two bands of the same bevel, +/// front or back, that turn by less than [`BEVEL_CREASE`], neither of them lying flat toward the +/// front or back (as a cap does). Such a corner takes the mean of the two bands' unit normals; +/// every other corner is `None` and takes its face's normal. `placed` holds the ring at each step +/// in view space. +fn smoothed_rows(camera: &Camera, ring: &[Point], steps: &[Step], placed: &[Vec]) -> Vec>> { + let n = ring.len(); + let front = camera.rotate(V3(0.0, 0.0, 1.0)); + // Each band's unit outward normal at each edge, as [`Builder::curved_band`] orients it. + let bands: Vec<(MeshPart, Vec)> = placed + .windows(2) + .zip(steps.windows(2)) + .map(|(pair, s)| { + let face = band_face(&s[0], &s[1]); + let normals = (0..n) + .map(|i| { + let j = (i + 1) % n; + let (Some(a), Some(c)) = (pair.first(), pair.get(1)) else { return V3::default() }; + let quad = [a.get(i), a.get(j), c.get(j), c.get(i)].into_iter().flatten().copied().collect::>(); + let normal = newell(std::slice::from_ref(&quad)).unit(); + if normal.dot(camera.rotate(outward(ring, i, face))) < 0.0 { V3(-normal.0, -normal.1, -normal.2) } else { normal } + }) + .collect(); + (band_part(face), normals) + }) + .collect(); + let crease = BEVEL_CREASE.to_radians().cos(); + let flat = |v: V3| v.dot(front).abs() > 1.0 - 1e-6; + (0..steps.len()) + .map(|k| { + let pair = k.checked_sub(1).and_then(|p| bands.get(p)).zip(bands.get(k)); + let Some(((_, n0), (_, n1))) = pair.filter(|((p0, _), (p1, _))| p0 == p1 && *p0 != MeshPart::Side) else { return vec![None; n] }; + n0.iter() + .zip(n1) + .map(|(a, b)| { + let whole = a.dot(*a) > 0.5 && b.dot(*b) > 0.5; + (whole && !flat(*a) && !flat(*b) && a.dot(*b) > crease).then(|| V3(a.0 + b.0, a.1 + b.1, a.2 + b.2).unit()) + }) + .collect() + }) + .collect() +} + /// Extrude & Bevel: the shape's outline extruded backwards, with optional twist, taper, bevels /// and caps. pub fn extrude(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result, String> { @@ -737,9 +960,14 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Some((k, side::along_ring(rings.get(k)?)?, y)) }) .flatten(); + // For a mesh: the texture coordinate across the side at each step, and the parts of the bands. + let across = step_coordinates(&steps, o.depth); + let part_of = |s0: &Step, s1: &Step| band_part(band_face(s0, s1)); for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() { let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); + let u = along_ring(ring); + let rows = if b.keeps_mesh() { smoothed_rows(&camera, ring, &steps, &placed) } else { vec![] }; for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; b.cells = layout.as_ref().and_then(|(sides, spans)| { @@ -753,32 +981,34 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); Some(BandCells { edges, across: (v0, v1) }) }); - // A band between two front bevel steps borders the front, one reaching a back bevel - // step the back; the rest are walls. - let face = if s1.face < 0.0 { - -1.0 - } else if s0.face > 0.0 && s1.face > 0.0 { - 1.0 - } else { - 0.0 - }; + let face = band_face(s0, s1); // The edges a band shares with a cap follow the cap's curves; the edges between two bands // stay straight, within the sampling tolerance. let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); - b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; + let normals = rows.get(k).zip(rows.get(k + 1)).map(|(na, nb)| (na.as_slice(), nb.as_slice())); + let v = [across.get(k).copied().unwrap_or(0.5), across.get(k + 1).copied().unwrap_or(0.5)]; + let mesh = BandMesh { part: part_of(s0, s1), u: &u, v, normals }; + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side, &mesh)?; } } b.cells = None; if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. - let caps = [(steps.first(), along.first(), 1.0, PlanarFace::Front), (steps.last(), along.last(), -1.0, PlanarFace::Back)]; - for (s, along, n, end) in caps { - let Some(s) = s else { continue }; + let caps = [ + (steps.first(), maps.first(), along.first(), 1.0, PlanarFace::Front, MeshPart::Front), + (steps.last(), maps.last(), along.last(), -1.0, PlanarFace::Back, MeshPart::Back), + ]; + // Each cap's corners take their art points, before any twist or taper, in the art's bounds. + let area = rings_bounds(rings.iter().copied()); + for (s, map, along, n, end, part) in caps { + let (Some(s), Some(map)) = (s, map) else { continue }; let before = b.len(); - b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last)?; + let (x, y, origin) = map.frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area }); + b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last, part, |_| plane)?; b.end(before, end); if let Some(along) = along { let traced: Vec<&Ring> = traced.iter().collect(); @@ -986,9 +1216,12 @@ pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: V // it is drawn last, as a cap is, and planes drawn in one order keep the order they are given in. let up = camera.rotate(V3(0.0, 0.0, 1.0)); let n = if camera.facing(V3::default(), up) < 0.0 { V3(-up.0, -up.1, -up.2) } else { up }; - b.face(contours, n, Order::Last)?; - b.end(0, PlanarFace::Front); let m = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + // The plane's corners take their art points in the art's bounds. + let (x, y, origin) = m.frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area: rings_bounds(rings.iter().map(|r| r.points.as_slice())) }); + b.face(contours, n, Order::Last, MeshPart::Front, |_| plane)?; + b.end(0, PlanarFace::Front); let at = |span: &Span, t: f64| camera.project(m.place(span.curve.eval(t))); let map = |p: Point| camera.project(m.place(p)); let along = Along { at: &at, map: Some(&map), affine: camera.eye.is_none(), tolerance: CURVE_TOLERANCE }; diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 812cf88a42..5e11fd4b59 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,11 @@ -use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; +use super::build::{ + Attrs, BandMesh, Builder, Built, Camera, Keep, Order, Placing, PlaneUv, Turn, along_ring, check_bounds, cuts, fit, newell, outward, rings_bounds, + share, +}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; +use crate::mesh::MeshPart; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -278,6 +282,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if n.dot(n) > 0.5 { n } else { V3(0.0, 0.0, 1.0) } }; let smooth = view.shade && view.has_colored_lights(); + // For a mesh, a point of the front or back takes its art point in the shape's bounds, and on a + // puffed surface its own normal, front or back (turned as the back is). + let area = rings_bounds(rings.iter().map(Vec::as_slice)); + let uv = |q: Point| [share(q.x, area.x0, area.x1), share(q.y, area.y0, area.y1)]; + let puffed = height > 0.0; + let back_normal = |n: V3, turn: &Turn| V3(turn.cos * n.0 - turn.sin * n.1, turn.sin * n.0 + turn.cos * n.1, -n.2); let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); // A graphic's offsets are from the center of the bounds the solid is built with. let center = bounds.center(); @@ -481,9 +491,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let before = b.facets.len(); let outward = newell(&[front.to_vec()]); if smoothed { - b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false, MeshPart::Front, points.map(uv))?; } else { - b.face(vec![front.to_vec()], outward, order)?; + let attrs = |_: &[Vec]| { + Attrs::Corners(vec![points.iter().map(|q| (uv(*q), puffed.then(|| camera.rotate(normal(*q))))).collect()]) + }; + b.face(vec![front.to_vec()], outward, order, MeshPart::Front, attrs)?; } if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); @@ -496,15 +509,16 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee // normal is reversed. let outward = V3(-n.0, -n.1, -n.2); if smoothed { - let normals = points.map(|q| { - let n = normal(q); - // A uniform taper scales all three coordinates equally; - // twist turns the back normal about the shape's z-axis. - camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) - }); - b.smooth_triangle(back, normals, true)?; + // A uniform taper scales all three coordinates equally; twist + // turns the back normal about the shape's z-axis. + let normals = points.map(|q| camera.rotate(back_normal(normal(q), &back_turn))); + b.smooth_triangle(back, normals, true, MeshPart::Back, points.map(uv))?; } else { - b.face(vec![back.to_vec()], outward, order)?; + let attrs = |_: &[Vec]| { + let corner = |q: &Point| (uv(*q), puffed.then(|| camera.rotate(back_normal(normal(*q), &back_turn)))); + Attrs::Corners(vec![points.iter().map(corner).collect()]) + }; + b.face(vec![back.to_vec()], outward, order, MeshPart::Back, attrs)?; } if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); @@ -521,7 +535,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect(); let n = newell(&front); let order = if flat { Order::Last } else { Order::Depth }; - b.face(front, n, order)?; + let corners = |side: &dyn Fn(Point) -> Option| -> Attrs { + Attrs::Corners(pieces.iter().map(|p| p.iter().map(|q| (uv(*q), side(*q))).collect()).collect()) + }; + let front_normal = |q: Point| puffed.then(|| camera.rotate(normal(q))); + b.face(front, n, order, MeshPart::Front, |_| corners(&front_normal))?; if o.both_sides && o.cap { // The back winds the same way round as the front, so its outward normal is // reversed. @@ -531,7 +549,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee .map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect()) .collect(); let n = newell(&back); - b.face(back, V3(-n.0, -n.1, -n.2), order)?; + let back_side = |q: Point| puffed.then(|| camera.rotate(back_normal(normal(q), &back_turn))); + b.face(back, V3(-n.0, -n.1, -n.2), order, MeshPart::Back, |_| corners(&back_side))?; } } } @@ -539,9 +558,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } if !o.both_sides && o.cap { let back: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect(); + let (x, y, origin) = Placing::new(&camera, bounds.center(), back_turn, -half).frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area }); // The back turned toward the viewer covers the walls it overlaps, even those nearer than // its center: twisted walls, and the walls of a fill inside the solid of its stroke. - b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last)?; + b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last, MeshPart::Back, |_| plane)?; } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. @@ -558,10 +579,14 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if b.len().saturating_add(edges.saturating_mul(slices)) > MAX_SOLID_FACES { return Err(TOO_COMPLEX_SURFACE.into()); } + // For a mesh, the sides run across from the front (0) to the back (1). + let across = |k: usize| k as f64 / slices.max(1) as f64; let sides = |b: &mut Builder<'_>, pieces: &[Vec]| -> Result<(), String> { for (ring, pieces) in rings.iter().zip(pieces) { + let u = along_ring(ring); for k in 0..slices { - b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0))?; + let mesh = BandMesh { part: MeshPart::Side, u: &u, v: [across(k), across(k + 1)], normals: None }; + b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0), &mesh)?; } } Ok(()) diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index d4b86d7b10..a4db35adb0 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -232,7 +232,7 @@ fn a_face_reaching_past_the_eye_has_no_plane() { for (far, has_plane) in [(eye / 2.0, true), (2.0 * eye, false)] { let mut builder = Builder::new(&camera, false, false, Keep::Facets); let corners = vec![V3(-10.0, -10.0, 0.0), V3(10.0, -10.0, 0.0), V3(0.0, 10.0, far)]; - builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth).unwrap(); + builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth, crate::MeshPart::Front, |_| super::Attrs::Corners(vec![])).unwrap(); assert_eq!(builder.facets.len(), 1, "{far}"); assert_eq!(builder.facets[0].plane.is_some(), has_plane, "{far}"); } diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs index 184ce53085..0016daf1e0 100644 --- a/crates/three-d/src/tests/cut_sides.rs +++ b/crates/three-d/src/tests/cut_sides.rs @@ -276,8 +276,8 @@ fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() { // cut side's alone, which faces back against the sweep. let in_plane = |all: bool| { let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9; - let kept = faces.iter().filter(|(_, n)| all || start(n)); - kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() + let kept = faces.iter().filter(|f| all || start(&f.normal)); + kept.flat_map(|f| f.contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() }; let cut = in_plane(false); assert!(!cut.is_empty()); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..06cf20131d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7269,6 +7269,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg a 3D effect on a group's fill or stroke draws nothing un efecte 3D al farciment o al traç d’un grup no dibuixa res @msg a 3D effect on a group's fill or stroke draws nothing to export un efecte 3D al farciment o al traç d’un grup no dibuixa res per exportar @msg The 3D object is too complex to export L’objecte 3D és massa complex per exportar-lo +@msg The 3D object's mesh is incomplete or holds a value that is not a number La malla de l’objecte 3D és incompleta o conté un valor que no és un nombre @msg give one element indica un element @msg the element needs an id, the filter's name l’element necessita un id, el nom del filtre @msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG té com a màxim {MAX_NAME} caràcters diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..999627f8f6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6860,6 +6860,7 @@ mark-style Japanese Japonské @msg a 3D effect on a group's fill or stroke draws nothing 3D efekt na výplni nebo tahu skupiny nic nekreslí @msg a 3D effect on a group's fill or stroke draws nothing to export 3D efekt na výplni nebo tahu skupiny nekreslí nic k exportu @msg The 3D object is too complex to export 3D objekt je pro export příliš složitý +@msg The 3D object's mesh is incomplete or holds a value that is not a number Síť 3D objektu je neúplná nebo obsahuje hodnotu, která není číslo @msg the element needs an id, the filter's name prvek potřebuje id, název filtru @msg an SVG filter's id is at most {MAX_NAME} characters id filtru SVG má nejvýše {MAX_NAME} znaků @msg <{_1}> isn't an element of an SVG filter <{_1}> není prvkem filtru SVG diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..56be9a99e0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -410,6 +410,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere @msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektets net er ufuldstændigt eller indeholder en værdi, der ikke er et tal @msg give one element angiv ét -element @msg the element needs an id, the filter's name -elementet skal have et id, filterets navn @msg an SVG filter's id is at most {MAX_NAME} characters et SVG-filters id er højst {MAX_NAME} tegn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..53c60f59a6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6427,6 +6427,7 @@ lighting Light Licht @msg a 3D effect on a group's fill or stroke draws nothing ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts @msg a 3D effect on a group's fill or stroke draws nothing to export ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts, das exportiert werden kann @msg The 3D object is too complex to export Das 3D-Objekt ist zu komplex für den Export +@msg The 3D object's mesh is incomplete or holds a value that is not a number Das Netz des 3D-Objekts ist unvollständig oder enthält einen Wert, der keine Zahl ist @msg the element needs an id, the filter's name das -Element braucht eine id, den Namen des Filters @msg an SVG filter's id is at most {MAX_NAME} characters die id eines SVG-Filters hat höchstens {MAX_NAME} Zeichen @msg <{_1}> isn't an element of an SVG filter <{_1}> ist kein Element eines SVG-Filters diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..c6612ad3a9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6242,6 +6242,7 @@ variable-list-end {0}, {1} {0} και {1} @msg a 3D effect on a group's fill or stroke draws nothing ένα εφέ 3D στο γέμισμα ή στην πινελιά μιας ομάδας δεν σχεδιάζει τίποτα @msg a 3D effect on a group's fill or stroke draws nothing to export ένα εφέ 3D στο γέμισμα ή στην πινελιά μιας ομάδας δεν σχεδιάζει τίποτα για εξαγωγή @msg The 3D object is too complex to export Το αντικείμενο 3D είναι πολύ σύνθετο για εξαγωγή +@msg The 3D object's mesh is incomplete or holds a value that is not a number Το πλέγμα του αντικειμένου 3D είναι ελλιπές ή περιέχει τιμή που δεν είναι αριθμός @msg give one element δώστε ένα στοιχείο @msg the element needs an id, the filter's name το στοιχείο χρειάζεται id, το όνομα του φίλτρου @msg an SVG filter's id is at most {MAX_NAME} characters το id ενός φίλτρου SVG έχει το πολύ {MAX_NAME} χαρακτήρες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3a4b1d39f7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6832,6 +6832,7 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing un efecto 3D en el relleno o el trazo de un grupo no dibuja nada @msg a 3D effect on a group's fill or stroke draws nothing to export un efecto 3D en el relleno o el trazo de un grupo no dibuja nada que exportar @msg The 3D object is too complex to export El objeto 3D es demasiado complejo para exportarlo +@msg The 3D object's mesh is incomplete or holds a value that is not a number La malla del objeto 3D está incompleta o contiene un valor que no es un número @msg give one element indique un elemento @msg the element needs an id, the filter's name el elemento necesita un id, el nombre del filtro @msg an SVG filter's id is at most {MAX_NAME} characters el id de un filtro SVG tiene como máximo {MAX_NAME} caracteres diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..379eb37892 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6760,6 +6760,7 @@ mark-style Japanese Japanilainen @msg a 3D effect on a group's fill or stroke draws nothing ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään @msg a 3D effect on a group's fill or stroke draws nothing to export ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään vietävää @msg The 3D object is too complex to export 3D-objekti on liian monimutkainen vietäväksi +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektin verkko on puutteellinen tai sisältää arvon, joka ei ole luku @msg give one element anna yksi -elementti @msg the element needs an id, the filter's name -elementti tarvitsee id:n, suotimen nimen @msg an SVG filter's id is at most {MAX_NAME} characters SVG-suotimen id on enintään {MAX_NAME} merkkiä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..bf54abd6ee 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6443,6 +6443,7 @@ lighting Light Lumière @msg a 3D effect on a group's fill or stroke draws nothing un effet 3D sur le fond ou le contour d’un groupe ne dessine rien @msg a 3D effect on a group's fill or stroke draws nothing to export un effet 3D sur le fond ou le contour d’un groupe ne dessine rien à exporter @msg The 3D object is too complex to export L’objet 3D est trop complexe pour être exporté +@msg The 3D object's mesh is incomplete or holds a value that is not a number Le maillage de l’objet 3D est incomplet ou contient une valeur qui n’est pas un nombre @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objet n’a aucun effet 3D (Extrusion et biseautage, Révolution, Gonfler ou Rotation) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` doit être un objet ne contenant que `mode`, avec la valeur shaded ou wireframe @msg its 3D effect builds no solid son effet 3D ne construit aucun volume diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e3b622ca0f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9174,6 +9174,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg a 3D effect on a group's fill or stroke draws nothing ग्रुप के फ़िल या स्ट्रोक पर 3D इफ़ेक्ट कुछ नहीं बनाता @msg a 3D effect on a group's fill or stroke draws nothing to export ग्रुप के फ़िल या स्ट्रोक पर 3D इफ़ेक्ट एक्सपोर्ट करने लायक कुछ नहीं बनाता @msg The 3D object is too complex to export 3D ऑब्जेक्ट एक्सपोर्ट करने के लिए बहुत जटिल है +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D ऑब्जेक्ट का मेश अधूरा है या उसमें ऐसा मान है जो संख्या नहीं है @msg give one element एक एलिमेंट दें @msg the element needs an id, the filter's name एलिमेंट को एक id चाहिए, जो फ़िल्टर का नाम है @msg an SVG filter's id is at most {MAX_NAME} characters SVG फ़िल्टर की id अधिकतम {MAX_NAME} वर्णों की होती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..6caee13e40 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6845,6 +6845,7 @@ variable-list-end {0}, {1} {0} és {1} @msg a 3D effect on a group's fill or stroke draws nothing a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmit @msg a 3D effect on a group's fill or stroke draws nothing to export a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmi exportálhatót @msg The 3D object is too complex to export A 3D objektum túl összetett az exportáláshoz +@msg The 3D object's mesh is incomplete or holds a value that is not a number A 3D objektum hálója hiányos, vagy olyan értéket tartalmaz, amely nem szám @msg the element needs an id, the filter's name a elemnek id kell, a szűrő neve @msg an SVG filter's id is at most {MAX_NAME} characters egy SVG-szűrő id-je legfeljebb {MAX_NAME} karakter @msg <{_1}> isn't an element of an SVG filter a(z) <{_1}> nem SVG-szűrő eleme diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4f2d3f71de 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -311,6 +311,7 @@ @msg a 3D effect on a group's fill or stroke draws nothing efek 3D pada isian atau goresan grup tidak menggambar apa pun @msg a 3D effect on a group's fill or stroke draws nothing to export efek 3D pada isian atau goresan grup tidak menggambar apa pun untuk diekspor @msg The 3D object is too complex to export Objek 3D terlalu rumit untuk diekspor +@msg The 3D object's mesh is incomplete or holds a value that is not a number Objek 3D memiliki mesh yang tidak lengkap atau berisi nilai yang bukan angka @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objek tidak memiliki efek 3D (Ekstrusi & bevel, Revolusi, Gelembungkan, atau Putar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` harus berupa objek yang hanya berisi `mode`, bernilai shaded atau wireframe @msg its 3D effect builds no solid efek 3D-nya tidak membangun bentuk padat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..eeaae620f1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6474,6 +6474,7 @@ lighting Light Luce @msg a 3D effect on a group's fill or stroke draws nothing un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla @msg a 3D effect on a group's fill or stroke draws nothing to export un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla da esportare @msg The 3D object is too complex to export L'oggetto 3D è troppo complesso per essere esportato +@msg The 3D object's mesh is incomplete or holds a value that is not a number La mesh dell'oggetto 3D è incompleta o contiene un valore che non è un numero @msg the element needs an id, the filter's name l'elemento richiede un id, il nome del filtro @msg an SVG filter's id is at most {MAX_NAME} characters l'id di un filtro SVG ha al massimo {MAX_NAME} caratteri @msg <{_1}> isn't an element of an SVG filter <{_1}> non è un elemento di un filtro SVG diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..89218ca5bf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6523,6 +6523,7 @@ lighting Light ライト @msg a 3D effect on a group's fill or stroke draws nothing グループの塗りまたは線にある 3D 効果は何も描画しません @msg a 3D effect on a group's fill or stroke draws nothing to export グループの塗りまたは線にある 3D 効果には書き出せる描画がありません @msg The 3D object is too complex to export 3D オブジェクトが複雑すぎるため書き出せません +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D オブジェクトのメッシュが不完全か、数値でない値を含んでいます @msg the element needs an id, the filter's name 要素には id (フィルターの名前) が必要です @msg an SVG filter's id is at most {MAX_NAME} characters SVG フィルターの id は {MAX_NAME} 文字までです @msg <{_1}> isn't an element of an SVG filter <{_1}> は SVG フィルターの要素ではありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..e41a0119b6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8198,6 +8198,7 @@ arrowhead Feather ბუმბული @msg a 3D effect on a group's fill or stroke draws nothing ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი არაფერს ხატავს @msg a 3D effect on a group's fill or stroke draws nothing to export ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი ექსპორტისთვის არაფერს ხატავს @msg The 3D object is too complex to export 3D ობიექტი ზედმეტად რთულია ექსპორტისთვის +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D ობიექტის ბადე არასრულია ან შეიცავს მნიშვნელობას, რომელიც რიცხვი არ არის @msg feConvolveMatrix's order feConvolveMatrix-ის order @msg feMorphology's radius feMorphology-ის radius @msg a blur's stdDeviation გაბუნდოვნების stdDeviation diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..dfb2913999 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6444,6 +6444,7 @@ lighting Light 광원 @msg a 3D effect on a group's fill or stroke draws nothing 그룹의 칠이나 획에 있는 3D 효과는 아무것도 그리지 않습니다 @msg a 3D effect on a group's fill or stroke draws nothing to export 그룹의 칠이나 획에 있는 3D 효과는 내보낼 것을 그리지 않습니다 @msg The 3D object is too complex to export 3D 개체가 너무 복잡하여 내보낼 수 없습니다 +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D 개체의 메시가 불완전하거나 숫자가 아닌 값을 포함합니다 @msg the element needs an id, the filter's name 요소에는 필터 이름인 id가 필요합니다 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 필터의 id는 최대 {MAX_NAME}자입니다 @msg <{_1}> isn't an element of an SVG filter <{_1}>은(는) SVG 필터의 요소가 아닙니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..5a2b732600 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8608,6 +8608,7 @@ mark-style Japanese Japans @msg a 3D effect on a group's fill or stroke draws nothing een 3D-effect op de vulling of contour van een groep tekent niets @msg a 3D effect on a group's fill or stroke draws nothing to export een 3D-effect op de vulling of contour van een groep tekent niets om te exporteren @msg The 3D object is too complex to export Het 3D-object is te complex om te exporteren +@msg The 3D object's mesh is incomplete or holds a value that is not a number Het net van het 3D-object is onvolledig of bevat een waarde die geen getal is @msg the element needs an id, the filter's name het -element heeft een id nodig, de naam van het filter @msg an SVG filter's id is at most {MAX_NAME} characters de id van een SVG-filter is hoogstens {MAX_NAME} tekens lang @msg <{_1}> isn't an element of an SVG filter <{_1}> is geen element van een SVG-filter diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..81851f0615 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6686,6 +6686,7 @@ mark-style Japanese Japońskie @msg a 3D effect on a group's fill or stroke draws nothing efekt 3D na wypełnieniu lub obrysie grupy niczego nie rysuje @msg a 3D effect on a group's fill or stroke draws nothing to export efekt 3D na wypełnieniu lub obrysie grupy nie rysuje niczego do eksportu @msg The 3D object is too complex to export Obiekt 3D jest zbyt złożony, aby go wyeksportować +@msg The 3D object's mesh is incomplete or holds a value that is not a number Siatka obiektu 3D jest niekompletna lub zawiera wartość, która nie jest liczbą @msg the element needs an id, the filter's name element wymaga id, czyli nazwy filtra @msg an SVG filter's id is at most {MAX_NAME} characters id filtra SVG ma najwyżej {MAX_NAME} znaków @msg <{_1}> isn't an element of an SVG filter <{_1}> nie jest elementem filtra SVG diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..cee5fae3aa 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6808,6 +6808,7 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing um efeito 3D no preenchimento ou traçado de um grupo não desenha nada @msg a 3D effect on a group's fill or stroke draws nothing to export um efeito 3D no preenchimento ou traçado de um grupo não desenha nada para exportar @msg The 3D object is too complex to export O objeto 3D é complexo demais para ser exportado +@msg The 3D object's mesh is incomplete or holds a value that is not a number A malha do objeto 3D está incompleta ou contém um valor que não é um número @msg the element needs an id, the filter's name o elemento precisa de um id, o nome do filtro @msg an SVG filter's id is at most {MAX_NAME} characters o id de um filtro SVG tem no máximo {MAX_NAME} caracteres @msg <{_1}> isn't an element of an SVG filter <{_1}> não é um elemento de filtro SVG diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..2f72bcfb4d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6471,6 +6471,7 @@ lighting Light Свет @msg a 3D effect on a group's fill or stroke draws nothing 3D-эффект на заливке или обводке группы ничего не рисует @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-эффект на заливке или обводке группы не рисует ничего для экспорта @msg The 3D object is too complex to export 3D-объект слишком сложен для экспорта +@msg The 3D object's mesh is incomplete or holds a value that is not a number Сетка 3D-объекта неполна или содержит значение, которое не является числом @msg the element needs an id, the filter's name элементу нужен id, имя фильтра @msg an SVG filter's id is at most {MAX_NAME} characters id фильтра SVG содержит не более {MAX_NAME} символов @msg <{_1}> isn't an element of an SVG filter <{_1}> не является элементом фильтра SVG diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..480faf82a3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6337,6 +6337,7 @@ lighting Light Ljus @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en grupps fyllning eller linje ritar ingenting @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en grupps fyllning eller linje ritar ingenting att exportera @msg The 3D object is too complex to export 3D-objektet är för komplext för att exporteras +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektets nät är ofullständigt eller innehåller ett värde som inte är ett tal @msg give one element ange ett -element @msg the element needs an id, the filter's name -elementet behöver ett id, filtrets namn @msg an SVG filter's id is at most {MAX_NAME} characters ett SVG-filters id har högst {MAX_NAME} tecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..0ec642e48f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6164,6 +6164,7 @@ lighting Light Işık @msg a 3D effect on a group's fill or stroke draws nothing bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt hiçbir şey çizmez @msg a 3D effect on a group's fill or stroke draws nothing to export bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt dışa aktarılacak hiçbir şey çizmez @msg The 3D object is too complex to export 3 boyutlu nesne dışa aktarmak için çok karmaşık +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3 boyutlu nesnenin ağı eksik veya sayı olmayan bir değer içeriyor @msg the element needs an id, the filter's name öğesinin, filtrenin adı olan bir id değeri olmalıdır @msg an SVG filter's id is at most {MAX_NAME} characters bir SVG filtresinin id değeri en fazla {MAX_NAME} karakterdir @msg <{_1}> isn't an element of an SVG filter <{_1}> bir SVG filtresi öğesi değildir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..9d684ea4a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6454,6 +6454,7 @@ lighting Light Світло @msg a 3D effect on a group's fill or stroke draws nothing 3D-ефект на заливці або обведенні групи нічого не малює @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-ефект на заливці або обведенні групи не малює нічого для експорту @msg The 3D object is too complex to export 3D-об’єкт надто складний для експорту +@msg The 3D object's mesh is incomplete or holds a value that is not a number Сітка 3D-об’єкта неповна або містить значення, яке не є числом @msg the element needs an id, the filter's name елементу потрібен id, назва фільтра @msg an SVG filter's id is at most {MAX_NAME} characters id фільтра SVG містить не більше {MAX_NAME} символів @msg <{_1}> isn't an element of an SVG filter <{_1}> не є елементом фільтра SVG diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..45fab60c7b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6205,6 +6205,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg a 3D effect on a group's fill or stroke draws nothing hiệu ứng 3D trên phần tô hoặc nét của nhóm không vẽ gì @msg a 3D effect on a group's fill or stroke draws nothing to export hiệu ứng 3D trên phần tô hoặc nét của nhóm không vẽ gì để xuất @msg The 3D object is too complex to export Đối tượng 3D quá phức tạp để xuất +@msg The 3D object's mesh is incomplete or holds a value that is not a number Lưới của đối tượng 3D chưa đầy đủ hoặc chứa giá trị không phải là số @msg give one element hãy chỉ định một phần tử @msg the element needs an id, the filter's name phần tử cần có id, là tên của bộ lọc @msg an SVG filter's id is at most {MAX_NAME} characters id của bộ lọc SVG có tối đa {MAX_NAME} ký tự diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..d10f494a61 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6723,6 +6723,7 @@ lighting Light 光源 @msg a 3D effect on a group's fill or stroke draws nothing 编组填色或描边上的 3D 效果不绘制任何内容 @msg a 3D effect on a group's fill or stroke draws nothing to export 编组填色或描边上的 3D 效果没有可导出的内容 @msg The 3D object is too complex to export 3D 对象过于复杂,无法导出 +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D 对象的网格不完整,或含有非数字的值 @msg the element needs an id, the filter's name 元素需要 id,即滤镜的名称 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 滤镜的 id 最多 {MAX_NAME} 个字符 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 滤镜的元素 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..fa9a5b7d81 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6572,6 +6572,7 @@ lighting Light 光源 @msg a 3D effect on a group's fill or stroke draws nothing 群組填色或筆畫上的 3D 效果不會繪製任何內容 @msg a 3D effect on a group's fill or stroke draws nothing to export 群組填色或筆畫上的 3D 效果沒有可匯出的內容 @msg The 3D object is too complex to export 3D 物件過於複雜,無法匯出 +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D 物件的網格不完整,或含有非數字的值 @msg the element needs an id, the filter's name 元素需要 id,也就是濾鏡的名稱 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 濾鏡的 id 最多 {MAX_NAME} 個字元 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 濾鏡的元素 diff --git a/docs/effects-parity.md b/docs/effects-parity.md index a3ba859915..f5f0dea3e1 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes and the custom bevels with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit, and the graphics on Revolve's side as a texture of the side unrolled; every corner carries texture coordinates and a normal, smoothed across a curved bevel and over Inflate's puff ([three-d.md](three-d.md#3d-meshes)); no materials and no lighting ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..5cc001c03a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10678,7 +10678,13 @@ fill's, each stroke's, a group's members') is its own mesh, with a two-sided mat (a gradient's stops averaged, a pattern gray); a solid with mapped graphics is split into a textured mesh for each face that carries them and a plain mesh for the rest, as described below. The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns -about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. +about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Each corner's normal is its face's, except +where two bands of one bevel meet at a turn of less than 60° (neither band lying flat toward the front or back) and on +Inflate's puffed front and back: there the normals are smoothed, and an app that reads them shades a rounded bevel or a +puff without facets ([three-d.md](three-d.md#3d-meshes)). Every corner also has texture coordinates from 0 to 1 +(`vt`, `TEXCOORD_0`, `primvars:st`), laid out for each kind of face as three-d.md describes. A mesh whose lists do not +match, or that holds a value that is not a number, stops the export with "The 3D object's mesh is incomplete or holds a +value that is not a number", and nothing is written. Files that would share a name get `-2`, `-3` and so on. Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..488b9b4b36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1690,6 +1690,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. + - The meshes of Extrude & Bevel, Inflate, Rotate and Revolve carry texture coordinates for every corner, normals smoothed across the bands of a curved bevel (a turn of 60° or more stays a hard edge, VectorCraft's own value) and over Inflate's puff, and a part for each triangle (front, back, side, front bevel, back bevel, end cap, cut side); exported OBJ, glTF and USD files write the new normals and every corner's texture coordinates, refuse a mesh whose lists do not match or hold a value that is not a number, and the vector facets stay the same bit for bit ([three-d.md](three-d.md#3d-meshes)). Tests `mesh::tests_attributes::every_corner_has_texture_coordinates_and_every_triangle_a_part`, `a_rounded_or_custom_bevels_normals_turn_smoothly_across_its_bands`, `a_steps_sharp_turns_and_a_classic_bevel_stay_hard_edges`, `the_meshs_outline_stays_within_a_twentieth_of_a_point_of_the_vector_facets`, `mesh3d::tests::a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. - The 3D and Materials panel works out whether Export 3D Object is available once for each document revision and reuses it on later frames. The button shows the same state. With 200,000 paths selected, working it out on every frame took a median 61.6 ms of thread CPU time per frame in a release build on Linux (57.1 ms with a path of a compound path with Extrude & Bevel selected last); the first frame after a change still takes about as long, and later frames take about 2 ns (`panels::three_d::tests::export_3d_object_state_kept_for_a_revision_equals_a_fresh_one`, `export_3d_object_state_is_worked_out_once_per_revision`, `export_3d_object_state_timing`). - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. diff --git a/docs/three-d.md b/docs/three-d.md index 2327eb1c24..afbbb2a996 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -95,6 +95,37 @@ pages describe it. rotation and light rings on the artboard are part of the options dialog only. The panel's Lighting tab has the lighting widget instead ([Lighting widget](#lighting-widget)). +## 3D meshes + +The meshes that Export 3D Object writes come from the `three-d` crate's `Mesh`, built from the same faces the effect +draws. The vector facets on the canvas and in SVG and PDF do not change with what follows. Besides positions, +normals and triangles, a mesh carries: + +- **Normals.** A corner takes its face's normal. Where two bands of one bevel meet, the shared corners take the mean of + the two bands' normals, unless the bevel turns there by 60° or more (a Step profile's turns) or one of the bands lies + flat toward the front or back; caps, walls and the edges between a bevel and a cap or wall stay hard. On Inflate's + puffed front and back each corner takes the surface's own normal. The bevel settings shape its profile into a + rounded curve or an ornamental one ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)); + the smoothing rule and the 60° crease are VectorCraft's own. +- **Texture coordinates** for every corner, each from 0 to 1, u to the right and v down, as glTF 2.0 places + `TEXCOORD_0` (). Caps, Rotate's plane and Inflate's + front and back take each corner's art point, before any twist or taper, in the art's bounds; the back is not + mirrored. Extrude & Bevel's bevels and walls and Inflate's walls take u along each contour of the outline from its + first point, as the distance over the contour's length, so the seam at the first point has corners at both 0 and 1, + and v across the side from the front cap's edge to the back cap's. Revolve's side takes u around the sweep from its + start and v along each contour of the profile; its end caps span the disk they close, and its cut sides take each + corner's profile point in the profile's bounds. An axis with no extent takes 0.5. These layouts are VectorCraft's + own. +- **A part for each triangle**: `Front` (a front cap, Rotate's plane, Inflate's front), `Back`, `Side` (walls and + Revolve's swept side), `FrontBevel`, `BackBevel`, `Cap` (Revolve's end caps) and `Cut` (the flat sides of a Revolve + of less than 360°). + +The exported files write the normals and the texture coordinates of every corner: OBJ's `vt` (up from the bottom), +glTF's `TEXCOORD_0` and USD's `primvars:st` (up from the bottom). A face with mapped graphics writes the coordinates +of its texture instead, laid out as the graphics are ([Graphics](#graphics)). The files do not write the parts. A +mesh whose lists do not match, or that holds a value that is not a number, stops the export with an error before any +file is written. + ## Extrude & Bevel The art is the front face; its outline is extruded backwards by **Depth** (0–2,000 pt), so seen straight on the From 1ab09c8978191fd1f64c3c50e2db5df30168ddf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:56:57 -0800 Subject: [PATCH 037/126] Scripts: UnitValue measurements convert and calculate with their units Scripts get the global UnitValue constructor: a number with one of the length units (inches, feet, yards, miles, millimeters, centimeters, meters, kilometers, points, picas, traditional points and picas, ciceros), pixels or percent. as() and convert() give or change the unit, baseUnit sets what one pixel and 100% measure, and the arithmetic, comparison and unary operators calculate with the object's number. With two objects the right one is converted to the left one's unit. Conversions go through exact ratios to the inch, so 1 in is exactly 72 pt. An unknown unit or text makes an invalid object; converting it or using it with an operator, a result that is not finite and a comparison with a number that is not finite throw a RangeError. A realm without UnitValue keeps the standard operators. docs/mcp.md describes the class. --- crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests/script_dollar.rs | 13 +- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/js/src/heap.rs | 6 + crates/js/src/interp.rs | 16 + crates/js/src/lib.rs | 3 + crates/js/src/realm.rs | 11 + crates/js/src/unit_value.rs | 522 ++++++++++++++++++ crates/js/src/unit_value_tests.rs | 359 ++++++++++++ docs/mcp.md | 21 + docs/target-app-parity.md | 1 + 11 files changed, 954 insertions(+), 3 deletions(-) create mode 100644 crates/js/src/unit_value.rs create mode 100644 crates/js/src/unit_value_tests.rs diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..378b41b9b7 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2073,6 +2073,7 @@ impl Session { })); } (if fresh { realm.add_script_extensions() } else { Ok(()) }) + .and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index 849d5b9080..bef2cf5c93 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -1,5 +1,5 @@ -//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and -//! `toSource`, and what of them one run keeps to itself. +//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize`, `toSource` +//! and `UnitValue`, and what of them one run keeps to itself. use std::time::Duration; @@ -140,6 +140,15 @@ fn to_source_writes_plain_data() { assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data"); } +#[test] +fn unit_values_convert_and_calculate_in_a_run() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "UnitValue('1 in').as('pt')"), json!(72)); + assert_eq!(value(&mut s, "String(new UnitValue(1, 'm') + new UnitValue(10, 'cm'))"), json!("1.1 m")); + assert_eq!(value(&mut s, "[UnitValue(98, 'cm') < UnitValue(1, 'm'), UnitValue(98, 'cm') == 98]"), json!([true, true])); + assert!(thrown(&mut s, "UnitValue(1, 'in').as('furlong')").starts_with("Error")); +} + #[test] fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { let mut s = Session::new(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..52aa59e27d 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -43,8 +43,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), + ("UnitValue.", "baseUnit baseUnit= length prototype"), + ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..60362f0c90 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A `UnitValue` object and its measurement ([`crate::unit_value`]). + UnitValue(Box), } /// What an XML value is. @@ -322,6 +324,7 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::UnitValue(_) => "UnitValue", } } } @@ -395,6 +398,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96; pub(crate) const XML_REF_BYTES: usize = 8; /// The estimated bytes of a namespace an XML node holds. pub(crate) const XML_NS_BYTES: usize = 48; +/// The estimated bytes of the measurement a `UnitValue` object holds. +pub(crate) const UNIT_VALUE_BYTES: usize = 32; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -680,6 +685,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..315788b7c7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the + /// operators take no object as a measurement. + pub(crate) unit_values: Option, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. @@ -518,6 +521,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + unit_values: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,6 +778,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -2873,6 +2878,11 @@ impl Interp { fn op_unary(&mut self, op: Op) -> JsResult<()> { let v = self.peek(0)?; + if self.unit_values.is_some() + && let Some(r) = crate::unit_value::unary(self, op, &v)? + { + return self.replace(1, r); + } let r = match op { Op::Neg => Value::Number(-self.to_number(&v)?), Op::Plus | Op::ToNumber => Value::Number(self.to_number(&v)?), @@ -2892,6 +2902,12 @@ impl Interp { } pub(crate) fn binary(&mut self, op: BinaryOp, a: &Value, b: &Value) -> JsResult { + if self.unit_values.is_some() + && (matches!(a, Value::Object(_)) || matches!(b, Value::Object(_))) + && let Some(r) = crate::unit_value::binary(self, op, a, b)? + { + return Ok(r); + } let num = |interp: &mut Self, f: fn(f64, f64) -> f64| -> JsResult { let x = interp.to_number(a)?; let y = interp.to_number(b)?; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c0acf50e37 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -69,6 +69,7 @@ mod regexp_builtins; mod regexp_vm; mod string_builtins; mod token; +mod unit_value; mod value; mod xml; mod xml_builtins; @@ -213,4 +214,6 @@ mod tests; #[cfg(test)] mod text_tests; #[cfg(test)] +mod unit_value_tests; +#[cfg(test)] mod xml_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..52ddea823b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -529,6 +529,17 @@ impl Realm { } } + /// Adds the global constructor `UnitValue`, measurements with a magnitude and a unit, and has + /// the arithmetic, comparison and unary operators calculate with its objects + /// ([`crate::unit_value`]). A realm without it keeps the standard operators. A second call + /// changes nothing. + pub fn add_unit_values(&mut self) -> Result<(), RunError> { + match crate::unit_value::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Defines the global function `name`, whose arguments arrive converted as `args` says /// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as /// it may a built-in function. diff --git a/crates/js/src/unit_value.rs b/crates/js/src/unit_value.rs new file mode 100644 index 0000000000..03a33ab3e6 --- /dev/null +++ b/crates/js/src/unit_value.rs @@ -0,0 +1,522 @@ +//! `UnitValue`, the measurement class the help page +//! +//! describes, added to a realm by [`crate::Realm::add_unit_values`]. +//! +//! An object holds a magnitude, a unit and the base that pixels and percentages convert through. +//! The length units convert through exact ratios to the inch; a pixel is one base and 100% is one +//! base. The base is an absolute length greater than 0, copied into each new object from +//! `UnitValue.baseUnit` (1 point, which is 1/72 inch, until a script sets it), and an object's own `baseUnit` may +//! replace it. A unit the table does not list, text that is not a number followed by a unit, and a +//! magnitude that is not finite make an invalid object: its `type` is `?`, its `value` 0, and it +//! cannot be converted or calculated with. +//! +//! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and +//! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in +//! its unit; with two, the right one is converted to the left one's unit first and the result is in +//! the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the +//! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its +//! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not +//! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all +//! operators in a realm without `UnitValue`. A calculation whose result is not finite (a division +//! by 0 included), a comparison with a number that is not finite, and a conversion of an invalid +//! object or any of these operators applied to one throw a `RangeError`; a unit the table does not list throws an +//! `Error`. + +use crate::ast::BinaryOp; +use crate::builtins::{arg, constructor, method, native}; +use crate::bytecode::Op; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, Prop, UNIT_VALUE_BYTES, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::{Value, is_str_space, number_to_str, string_to_number, to_int32}; + +/// The units of the table, in its order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Unit { + In, + Ft, + Yd, + Mi, + Mm, + Cm, + M, + Km, + Pt, + Pc, + Tpt, + Tpc, + Ci, + Px, + Percent, +} + +/// Each unit with its abbreviation, singular and plural names, and its length in inches as a ratio +/// (0 for the units that convert through the base). +const UNITS: [(Unit, &str, &str, &str, u64, u64); 15] = [ + (Unit::In, "in", "inch", "inches", 1, 1), + (Unit::Ft, "ft", "foot", "feet", 12, 1), + (Unit::Yd, "yd", "yard", "yards", 36, 1), + (Unit::Mi, "mi", "mile", "miles", 63_360, 1), + (Unit::Mm, "mm", "millimeter", "millimeters", 5, 127), + (Unit::Cm, "cm", "centimeter", "centimeters", 50, 127), + (Unit::M, "m", "meter", "meters", 5_000, 127), + (Unit::Km, "km", "kilometer", "kilometers", 5_000_000, 127), + (Unit::Pt, "pt", "point", "points", 1, 72), + (Unit::Pc, "pc", "pica", "picas", 1, 6), + (Unit::Tpt, "tpt", "traditional point", "traditional points", 100, 7_227), + (Unit::Tpc, "tpc", "traditional pica", "traditional picas", 1_200, 7_227), + (Unit::Ci, "ci", "cicero", "ciceros", 111, 625), + (Unit::Px, "px", "pixel", "pixels", 0, 0), + (Unit::Percent, "%", "percent", "percent", 0, 0), +]; + +/// The longest unit name in the table, in code units. +const LONGEST_NAME: usize = 18; + +/// The longest text the constructor reads as a magnitude and a unit, in code units; longer text +/// makes an invalid object without being read. +const LONGEST_TEXT: usize = 64; + +impl Unit { + fn row(self) -> Option<&'static (Unit, &'static str, &'static str, &'static str, u64, u64)> { + UNITS.iter().find(|row| row.0 == self) + } + + fn abbreviation(self) -> &'static str { + self.row().map_or("?", |row| row.1) + } + + /// The unit's length in inches as a ratio, `None` for pixels and percentages. + fn inches(self) -> Option<(u64, u64)> { + let &(_, _, _, _, n, d) = self.row()?; + (n != 0).then_some((n, d)) + } + + /// The unit with this abbreviation, singular or plural name. + fn named(units: &[u16]) -> Option { + if units.is_empty() || units.len() > LONGEST_NAME { + return None; + } + let name = String::from_utf16(units).ok()?; + UNITS.iter().find(|(_, a, s, p, _, _)| name == *a || name == *s || name == *p).map(|row| row.0) + } +} + +/// The length that pixels and percentages convert through: a finite magnitude greater than 0 in a +/// unit with a length. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Base { + value: f64, + unit: Unit, +} + +/// 1/72 inch, kept as 1 point so that conversions through it are exact. +const DEFAULT_BASE: Base = Base { value: 1.0, unit: Unit::Pt }; + +/// What a `UnitValue` object holds. `unit` is `None` for an invalid object. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Measure { + value: f64, + unit: Option, + base: Base, +} + +/// The prototype of `UnitValue` objects and the current `UnitValue.baseUnit`, kept by the realm. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + proto: ObjId, + base: Base, +} + +impl Classes { + /// The object a collection keeps. + pub(crate) fn object(&self) -> ObjId { + self.proto + } +} + +fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a +} + +/// `value` in unit `from`, given in unit `to`; both have a length. +fn between(value: f64, from: (u64, u64), to: (u64, u64)) -> f64 { + // The products stay below 2^53, so the ratio's terms are exact. + let (n, d) = (from.0 * to.1, from.1 * to.0); + let g = greatest_common_divisor(n, d).max(1); + #[allow(clippy::cast_precision_loss)] + let (n, d) = ((n / g) as f64, (d / g) as f64); + let scaled = value * n; + // A large value is divided first, so a result that is finite does not overflow on the way. + if scaled.is_finite() { scaled / d } else { value / d * n } +} + +fn invalid(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: an invalid UnitValue cannot be converted or calculated with")) +} + +fn finite_value(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the value must be a finite number")) +} + +fn not_finite(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the result is not a finite number")) +} + +/// The magnitude of `m` in unit `to`, through `m`'s own base. +fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult { + let Some(from) = m.unit else { + return Err(invalid(i, what)); + }; + let base = m.base; + let base_inches = base.unit.inches().unwrap_or((1, 1)); + let r = match (from, to) { + (a, b) if a == b => m.value, + (Unit::Px, Unit::Percent) => m.value * 100.0, + (Unit::Percent, Unit::Px) => m.value / 100.0, + (Unit::Px | Unit::Percent, _) => { + let to = to.inches().unwrap_or((1, 1)); + let bases = if from == Unit::Px { m.value } else { m.value / 100.0 }; + // A large base is applied after the unit ratio, so a result that is finite does not + // overflow on the way. + let scaled = bases * base.value; + if scaled.is_finite() { between(scaled, base_inches, to) } else { between(bases, base_inches, to) * base.value } + } + (_, Unit::Px | Unit::Percent) => { + let from = from.inches().unwrap_or((1, 1)); + let lengths = between(m.value, from, base_inches); + let bases = if lengths.is_finite() { lengths / base.value } else { between(m.value / base.value, from, base_inches) }; + if to == Unit::Px { bases } else { bases * 100.0 } + } + (_, _) => between(m.value, from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))), + }; + if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) } +} + +/// The measure of `v` when it is a `UnitValue` object. +pub(crate) fn measure(i: &Interp, v: &Value) -> Option { + let o = v.as_object()?; + match &i.heap.object(o)?.class { + Class::UnitValue(m) => Some(**m), + _ => None, + } +} + +fn this_measure(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Measure)> { + if let (Some(o), Some(m)) = (this.as_object(), measure(i, this)) { + return Ok((o, m)); + } + Err(i.type_error(&format!("{what}: the object is not a UnitValue"))) +} + +fn store(i: &mut Interp, o: ObjId, m: Measure) { + if let Some(obj) = i.heap.object_mut(o) + && let Class::UnitValue(slot) = &mut obj.class + { + **slot = m; + } +} + +fn classes(i: &Interp) -> JsResult { + i.unit_values.clone().ok_or_else(|| Abrupt::Internal("UnitValue is not installed".into())) +} + +/// A new `UnitValue` object holding `m`. +fn make(i: &mut Interp, m: Measure) -> JsResult { + let proto = classes(i)?.proto; + i.reserve_heap(OBJECT_BYTES + UNIT_VALUE_BYTES)?; + i.heap.bytes = i.heap.bytes.saturating_add(UNIT_VALUE_BYTES); + Ok(Value::Object(i.heap.alloc_object(Object::new(Class::UnitValue(Box::new(m)), Some(proto))))) +} + +/// The unit `v` names, or an `Error` naming `what`. +fn unit_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) }; + unit.ok_or_else(|| i.throw(ErrorType::Error, &format!("{what}: the unit is not known"))) +} + +/// A magnitude followed by a unit, with spaces around and between them allowed: `12 pt`, +/// `-1.5e2 traditional points`, `10%`. +fn parse_text(units: &[u16]) -> Option<(f64, Unit)> { + let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len()); + let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |e| e + 1); + let text = units.get(start..end)?; + let digit = |u: u16| (u16::from(b'0')..=u16::from(b'9')).contains(&u); + let at = |k: usize| text.get(k).copied().unwrap_or(0); + let mut k = 0; + if at(k) == u16::from(b'+') || at(k) == u16::from(b'-') { + k += 1; + } + let mut digits = 0; + while digit(at(k)) { + k += 1; + digits += 1; + } + if at(k) == u16::from(b'.') { + k += 1; + while digit(at(k)) { + k += 1; + digits += 1; + } + } + if digits == 0 { + return None; + } + if at(k) == u16::from(b'e') || at(k) == u16::from(b'E') { + let mut e = k + 1; + if at(e) == u16::from(b'+') || at(e) == u16::from(b'-') { + e += 1; + } + if digit(at(e)) { + while digit(at(e)) { + e += 1; + } + k = e; + } + } + let (number, rest) = text.split_at_checked(k)?; + let value = string_to_number(number); + let u = rest.iter().position(|&u| !is_str_space(u)).unwrap_or(rest.len()); + let unit = Unit::named(rest.get(u..)?)?; + value.is_finite().then_some((value, unit)) +} + +/// `new UnitValue(value, unit)`, `new UnitValue("value unit")`, `new UnitValue(unitValue)` and the +/// same without `new`. +fn unit_value_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let base = classes(i)?.base; + let bad = Measure { value: 0.0, unit: None, base }; + let first = arg(args, 0); + let m = if args.len() >= 2 { + let value = i.to_number(&first)?; + let s = i.to_str(&arg(args, 1))?; + let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) }; + match unit { + Some(unit) if value.is_finite() => Measure { value, unit: Some(unit), base }, + _ => bad, + } + } else if let Some(m) = measure(i, &first) { + m + } else if matches!(first, Value::Undefined | Value::Number(_)) { + bad + } else { + let s = i.to_str(&first)?; + match if s.len() > LONGEST_TEXT { None } else { parse_text(&s.flat()) } { + Some((value, unit)) => Measure { value, unit: Some(unit), base }, + None => bad, + } + }; + make(i, m) +} + +fn get_value(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.value")?; + Ok(Value::Number(m.value)) +} + +fn set_value(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_measure(i, &this, "UnitValue.value")?; + let value = i.to_number(&arg(args, 0))?; + if !value.is_finite() { + return Err(finite_value(i, "UnitValue.value")); + } + // The conversion may have run script code that changed the object, so it is read again. + let (_, mut m) = this_measure(i, &this, "UnitValue.value")?; + m.value = value; + store(i, o, m); + Ok(Value::Undefined) +} + +fn get_type(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.type")?; + Ok(Value::str(m.unit.map_or("?", Unit::abbreviation))) +} + +fn set_type(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_measure(i, &this, "UnitValue.type")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.type")?; + let (_, mut m) = this_measure(i, &this, "UnitValue.type")?; + m.unit = Some(unit); + store(i, o, m); + Ok(Value::Undefined) +} + +/// The base `v` gives: `null` gives the default, and any other value must be a valid `UnitValue` +/// with a length greater than 0. +fn base_arg(i: &mut Interp, v: &Value, null: Base, what: &str) -> JsResult { + if matches!(v, Value::Null) { + return Ok(null); + } + match measure(i, v) { + Some(Measure { value, unit: Some(unit), .. }) if unit.inches().is_some() && value.is_finite() && value > 0.0 => Ok(Base { value, unit }), + _ => Err(i.throw(ErrorType::Range, &format!("{what}: the base must be null or a UnitValue of a length greater than 0"))), + } +} + +fn base_object(i: &mut Interp, base: Base) -> JsResult { + let class = classes(i)?.base; + make(i, Measure { value: base.value, unit: Some(base.unit), base: class }) +} + +fn get_base(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.baseUnit")?; + base_object(i, m.base) +} + +fn set_base(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, mut m) = this_measure(i, &this, "UnitValue.baseUnit")?; + let class = classes(i)?.base; + m.base = base_arg(i, &arg(args, 0), class, "UnitValue.baseUnit")?; + store(i, o, m); + Ok(Value::Undefined) +} + +fn get_class_base(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let base = classes(i)?.base; + base_object(i, base) +} + +fn set_class_base(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let base = base_arg(i, &arg(args, 0), DEFAULT_BASE, "UnitValue.baseUnit")?; + if let Some(c) = i.unit_values.as_mut() { + c.base = base; + } + Ok(Value::Undefined) +} + +/// `unitValue.as(unit)`: the magnitude in `unit`, leaving the object as it is. +fn unit_as(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_measure(i, &this, "UnitValue.as")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.as")?; + let (_, m) = this_measure(i, &this, "UnitValue.as")?; + convert(i, &m, unit, "UnitValue.as").map(Value::Number) +} + +/// `unitValue.convert(unit)`: changes the object to `unit` and gives `true`. A failure throws and +/// leaves the object as it was. +fn unit_convert(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_measure(i, &this, "UnitValue.convert")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.convert")?; + let (o, mut m) = this_measure(i, &this, "UnitValue.convert")?; + m.value = convert(i, &m, unit, "UnitValue.convert")?; + m.unit = Some(unit); + store(i, o, m); + Ok(Value::Bool(true)) +} + +/// `unitValue.toString()`: the magnitude and the abbreviation, `12 pt`; an invalid object gives +/// `UnitValue 0.00000`. +fn unit_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.toString")?; + Ok(Value::str(&match m.unit { + Some(unit) => format!("{} {}", number_to_str(m.value).to_rust_string(), unit.abbreviation()), + None => format!("UnitValue {:.5}", m.value), + })) +} + +/// Defines the accessor `name` on `on`, not enumerable. +fn accessor(i: &mut Interp, on: ObjId, name: &'static str, get: NativeFn, set: NativeFn) -> JsResult<()> { + let g = native(i, name, get, 0, NativeKind::Plain, false)?; + i.rooted(&[Value::Object(g)], |i| { + let s = native(i, name, set, 1, NativeKind::Plain, false)?; + i.define(on, key(name), Prop::Accessor { get: Some(g), set: Some(s), flags: CONFIGURABLE }) + }) +} + +/// Adds the global constructor `UnitValue` ([`crate::Realm::add_unit_values`]). A second call +/// changes nothing. +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + if i.unit_values.is_some() { + return Ok(()); + } + let object_proto = i.intrinsics.object_proto; + i.reserve_heap(OBJECT_BYTES)?; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.unit_values = Some(Classes { proto, base: DEFAULT_BASE }); + let ctor = native(i, "UnitValue", unit_value_ctor, 2, NativeKind::Plain, true)?; + constructor(i, "UnitValue", ctor, proto)?; + accessor(i, ctor, "baseUnit", get_class_base, set_class_base)?; + accessor(i, proto, "value", get_value, set_value)?; + accessor(i, proto, "type", get_type, set_type)?; + accessor(i, proto, "baseUnit", get_base, set_base)?; + method(i, proto, "as", unit_as, 1)?; + method(i, proto, "convert", unit_convert, 1)?; + method(i, proto, "toString", unit_to_string, 0) +} + +/// Unary `op` on `v` when `v` is a `UnitValue`; `None` otherwise. +pub(crate) fn unary(i: &mut Interp, op: Op, v: &Value) -> JsResult> { + let Some(m) = measure(i, v) else { return Ok(None) }; + if !matches!(op, Op::Neg | Op::Plus | Op::BitNot | Op::Not) { + return Ok(None); + } + if m.unit.is_none() { + return Err(invalid(i, "UnitValue")); + } + Ok(Some(match op { + Op::Neg => Value::Number(-m.value), + Op::Plus => Value::Number(m.value), + Op::BitNot => Value::Number(f64::from(!to_int32(m.value))), + _ => Value::Bool(m.value != 0.0), + })) +} + +/// Binary `op` on `a` and `b` when one is a `UnitValue` and the other a number or a `UnitValue`, +/// for the arithmetic and comparison operators; `None` otherwise. +pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsResult> { + let arithmetic = matches!(op, BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod); + let comparison = matches!(op, BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq | BinaryOp::Eq | BinaryOp::NotEq); + if !arithmetic && !comparison { + return Ok(None); + } + let what = "UnitValue"; + let (x, y, owner) = match (measure(i, a), measure(i, b), a, b) { + (Some(l), Some(r), _, _) => { + let Some(unit) = l.unit else { + return Err(invalid(i, what)); + }; + let y = convert(i, &r, unit, what)?; + (l.value, y, l) + } + (Some(l), None, _, Value::Number(n)) => (l.value, *n, l), + (None, Some(r), Value::Number(n), _) => (*n, r.value, r), + (l, r, _, _) => { + if l.or(r).is_some_and(|m| m.unit.is_none()) { + return Err(invalid(i, what)); + } + return Ok(None); + } + }; + if owner.unit.is_none() { + return Err(invalid(i, what)); + } + if comparison { + if !x.is_finite() || !y.is_finite() { + return Err(finite_value(i, what)); + } + // Without NaN, `x > y` is the negation of `x <= y` and `x >= y` the negation of `x < y`. + return Ok(Some(Value::Bool(match op { + BinaryOp::Lt => x < y, + BinaryOp::LtEq => x <= y, + BinaryOp::Gt => x > y, + BinaryOp::GtEq => x >= y, + BinaryOp::Eq => x == y, + _ => x != y, + }))); + } + // A division by 0 gives an infinite result or NaN, which is refused below. + let r = match op { + BinaryOp::Add => x + y, + BinaryOp::Sub => x - y, + BinaryOp::Mul => x * y, + BinaryOp::Div => x / y, + _ => x % y, + }; + if !r.is_finite() { + return Err(not_finite(i, what)); + } + make(i, Measure { value: r, ..owner }).map(Some) +} diff --git a/crates/js/src/unit_value_tests.rs b/crates/js/src/unit_value_tests.rs new file mode 100644 index 0000000000..6e4f2ee33e --- /dev/null +++ b/crates/js/src/unit_value_tests.rs @@ -0,0 +1,359 @@ +//! `UnitValue` and the operators in a realm that has it. + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_unit_values().unwrap(); + r +} + +fn number(r: &mut Realm, source: &str) -> f64 { + match r.run(source) { + Ok(JsValue::Number(n)) => n, + other => panic!("{source}: {other:?}"), + } +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn boolean(r: &mut Realm, source: &str) -> bool { + match r.run(source) { + Ok(JsValue::Bool(b)) => b, + other => panic!("{source}: {other:?}"), + } +} + +/// The name of the error `statement` throws, or `none`. +fn error_name(r: &mut Realm, statement: &str) -> String { + text(r, &format!("(function () {{ try {{ {statement}; return 'none'; }} catch (e) {{ return e.name; }} }})()")) +} + +fn close(got: f64, want: f64, what: &str) { + assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}"); +} + +/// Each length unit with its length in inches. +const LENGTHS: [(&str, f64); 13] = [ + ("in", 1.0), + ("ft", 12.0), + ("yd", 36.0), + ("mi", 63_360.0), + ("mm", 1.0 / 25.4), + ("cm", 1.0 / 2.54), + ("m", 1.0 / 0.0254), + ("km", 1000.0 / 0.0254), + ("pt", 1.0 / 72.0), + ("pc", 1.0 / 6.0), + ("tpt", 1.0 / 72.27), + ("tpc", 12.0 / 72.27), + ("ci", 12.7872 / 72.0), +]; + +#[test] +fn every_length_unit_converts_to_every_other_and_back() { + let mut r = realm(); + for (from, a) in LENGTHS { + for (to, b) in LENGTHS { + let there = number(&mut r, &format!("UnitValue(3, '{from}').as('{to}')")); + close(there, 3.0 * a / b, &format!("3 {from} in {to}")); + let back = number(&mut r, &format!("UnitValue({there}, '{to}').as('{from}')")); + close(back, 3.0, &format!("3 {from} through {to} and back")); + } + } +} + +#[test] +fn the_table_relations_are_exact() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(1, 'in').as('pt')", 72.0), + ("UnitValue(1, 'ft').as('in')", 12.0), + ("UnitValue(1, 'yd').as('ft')", 3.0), + ("UnitValue(1, 'mi').as('m')", 1609.344), + ("UnitValue(1, 'm').as('cm')", 100.0), + ("UnitValue(1, 'km').as('m')", 1000.0), + ("UnitValue(10, 'mm').as('cm')", 1.0), + ("UnitValue(2.54, 'cm').as('in')", 1.0), + ("UnitValue(1, 'pc').as('pt')", 12.0), + ("UnitValue(1, 'tpc').as('tpt')", 12.0), + ("UnitValue(72.27, 'tpt').as('in')", 1.0), + ("UnitValue(1, 'ci').as('pt')", 12.7872), + ("UnitValue(1, 'in').as('px')", 72.0), + ] { + assert_eq!(number(&mut r, source), want, "{source}"); + } +} + +#[test] +fn units_are_named_by_abbreviation_singular_or_plural() { + let mut r = realm(); + for (name, abbreviation) in [ + ("inch", "in"), + ("inches", "in"), + ("feet", "ft"), + ("millimeter", "mm"), + ("centimeters", "cm"), + ("traditional point", "tpt"), + ("traditional picas", "tpc"), + ("ciceros", "ci"), + ("pixel", "px"), + ("percent", "%"), + ] { + assert_eq!(text(&mut r, &format!("UnitValue(1, '{name}').type")), abbreviation, "{name}"); + assert_eq!(text(&mut r, &format!("UnitValue('2 {name}').type")), abbreviation, "2 {name}"); + } +} + +#[test] +fn the_constructor_takes_a_number_and_unit_text_or_another_unit_value() { + let mut r = realm(); + assert_eq!(text(&mut r, "String(new UnitValue(12, 'pt'))"), "12 pt"); + assert_eq!(text(&mut r, "String(UnitValue('12 cm'))"), "12 cm"); + assert_eq!(text(&mut r, "String(UnitValue(' -1.5e1 centimeters '))"), "-15 cm"); + assert_eq!(text(&mut r, "String(UnitValue('10%'))"), "10 %"); + assert_eq!(text(&mut r, "String(UnitValue('12', 'in'))"), "12 in"); + assert!(boolean(&mut r, "UnitValue(1, 'in') instanceof UnitValue")); + assert_eq!(text(&mut r, "Object.prototype.toString.call(UnitValue(1, 'in'))"), "[object UnitValue]"); + let copy = "var a = UnitValue(5, 'px'); a.baseUnit = UnitValue(1, 'mm'); var b = UnitValue(a); a.value = 1; \ + [a === b, b.value, b.type, b.as('mm')].join()"; + assert_eq!(text(&mut r, copy), "false,5,px,5", "a copy is a new object with the same value, unit and base"); +} + +#[test] +fn an_unknown_unit_or_text_makes_an_invalid_unit_value() { + let mut r = realm(); + for source in [ + "UnitValue(12, 'furlong')", + "UnitValue('12')", + "UnitValue('pt')", + "UnitValue('12 pt extra')", + "UnitValue(12)", + "UnitValue()", + "UnitValue(NaN, 'pt')", + "UnitValue(Infinity, 'pt')", + "UnitValue(12, 'PT')", + ] { + assert_eq!(text(&mut r, &format!("var u = {source}; u.type + ' ' + u.value")), "? 0", "{source}"); + assert_eq!(text(&mut r, &format!("String({source})")), "UnitValue 0.00000", "{source}"); + } + for statement in [ + "UnitValue(1, 'zz').as('pt')", + "UnitValue(1, 'zz').convert('pt')", + "UnitValue(1, 'zz') + 1", + "UnitValue(1, 'in') + UnitValue(1, 'zz')", + "UnitValue('bad') == 0", + "1 > UnitValue('bad')", + "+UnitValue('bad')", + "-UnitValue('bad')", + "~UnitValue('bad')", + "!UnitValue('bad')", + "UnitValue('bad') + 'x'", + "'x' < UnitValue('bad')", + "UnitValue('bad') == null", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } +} + +#[test] +fn as_leaves_the_object_and_convert_changes_it() { + let mut r = realm(); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.as('pt'), String(u)].join()"), "72,1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.convert('pt'), String(u)].join()"), "true,72 pt"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'in').as('furlong')"), "Error"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.convert('furlong'); } catch (e) {} String(u)"), "1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.type = 'furlong'; } catch (e) {} String(u)"), "1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); u.type = 'points'; u.value = 3; String(u)"), "3 pt"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'in').value = NaN"), "RangeError"); + assert_eq!(error_name(&mut r, "UnitValue.prototype.as.call({}, 'pt')"), "TypeError"); +} + +#[test] +fn pixels_and_percentages_convert_through_the_base() { + let mut r = realm(); + assert_eq!(number(&mut r, "UnitValue(72, 'px').as('in')"), 1.0); + assert_eq!(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(0.75, 'pt'); p.as('pt')"), 7.5); + close(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(1/96, 'in'); p.as('in')"), 10.0 / 96.0, "10 px at 96 per inch"); + assert_eq!(text(&mut r, "String(UnitValue.baseUnit)"), "1 pt"); + assert_eq!(number(&mut r, "var p = UnitValue(40, '%'); p.baseUnit = UnitValue(10, 'ft'); p.as('ft')"), 4.0); + assert_eq!(number(&mut r, "var m = UnitValue(10, 'm'); m.baseUnit = UnitValue(1, 'km'); m.as('%')"), 1.0); + assert_eq!(number(&mut r, "var p = UnitValue(3, 'px'); p.baseUnit = UnitValue(2, 'pt'); p.as('%')"), 300.0); + assert_eq!(number(&mut r, "var p = UnitValue(50, '%'); p.as('px')"), 0.5); + let class = "var before = UnitValue(1, 'in'); UnitValue.baseUnit = UnitValue(0.5, 'pt'); \ + var after = UnitValue(1, 'in'); var r = [before.as('px'), after.as('px'), String(UnitValue.baseUnit.type)]; \ + UnitValue.baseUnit = null; r.push(UnitValue(1, 'in').as('px')); r.join()"; + assert_eq!(text(&mut r, class), "72,144,pt,72", "the class base applies to objects made after it is set, and null restores it"); + assert_eq!(number(&mut r, "var p = UnitValue(1, 'in'); p.baseUnit = UnitValue(1, 'cm'); p.baseUnit = null; p.as('px')"), 72.0); + let large = "var p = UnitValue(100, '%'); p.baseUnit = UnitValue(1e308, 'pt'); var q = UnitValue(2, 'px'); \ + q.baseUnit = UnitValue(1e308, 'pt'); var l = UnitValue(1e308, 'km'); l.baseUnit = UnitValue(1e300, 'pt'); \ + [p.as('pt'), q.as('in'), l.as('px')].join()"; + let got: Vec = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect(); + close(got[0], 1e308, "100% of a large base"); + close(got[1], 1e308 / 72.0 * 2.0, "2 px of a large base in inches"); + close(got[2], 1e308 / 1e300 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base"); +} + +#[test] +fn a_base_must_be_a_length_greater_than_zero() { + let mut r = realm(); + for base in ["UnitValue(0, 'pt')", "UnitValue(-1, 'pt')", "UnitValue(1, 'px')", "UnitValue(1, '%')", "UnitValue(1, 'zz')"] { + assert_eq!(error_name(&mut r, &format!("UnitValue.baseUnit = {base}")), "RangeError", "{base}"); + assert_eq!(error_name(&mut r, &format!("UnitValue(1, 'px').baseUnit = {base}")), "RangeError", "{base}"); + } + assert_eq!(error_name(&mut r, "UnitValue.baseUnit = 5"), "RangeError"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'px').baseUnit = '1 pt'"), "RangeError"); + assert_eq!(number(&mut r, "UnitValue(1, 'in').as('px')"), 72.0, "a refused base leaves the class base as it was"); +} + +#[test] +fn arithmetic_gives_a_new_unit_value_in_the_left_unit() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(1, 'm') + UnitValue(10, 'cm')", "1.1 m"), + ("UnitValue(10, 'cm') + UnitValue(1, 'm')", "110 cm"), + ("UnitValue(10, 'cm') * 20", "200 cm"), + ("20 * UnitValue(10, 'cm')", "200 cm"), + ("10 - UnitValue(3, 'pt')", "7 pt"), + ("UnitValue(10, 'pt') - 3", "7 pt"), + ("20 / UnitValue(4, 'pt')", "5 pt"), + ("UnitValue(20, 'pt') / 4", "5 pt"), + ("UnitValue(7, 'pt') % 4", "3 pt"), + ("UnitValue(1, 'in') - UnitValue(36, 'pt')", "0.5 in"), + ] { + assert_eq!(text(&mut r, &format!("String({source})")), want, "{source}"); + } + assert_eq!(text(&mut r, "var u = UnitValue(1, 'pt'); u += 2; String(u)"), "3 pt", "compound assignment uses the operator"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); var v = u + 1; String(u)"), "1 in", "the operands do not change"); + assert_eq!(text(&mut r, "var u = UnitValue(2, 'px'); u.baseUnit = UnitValue(1, 'mm'); (u * 3).as('mm') + ''"), "6", "the result keeps the base"); + assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript"); +} + +#[test] +fn comparisons_use_the_numbers_and_greater_is_the_negation() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(98, 'cm') < UnitValue(1, 'm')", true), + ("UnitValue(98, 'cm') < 1", false), + ("UnitValue(98, 'cm') == 98", true), + ("98 == UnitValue(98, 'cm')", true), + ("UnitValue(1, 'in') == UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') != UnitValue(72, 'pt')", false), + ("UnitValue(1, 'in') === UnitValue(72, 'pt')", false), + ("var u = UnitValue(1, 'in'); u === u", true), + ("UnitValue(1, 'in') <= UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') >= UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') > UnitValue(72, 'pt')", false), + ("UnitValue(1, 'in') > UnitValue(71, 'pt')", true), + ("UnitValue(1, 'in') >= UnitValue(73, 'pt')", false), + ("2 > UnitValue(1, 'pt')", true), + ("2 >= UnitValue(3, 'pt')", false), + ] { + assert_eq!(boolean(&mut r, source), want, "{source}"); + } + for statement in [ + "UnitValue(1, 'pt') < NaN", + "UnitValue(1, 'pt') > NaN", + "NaN == UnitValue(1, 'pt')", + "UnitValue(1, 'pt') < Infinity", + "UnitValue(1, 'in') < UnitValue(1, 'zz')", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } +} + +#[test] +fn unary_operators_use_the_number() { + let mut r = realm(); + assert_eq!(text(&mut r, "var u = UnitValue(2.5, 'pt'); [+u, -u, ~u, !u, !UnitValue(0, 'pt'), typeof u].join()"), "2.5,-2.5,-3,true,false,object"); +} + +#[test] +fn results_that_are_not_finite_and_division_by_zero_throw() { + let mut r = realm(); + for statement in [ + "UnitValue(1e308, 'pt') * 10", + "UnitValue(1, 'pt') / 0", + "1 / UnitValue(0, 'pt')", + "UnitValue(1, 'pt') % 0", + "UnitValue(1, 'pt') + NaN", + "UnitValue(1e308, 'mi').as('pt')", + "UnitValue(1, 'pt') + UnitValue(1e308, 'mi')", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } + assert_eq!(number(&mut r, "UnitValue(1e300, 'pt').as('mi') * 0"), 0.0); + close(number(&mut r, "UnitValue(1e307, 'km').as('mi')"), 1e307 * 1000.0 / 1609.344, "a large value that fits after the division"); +} + +#[test] +fn a_realm_without_unit_values_keeps_the_standard_operators() { + let mut r = Realm::new(); + assert_eq!(text(&mut r, "typeof UnitValue"), "undefined"); + let mut r = realm(); + let plain = "var o = {valueOf: function () { return 4; }}; [o + 1, o * 2, o < 5, o == 4].join()"; + assert_eq!(text(&mut r, plain), "5,8,true,true", "other objects use their valueOf"); + let named = "function P() {} P.prototype['+'] = function () { return 'called'; }; String(new P() + 1)"; + assert_eq!(text(&mut r, named), "[object Object]1", "a method named for an operator is not called"); +} + +#[test] +fn hostile_input_ends_in_an_error_or_a_limit() { + let mut r = realm(); + let long = "var s = 'pt'; for (var i = 0; i < 17; i++) s += s; "; + assert_eq!(text(&mut r, &format!("{long} UnitValue(1, s).type")), "?"); + assert_eq!(text(&mut r, &format!("{long} UnitValue('1 ' + s).type")), "?"); + assert_eq!(error_name(&mut r, &format!("{long} UnitValue(1, 'in').as(s)")), "Error"); + let loop_text = "var o = {toString: function () { return String(UnitValue(o)); }}; UnitValue(o)"; + match r.run(loop_text) { + Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"), + other => panic!("{other:?}"), + } + let value_of = "var o = {valueOf: function () { return UnitValue(1, 'pt') * o; }}; UnitValue(1, 'pt') * o"; + match r.run(value_of) { + Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"), + other => panic!("{other:?}"), + } + assert_eq!(text(&mut r, "String(UnitValue(3, 'pt'))"), "3 pt", "the realm runs on"); +} + +#[test] +fn unit_values_survive_a_collection() { + let mut r = realm(); + r.run("var keep = UnitValue(2, 'in'); for (var i = 0; i < 1000; i++) UnitValue(i, 'pt');").unwrap(); + r.collect_garbage(); + assert_eq!(text(&mut r, "String(keep + UnitValue(72, 'pt')) + ' ' + String(UnitValue(1, 'pc'))"), "3 in 1 pc"); +} + +#[test] +fn each_measurement_counts_toward_the_heap() { + let mut r = realm(); + // The growth from 100 objects to 200, so the script's own code and strings cancel out. + let mut per_hundred = |make: &str| { + let mut grown = |count: usize| { + r.run("var kept = [];").unwrap(); + let before = r.collect_garbage(); + r.run(&format!("for (var i = 0; i < {count}; i++) kept.push({make});")).unwrap(); + r.collect_garbage() - before + }; + grown(200) - grown(100) + }; + // The first runs also leave bindings and names the later ones reuse. + per_hundred("{}"); + let plain = per_hundred("{}"); + let measures = per_hundred("UnitValue(i, 'pt')"); + assert_eq!(measures - plain, 100 * crate::heap::UNIT_VALUE_BYTES); +} + +#[test] +fn a_second_install_changes_nothing() { + let mut r = realm(); + r.run("UnitValue.baseUnit = UnitValue(1, 'mm'); var Kept = UnitValue;").unwrap(); + r.add_unit_values().unwrap(); + assert!(boolean(&mut r, "Kept === UnitValue && UnitValue(1, 'mm').as('px') === 1")); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..2da5bbb538 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2727,6 +2727,27 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`UnitValue` holds a measurement: a number and a unit +(https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/). Scripts make one +with or without `new`, as `UnitValue(12, 'pt')`, `UnitValue('12 pt')` or `UnitValue(other)` (a copy). The units are +`in`, `ft`, `yd`, `mi`, `mm`, `cm`, `m`, `km`, `pt`, `pc`, `tpt`, `tpc`, `ci`, `px` and `%`, each also written as its +singular or plural name (`inch`, `inches`, `traditional point`); `type` gives the abbreviation. `as(unit)` gives the +number in another unit and `convert(unit)` changes the object to it and returns `true`. A pixel is one `baseUnit` and +100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets +it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation, +such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and +give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit and the result is in +the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and +`>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~` +inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators, +work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or +longer than 64 characters), and a number that is not finite make an object whose `type` is `?` and whose `value` is +0, which prints as `UnitValue 0.00000`; converting it, using it with any of these operators, a result that is not finite (a division +by 0 included) and a comparison with a number that is not finite throw a `RangeError`; an unknown unit given to `as`, `convert` or `type` throws an +`Error` and leaves the object as it was; `value` takes only a finite number; and `baseUnit` takes only `null` or a +length greater than 0 (not pixels or percentages). Two units of length convert through their exact ratio to the inch, +so `UnitValue(1, 'in').as('pt')` is exactly 72. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3d8f84381f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1028,6 +1028,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: `UnitValue` measurements ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/)): the constructor with a number and a unit, with text such as `12 pt`, or with another `UnitValue`; the length units, `px` and `%` by abbreviation, singular or plural; `value`, `type` and `baseUnit` on the class and on each object; `as` and `convert`; and the arithmetic, comparison and unary operators with a number or another `UnitValue`, the right one converted to the left one's unit, with `>` and `>=` as the negations of `<=` and `<`. Realms without `UnitValue` keep the standard operators. VectorCraft's own rules: an invalid object has `type` `?` and value 0, and converting it or using it with these operators, a result that is not finite (a division by 0 included), a comparison with a number that is not finite and a base that is not a length greater than 0 throw. `crates/js/src/unit_value_tests.rs`, `crates/engine/src/tests/script_dollar.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. From 7e5b421db26f7eb25e5be6b8813f5a7b5610e023 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:25:38 -0800 Subject: [PATCH 038/126] Scripts: UnitValue pixels and percentages use the left object's base With two UnitValues and a left one in px or %, the right one is now converted with the left one's baseUnit, so a 1 px value with a 2 pt base plus 1 in gives 37 px. Conversions keep their intermediate values in range, so a result that is a finite number no longer fails because a step on the way overflows or reaches 0. --- crates/js/src/unit_value.rs | 89 +++++++++++++++++++++++-------- crates/js/src/unit_value_tests.rs | 35 ++++++++++++ docs/mcp.md | 4 +- 3 files changed, 105 insertions(+), 23 deletions(-) diff --git a/crates/js/src/unit_value.rs b/crates/js/src/unit_value.rs index 03a33ab3e6..f971e27b07 100644 --- a/crates/js/src/unit_value.rs +++ b/crates/js/src/unit_value.rs @@ -12,8 +12,8 @@ //! //! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and //! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in -//! its unit; with two, the right one is converted to the left one's unit first and the result is in -//! the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the +//! its unit; with two, the right one is converted to the left one's unit first, with the left one's +//! base for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the //! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its //! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not //! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all @@ -141,16 +141,45 @@ fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 { a } -/// `value` in unit `from`, given in unit `to`; both have a length. -fn between(value: f64, from: (u64, u64), to: (u64, u64)) -> f64 { +/// The ratio of a length in unit `from` to the same length in unit `to`, as a reduced fraction. +fn ratio(from: Unit, to: Unit) -> (f64, f64) { + let (from, to) = (from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))); // The products stay below 2^53, so the ratio's terms are exact. let (n, d) = (from.0 * to.1, from.1 * to.0); let g = greatest_common_divisor(n, d).max(1); #[allow(clippy::cast_precision_loss)] - let (n, d) = ((n / g) as f64, (d / g) as f64); - let scaled = value * n; - // A large value is divided first, so a result that is finite does not overflow on the way. - if scaled.is_finite() { scaled / d } else { value / d * n } + (((n / g) as f64), ((d / g) as f64)) +} + +/// `x` as a significand in [0.5, 1) and a power of 2; zero, infinities and NaN as themselves. +fn split(x: f64) -> (f64, i32) { + if x == 0.0 || !x.is_finite() { + return (x, 0); + } + let (x, shift) = if x.is_normal() { (x, 0) } else { (x * 2f64.powi(64), -64) }; + let bits = x.to_bits(); + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + let exponent = ((bits >> 52) & 0x7ff) as i32 - 1022; + (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), exponent + shift) +} + +/// The product of `factors` divided by each of `divisors`, in that order. Each step rounds as +/// plain multiplication and division do, but no step overflows or reaches 0 on the way, so only +/// a result outside the range of numbers is infinite or 0. +fn product(factors: &[f64], divisors: &[f64]) -> f64 { + let (mut m, mut e) = (1.0, 0); + for (&x, divide) in factors.iter().map(|x| (x, false)).chain(divisors.iter().map(|x| (x, true))) { + let (xm, xe) = split(x); + let (rm, re) = split(if divide { m / xm } else { m * xm }); + (m, e) = (rm, if divide { e - xe } else { e + xe } + re); + } + while e > 1000 { + (m, e) = (m * 2f64.powi(1000), e - 1000); + } + while e < -1000 { + (m, e) = (m * 2f64.powi(-1000), e + 1000); + } + m * 2f64.powi(e) } fn invalid(i: &mut Interp, what: &str) -> Abrupt { @@ -171,26 +200,22 @@ fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult { return Err(invalid(i, what)); }; let base = m.base; - let base_inches = base.unit.inches().unwrap_or((1, 1)); let r = match (from, to) { (a, b) if a == b => m.value, (Unit::Px, Unit::Percent) => m.value * 100.0, (Unit::Percent, Unit::Px) => m.value / 100.0, (Unit::Px | Unit::Percent, _) => { - let to = to.inches().unwrap_or((1, 1)); - let bases = if from == Unit::Px { m.value } else { m.value / 100.0 }; - // A large base is applied after the unit ratio, so a result that is finite does not - // overflow on the way. - let scaled = bases * base.value; - if scaled.is_finite() { between(scaled, base_inches, to) } else { between(bases, base_inches, to) * base.value } + let (n, d) = ratio(base.unit, to); + if from == Unit::Px { product(&[m.value, base.value, n], &[d]) } else { product(&[m.value, base.value, n], &[100.0, d]) } } (_, Unit::Px | Unit::Percent) => { - let from = from.inches().unwrap_or((1, 1)); - let lengths = between(m.value, from, base_inches); - let bases = if lengths.is_finite() { lengths / base.value } else { between(m.value / base.value, from, base_inches) }; - if to == Unit::Px { bases } else { bases * 100.0 } + let (n, d) = ratio(from, base.unit); + if to == Unit::Px { product(&[m.value, n], &[d, base.value]) } else { product(&[m.value, n, 100.0], &[d, base.value]) } + } + (_, _) => { + let (n, d) = ratio(from, to); + product(&[m.value, n], &[d]) } - (_, _) => between(m.value, from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))), }; if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) } } @@ -478,7 +503,29 @@ pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsRe let Some(unit) = l.unit else { return Err(invalid(i, what)); }; - let y = convert(i, &r, unit, what)?; + // Pixels and percentages of the left object are measured with its own base. + let y = match unit { + Unit::Px | Unit::Percent if r.base != l.base || !matches!(r.unit, Some(Unit::Px | Unit::Percent)) => match r.unit { + Some(from @ (Unit::Px | Unit::Percent)) => { + let (n, d) = ratio(r.base.unit, l.base.unit); + let mut factors = vec![r.value, r.base.value, n]; + let mut divisors = vec![d, l.base.value]; + if from == Unit::Percent { + divisors.push(100.0); + } + if unit == Unit::Percent { + factors.push(100.0); + } + let y = product(&factors, &divisors); + if !y.is_finite() { + return Err(not_finite(i, what)); + } + y + } + _ => convert(i, &Measure { base: l.base, ..r }, unit, what)?, + }, + _ => convert(i, &r, unit, what)?, + }; (l.value, y, l) } (Some(l), None, _, Value::Number(n)) => (l.value, *n, l), diff --git a/crates/js/src/unit_value_tests.rs b/crates/js/src/unit_value_tests.rs index 6e4f2ee33e..d7f3a642e8 100644 --- a/crates/js/src/unit_value_tests.rs +++ b/crates/js/src/unit_value_tests.rs @@ -38,6 +38,11 @@ fn close(got: f64, want: f64, what: &str) { assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}"); } +/// `got` is within a millionth of `want`, which is not 0, however small `want` is. +fn relative(got: f64, want: f64, what: &str) { + assert!((got / want - 1.0).abs() <= 1e-6, "{what}: {got} is not {want}"); +} + /// Each length unit with its length in inches. const LENGTHS: [(&str, f64); 13] = [ ("in", 1.0), @@ -234,6 +239,36 @@ fn arithmetic_gives_a_new_unit_value_in_the_left_unit() { assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript"); } +#[test] +fn the_left_objects_base_measures_its_pixels_and_percentages() { + let mut r = realm(); + let pair = "var l = UnitValue(1, 'px'); l.baseUnit = UnitValue(2, 'pt'); var m = UnitValue(1, 'px'); \ + m.baseUnit = UnitValue(4, 'pt'); var p = UnitValue(50, '%'); p.baseUnit = UnitValue(1, 'in');"; + assert_eq!(text(&mut r, &format!("{pair} String(l + UnitValue(1, 'in'))")), "37 px"); + assert_eq!(text(&mut r, &format!("{pair} String(l + m)")), "3 px"); + close(number(&mut r, &format!("{pair} (p + l).value")), 50.0 + 200.0 / 72.0, "2 pt as a percentage of 1 in"); + assert!(boolean(&mut r, &format!("{pair} l < m && m > l && l == UnitValue(2, 'pt')"))); + let large = "var b = UnitValue(0, 'px'); b.baseUnit = UnitValue(1e308, 'pt'); var c = UnitValue(1e300, 'px'); \ + c.baseUnit = UnitValue(1e10, 'pt'); [(b + UnitValue(1e304, 'km')).value, (b + c).value].join()"; + let got: Vec = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect(); + close(got[0], 1e304 / 1e308 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base"); + close(got[1], 1e300 / 1e308 * 1e10, "large pixels of one large base in pixels of another"); + let small = "var s = UnitValue(0, 'px'); s.baseUnit = UnitValue(1e-300, 'pt'); var t = UnitValue(1e-200, 'px'); \ + t.baseUnit = UnitValue(1e-200, 'pt'); (s + t).value"; + let units = "var u = UnitValue(0, 'px'); u.baseUnit = UnitValue(1e20, 'pt'); var v = UnitValue(1e308, 'px'); \ + v.baseUnit = UnitValue(1e10, 'km'); (u + v).value"; + close(number(&mut r, units), 1e298 * 1000.0 * 5000.0 / 127.0 * 72.0, "large pixels of a base in a larger unit"); + let apart = "var w = UnitValue(0, 'px'); w.baseUnit = UnitValue(7e-16, 'km'); var x = UnitValue(1e-20, 'px'); \ + x.baseUnit = UnitValue(1e308, 'pt'); (w + x).value"; + close(number(&mut r, apart), 1e288 / (1000.0 * 5000.0 / 127.0 * 72.0) / 7e-16, "bases too far apart for their ratio"); + relative(number(&mut r, small), 1e-100, "small pixels of one small base in pixels of another"); + let tiny = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-200, 'km'); var z = UnitValue(1e-320, 'px'); (y + z).value"; + relative(number(&mut r, tiny), 1e-320 * 1e200 / (1000.0 * 5000.0 / 127.0 * 72.0), "a tiny value in pixels of a tiny base"); + let tinier = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-320, 'pt'); var z = UnitValue(1e-320, 'px'); \ + z.baseUnit = UnitValue(1e-10, 'pt'); (y + z).value"; + relative(number(&mut r, tinier), 1e-10, "a tiny value of a small base in pixels of a tiny base"); +} + #[test] fn comparisons_use_the_numbers_and_greater_is_the_negation() { let mut r = realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 2da5bbb538..e3721e054f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2736,8 +2736,8 @@ number in another unit and `convert(unit)` changes the object to it and returns 100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation, such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and -give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit and the result is in -the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and +give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit, with the left one's +`baseUnit` for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and `>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~` inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators, work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or From 7d3094afe6b42f7b0d538966b9a9c0834fabcb01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:43:20 -0800 Subject: [PATCH 039/126] Scripts: .js scripts run let, const, arrows, templates, default and rest parameters and spread vectorcraft-js gains Options::es2015, which reads and runs these ECMAScript 2015 forms: let and const with block scope and their temporal dead zone, a new let binding for each loop iteration, function declarations scoped to their block (with the Annex B.3.3 variable outside strict mode code), arrow functions, template literals and tagged templates, default and rest parameters, and spread in array literals, calls and new. Spread reads arrays, strings by code point and objects with a length, by index, and throws a TypeError for anything else until iterators are added. Eval code outside strict mode code cannot declare a var that clashes with a let or const around it, or with a parameter inside a default value. Spread, template objects and the new scopes take fuel and count against the heap limit, and nested arrows and templates count against the depth limit. script.run sets the option for a .js file; eval, Function, #include files, $.evalFile and a kept #targetengine read code the way the running script does. A .jsx file and a source string stay ES5.1. The test262 runner gains an ES2015 subset run, read without and with the option. docs/mcp.md and docs/target-app-parity.md describe the new forms. --- crates/engine/src/script/include.rs | 17 +- crates/engine/src/script/mod.rs | 9 +- crates/engine/src/tests/script_run.rs | 34 ++ crates/js/src/ast.rs | 57 +++ crates/js/src/builtins.rs | 2 +- crates/js/src/bytecode.rs | 81 +++- crates/js/src/compiler.rs | 549 +++++++++++++++++++++--- crates/js/src/es2015_tests.rs | 466 +++++++++++++++++++++ crates/js/src/heap.rs | 32 +- crates/js/src/interp.rs | 577 ++++++++++++++++++++++++-- crates/js/src/interp_tests.rs | 8 + crates/js/src/lexer.rs | 95 ++++- crates/js/src/lib.rs | 23 +- crates/js/src/parser.rs | 503 ++++++++++++++++++++-- crates/js/src/realm.rs | 6 + crates/js/src/token.rs | 15 + crates/js/src/xml.rs | 2 +- crates/js/tests/test262.rs | 169 +++++++- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 20 files changed, 2507 insertions(+), 149 deletions(-) create mode 100644 crates/js/src/es2015_tests.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..a024949a35 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -217,6 +217,15 @@ pub(crate) struct Files { levels: usize, /// The files `$.evalFile` is running, the script first. frames: Vec, + /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. + es2015: bool, +} + +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as +/// ECMAScript 5.1 with the ExtendScript extensions. +pub(crate) fn es2015_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -311,9 +320,15 @@ impl Files { chain: real.into_iter().collect(), levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], + es2015: es2015_script(path), } } + /// The options a file of this run is parsed with, preprocessor lines aside. + pub(crate) fn options(&self) -> Options { + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + } + /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. pub(crate) fn jsinclude_env() -> Vec { #[cfg(test)] @@ -456,7 +471,7 @@ impl Files { return Ok(()); } let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column }; - let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() }; + let options = Options { preprocessor_lines: true, ..self.options() }; let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?; let mut cursor = 0usize; for d in &program.directives { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..a01453a627 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1475,7 +1475,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { host.placed(error, f.file, f.line, f.column) } else { error } })?; // A file without preprocessor lines is parsed here first, so its syntax error names its place. - let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() }; + let options = host.files.borrow().options(); if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) { host.files.borrow_mut().end_eval(); let (_, file, line, column) = expanded.map.locate(e.line, e.column); @@ -1967,11 +1967,16 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read + // code the way the script does. + let es2015 = include::es2015_script(request.file.as_deref()); + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; + // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + realm.set_es2015(es2015); realm } None => { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..7b0e4bc2f8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -297,6 +297,40 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n"); + write("more.jsx", "let m = `m${k}`;\nm;\n"); + let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n"; + let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap(); + assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}"); + let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap(); + assert_eq!(upper["log"], json!([1]), "{upper}"); + for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "const c = 1;").unwrap_err().to_string().contains("SyntaxError")); + // A named engine reads each run the way that run's script does. + s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap(); + let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap(); + assert_eq!(modern["log"], json!([2]), "{modern}"); + let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); + assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); + let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); + assert_eq!(legacy["log"], json!([3]), "{legacy}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 8d9ffc06c0..c015e3fa38 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -200,6 +200,40 @@ pub enum Expr { object: ExprId, predicate: ExprId, }, + /// An arrow function. + Arrow(FunctionId), + /// A template literal: its pieces (one more than its substitutions) and its substitutions, + /// in source order. + Template { + quasis: Vec, + exprs: Vec, + }, + /// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the + /// substitutions. + TaggedTemplate { + tag: ExprId, + quasis: Vec, + exprs: Vec, + }, + /// `...expression` in an array literal or an argument list, and as the last of an arrow + /// function's parenthesized parameters while they are read. + Spread(ExprId), +} + +/// A piece of a template literal's text between its substitutions. +#[derive(Clone, Debug, PartialEq)] +pub struct TemplatePiece { + /// The text with its escapes read. + pub cooked: Vec, + /// The text as written. + pub raw: Vec, +} + +/// Which lexical declaration a name has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LexKind { + Let, + Const, } /// A piece of an XML literal, in source order. @@ -247,12 +281,17 @@ pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), Expr(ExprId), + /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. + Lexical(LexKind, Name), } #[derive(Clone, Debug, PartialEq)] pub enum ForInit { Var(Vec), Expr(ExprId), + /// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let` + /// binding for each iteration. + Lexical(LexKind, Vec), } #[derive(Clone, Debug, PartialEq)] @@ -272,6 +311,8 @@ pub struct CatchClause { #[derive(Clone, Debug, PartialEq)] pub enum Stmt { Var(Vec), + /// `let` or `const` declarations (a `const` always has an initializer). + Lexical(LexKind, Vec), FunctionDecl(FunctionId), Expr(ExprId), Block(Vec), @@ -334,13 +375,20 @@ pub enum FunctionKind { Expression, Getter, Setter, + /// An arrow function; one with an expression body has a body of one `return` statement. + Arrow, } #[derive(Clone, Debug, PartialEq)] pub struct Function { pub kind: FunctionKind, pub name: Option, + /// The parameters before a rest parameter. pub params: Vec, + /// Each parameter's default value, in the order of `params` (empty when none has one). + pub defaults: Vec>, + /// The rest parameter (`...name`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -348,6 +396,13 @@ pub struct Function { pub span: Span, } +impl Function { + /// The parameters are plain names: no default value and no rest parameter. + pub fn simple_params(&self) -> bool { + self.rest.is_none() && self.defaults.iter().all(Option::is_none) + } +} + /// The arenas of a parsed script. #[derive(Clone, Debug, Default, PartialEq)] pub struct Ast { @@ -412,6 +467,8 @@ pub struct Program { /// Its preprocessor lines, in source order. pub directives: Vec, pub(crate) lines: crate::LineTable, + /// It was read with [`crate::Options::es2015`]. + pub(crate) es2015: bool, } impl Program { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..f2c02bdf4c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; interp.charge_code(&code, 0)?; - let env = interp.global_env; + let env = interp.global_scope(); interp.make_closure(code, env).map(Value::Object) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 6992fd5606..28db7edf3d 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -178,6 +178,49 @@ pub(crate) enum Op { ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, + /// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet + /// initialized, and its function declarations. + PushBlock(u32), + /// Replaces the current environment with a copy of it, for a `for` loop's next iteration. + CopyEnv, + /// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or + /// a parameter of a function with default or rest parameters. + InitVar(u32), + /// Pushes the value of the parameter `names[i]` of the running function, initialized or not. + LoadParam(u32), + /// Ends the parameters of a function with default or rest parameters: enters the environment + /// of its body's variables and function declarations, and of its `let` and `const` names. + BodyEnv, + /// `value` → nothing: assigns the function declared in a block outside strict mode code to + /// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3). + AnnexB(u32), + /// `array value` → `array`, with the elements of the value appended (spread). + ArraySpread, + /// `function this array` → result: a call with the array's elements as its arguments, a + /// direct eval when `eval` is true and the function is the global `eval`. + CallSpread(bool), + /// `function array` → the new object, constructed with the array's elements as arguments. + NewSpread, + /// `value` → its string (a template literal's substitution). + ToStr, + /// Pushes the template object of `templates[i]`, the same object for each evaluation. + TemplateObject(u32), +} + +/// The names a block declares, entered with [`Op::PushBlock`]. +#[derive(Debug, Default)] +pub(crate) struct BlockScope { + /// The `let` and `const` names, each with whether it is a `const`. + pub(crate) lets: Vec<(Key, bool)>, + /// The function declarations: their names and indices in `functions`. + pub(crate) funcs: Vec<(Key, u32)>, +} + +/// A tagged template's strings: as read and as written. +#[derive(Debug)] +pub(crate) struct Template { + pub(crate) cooked: Vec, + pub(crate) raw: Vec, } /// What code is: a function body, a script, or eval code. @@ -239,6 +282,23 @@ pub(crate) struct Code { pub(crate) source: Rc, /// Where the function's text starts and ends in the source. pub(crate) span: (u32, u32), + /// The block scopes [`Op::PushBlock`] enters. + pub(crate) scopes: Vec, + /// The scope of the `let` and `const` names at the top of the body, script or eval code. + pub(crate) top_scope: Option, + /// The tagged templates [`Op::TemplateObject`] makes objects of. + pub(crate) templates: Vec